answer
stringlengths
17
10.2M
package com.github.lgooddatepicker.components; import static org.junit.Assert.assertTrue; import com.github.lgooddatepicker.TestHelpers; import com.github.lgooddatepicker.components.DatePickerSettings.DateArea; import com.github.lgooddatepicker.zinternaltools.HighlightInformation; import java.awt.Color; import java.awt.event.MouseEvent; import java.lang.reflect.InvocationTargetException; import java.time.LocalDate; import java.time.Month; import java.time.YearMonth; import java.time.temporal.ChronoField; import java.util.ArrayList; import java.util.Locale; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.MenuElement; import org.junit.Test; public class TestCalendarPanel { @Test(expected = Test.None.class /* no exception expected */) public void TestCustomClockCalenderPanel() { CalendarPanel panel = new CalendarPanel(); java.time.YearMonth defaultDateNeverNull = panel.getDisplayedYearMonth(); assertTrue("displayedYearMonth may never be null", defaultDateNeverNull != null); assertTrue( "Year must be the year of today", defaultDateNeverNull.getYear() == LocalDate.now().getYear()); assertTrue( "Month must be the month of today", defaultDateNeverNull.getMonthValue() == LocalDate.now().getMonthValue()); panel = new CalendarPanel(new DatePicker()); defaultDateNeverNull = panel.getDisplayedYearMonth(); assertTrue("displayedYearMonth may never be null", defaultDateNeverNull != null); assertTrue( "Year must be the year of today", defaultDateNeverNull.getYear() == LocalDate.now().getYear()); assertTrue( "Month must be the month of today", defaultDateNeverNull.getMonthValue() == LocalDate.now().getMonthValue()); DatePickerSettings settings = new DatePickerSettings(Locale.ENGLISH); settings.setClock(TestHelpers.getClockFixedToInstant(1995, Month.OCTOBER, 31, 0, 0)); panel = new CalendarPanel(settings); defaultDateNeverNull = panel.getDisplayedYearMonth(); assertTrue("displayedYearMonth may never be null", defaultDateNeverNull != null); assertTrue("Year must be the year 1995", defaultDateNeverNull.getYear() == 1995); assertTrue("Month must be the month October", defaultDateNeverNull.getMonth() == Month.OCTOBER); } @Test(expected = Test.None.class /* no exception expected */) public void TestMouseHoverCalendarPanel() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { DatePickerSettings settings = new DatePickerSettings(Locale.ENGLISH); CalendarPanel panel = new CalendarPanel(settings); final Color generalHighlight = settings.getColor(DatePickerSettings.DateArea.BackgroundCalendarPanelLabelsOnHover); final Color yearMonthBackground = settings.getColor(DatePickerSettings.DateArea.BackgroundMonthAndYearMenuLabels); final Color yearMonthText = settings.getColor(DatePickerSettings.DateArea.TextMonthAndYearMenuLabels); verifyLabelHover( panel, "labelMonth", yearMonthBackground, yearMonthText, generalHighlight, yearMonthText); verifyLabelHover( panel, "labelYear", yearMonthBackground, yearMonthText, generalHighlight, yearMonthText); final Color todayLabelBackground = settings.getColor(DatePickerSettings.DateArea.BackgroundTodayLabel); final Color todayLabelText = settings.getColor(DatePickerSettings.DateArea.TextTodayLabel); verifyLabelHover( panel, "labelSetDateToToday", todayLabelBackground, todayLabelText, generalHighlight, todayLabelText); final Color clearLabelBackground = settings.getColor(DatePickerSettings.DateArea.BackgroundClearLabel); final Color clearLabelText = settings.getColor(DatePickerSettings.DateArea.TextClearLabel); verifyLabelHover( panel, "labelClearDate", clearLabelBackground, clearLabelText, generalHighlight, clearLabelText); } @Test(expected = Test.None.class /* no exception expected */) public void TestCustomMouseHoverColorCalendarPanel() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { DatePickerSettings settings = new DatePickerSettings(Locale.ENGLISH); settings.setColor(DatePickerSettings.DateArea.BackgroundCalendarPanelLabelsOnHover, Color.red); settings.setColor(DatePickerSettings.DateArea.TextCalendarPanelLabelsOnHover, Color.yellow); CalendarPanel panel = new CalendarPanel(settings); final Color generalHighlight = Color.red; final Color generalHighlightText = Color.yellow; final Color yearMonthBackground = settings.getColor(DatePickerSettings.DateArea.BackgroundMonthAndYearMenuLabels); final Color yearMonthText = settings.getColor(DatePickerSettings.DateArea.TextMonthAndYearMenuLabels); verifyLabelHover( panel, "labelMonth", yearMonthBackground, yearMonthText, generalHighlight, generalHighlightText); verifyLabelHover( panel, "labelYear", yearMonthBackground, yearMonthText, generalHighlight, generalHighlightText); final Color todayLabelBackground = settings.getColor(DatePickerSettings.DateArea.BackgroundTodayLabel); final Color todayLabelText = settings.getColor(DatePickerSettings.DateArea.TextTodayLabel); verifyLabelHover( panel, "labelSetDateToToday", todayLabelBackground, todayLabelText, generalHighlight, generalHighlightText); final Color clearLabelBackground = settings.getColor(DatePickerSettings.DateArea.BackgroundClearLabel); final Color clearLabelText = settings.getColor(DatePickerSettings.DateArea.TextClearLabel); verifyLabelHover( panel, "labelClearDate", clearLabelBackground, clearLabelText, generalHighlight, generalHighlightText); } void verifyLabelHover( CalendarPanel panel, String labelname, Color defaultBackground, Color defaultText, Color highlightBackground, Color highlightText) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { JLabel labeltoverify = (JLabel) TestHelpers.readPrivateField(CalendarPanel.class, panel, labelname); assertTrue( labelname + " has wrong background color: " + labeltoverify.getBackground().toString(), labeltoverify.getBackground().equals(defaultBackground)); assertTrue( labelname + " has wrong text color: " + labeltoverify.getForeground().toString(), labeltoverify.getForeground().equals(defaultText)); MouseEvent testEvent = new MouseEvent(labeltoverify, MouseEvent.MOUSE_ENTERED, 0, 0, 0, 0, 0, false); TestHelpers.accessPrivateMethod( java.awt.Component.class, "processEvent", java.awt.AWTEvent.class) .invoke(labeltoverify, testEvent); assertTrue( labelname + " has wrong background color: " + labeltoverify.getBackground().toString(), labeltoverify.getBackground().equals(highlightBackground)); assertTrue( labelname + " has wrong text color: " + labeltoverify.getForeground().toString(), labeltoverify.getForeground().equals(highlightText)); testEvent = new MouseEvent(labeltoverify, MouseEvent.MOUSE_EXITED, 0, 0, 0, 0, 0, false); TestHelpers.accessPrivateMethod( java.awt.Component.class, "processEvent", java.awt.AWTEvent.class) .invoke(labeltoverify, testEvent); assertTrue( labelname + " has wrong background color: " + labeltoverify.getBackground().toString(), labeltoverify.getBackground().equals(defaultBackground)); assertTrue( labelname + " has wrong text color: " + labeltoverify.getForeground().toString(), labeltoverify.getForeground().equals(defaultText)); } @Test(expected = Test.None.class /* no exception expected */) public void TestDateHighlightAndVetoPolicy() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { DatePickerSettings settings = new DatePickerSettings(Locale.ENGLISH); settings.setHighlightPolicy( dateToHighlight -> { if (dateToHighlight.get(ChronoField.DAY_OF_MONTH) % 2 == 0) { return new HighlightInformation(Color.green, Color.blue, "highlighted"); } return null; }); CalendarPanel panel = new CalendarPanel(settings); settings.setVetoPolicy( dateToVeto -> { final int day = dateToVeto.get(ChronoField.DAY_OF_MONTH); return (day % 5 != 0); }); panel.setDisplayedYearMonth(YearMonth.of(2021, Month.MARCH)); final Color defaultColor = settings.getColor(DateArea.CalendarBackgroundNormalDates); final Color defaultTextColor = settings.getColor(DateArea.CalendarTextNormalDates); final Color defaultVetoedColor = settings.getColor(DateArea.CalendarBackgroundVetoedDates); for (int dayLabelIdx = 0; dayLabelIdx < 42; ++dayLabelIdx) { if (dayLabelIdx < 1 || dayLabelIdx > 31) { verifyDateLabelColorAndToolTip(panel, dayLabelIdx, defaultColor, defaultTextColor, null); continue; } if (dayLabelIdx % 5 == 0) { verifyDateLabelColorAndToolTip( panel, dayLabelIdx, defaultVetoedColor, defaultTextColor, null); continue; } if (dayLabelIdx % 2 == 0) { verifyDateLabelColorAndToolTip(panel, dayLabelIdx, Color.green, Color.blue, "highlighted"); continue; } verifyDateLabelColorAndToolTip(panel, dayLabelIdx, defaultColor, defaultTextColor, null); } } void verifyDateLabelColorAndToolTip( CalendarPanel panel, int labelIdx, Color bgColor, Color textColor, String tooltip) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { ArrayList<?> labelList = (ArrayList<?>) TestHelpers.readPrivateField(CalendarPanel.class, panel, "dateLabels"); JLabel labeltoverify = (JLabel) labelList.get(labelIdx); String labelname = "DateLabel_" + labelIdx; String labelToolTip = labeltoverify.getToolTipText(); // assertTrue( // labelname + " has wrong tool tip text: " + labelToolTip, // labelToolTip != null ? labelToolTip.equals(tooltip) : tooltip == null); assertTrue( labelname + " has wrong background color: " + labeltoverify.getBackground().toString(), labeltoverify.getBackground().equals(bgColor)); assertTrue( labelname + " has wrong text color: " + labeltoverify.getForeground().toString(), labeltoverify.getForeground().equals(textColor)); } @Test(expected = Test.None.class /* no exception expected */) public void TestYearEditor() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { verifyYearEditor(YearEditorFinalizer.doneEditingButton); verifyYearEditor(YearEditorFinalizer.yearTextField); } enum YearEditorFinalizer { doneEditingButton, yearTextField } void verifyYearEditor(YearEditorFinalizer editorFinalizer) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { DatePickerSettings dateSettings = new DatePickerSettings(Locale.ENGLISH); CalendarPanel testPanel = new CalendarPanel(dateSettings); JPanel monthAndYearInnerPanel = (JPanel) TestHelpers.readPrivateField(CalendarPanel.class, testPanel, "monthAndYearInnerPanel"); JPanel yearEditorPanel = (JPanel) TestHelpers.readPrivateField(CalendarPanel.class, testPanel, "yearEditorPanel"); // monthAndYearInnerPanel invisible as default assertTrue(!monthAndYearInnerPanel.isAncestorOf(yearEditorPanel)); final String currentYear = String.valueOf(LocalDate.now().getYear()); JLabel labelYear = (JLabel) TestHelpers.readPrivateField(CalendarPanel.class, testPanel, "labelYear"); assertTrue( "Wrong text in labelYear: " + labelYear.getText(), labelYear.getText().equals(currentYear)); assertTrue( "Wrong text in yearTextField: " + labelYear.getText(), labelYear.getText().equals(currentYear)); TestHelpers.accessPrivateMethod(CalendarPanel.class, "populateYearPopupMenu").invoke(testPanel); JPopupMenu popupYear = (JPopupMenu) TestHelpers.readPrivateField(CalendarPanel.class, testPanel, "popupYear"); boolean found = false; for (MenuElement elem : popupYear.getSubElements()) { JMenuItem menuItem = (JMenuItem) elem.getComponent(); if (menuItem.getText().equals("( . . . )")) { menuItem.doClick(); found = true; break; } } assertTrue(found); // monthAndYearInnerPanel now visible assertTrue(monthAndYearInnerPanel.isAncestorOf(yearEditorPanel)); JTextField yearTextField = (JTextField) TestHelpers.readPrivateField(CalendarPanel.class, testPanel, "yearTextField"); yearTextField.setText("2005"); assertTrue( "Wrong text in labelYear: " + labelYear.getText(), labelYear.getText().equals("2005")); assertTrue( "Wrong text in labelYear: " + labelYear.getText(), !labelYear.getText().equals(currentYear)); switch (editorFinalizer) { case doneEditingButton: JButton doneEditingYearButton = (JButton) TestHelpers.readPrivateField( CalendarPanel.class, testPanel, "doneEditingYearButton"); doneEditingYearButton.doClick(); break; case yearTextField: yearTextField.postActionEvent(); break; default: assertTrue("Unknown finalizer value " + editorFinalizer, false); } // monthAndYearInnerPanel invisible after finishing editing assertTrue(!monthAndYearInnerPanel.isAncestorOf(yearEditorPanel)); } }
package ibis.ipl.impl.registry.central; import ibis.ipl.impl.IbisIdentifier; import ibis.ipl.impl.Location; import ibis.util.ThreadPool; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.log4j.Logger; final class Pool implements Runnable { static final int MAX_TRIES = 5; static final int PING_INTERVAL = 5 * 60 * 1000; static final int PING_THREADS = 5; static final int GOSSIP_INTERVAL = 120 * 60 * 1000; static final int GOSSIP_THREADS = 10; static final int PUSH_THREADS = 10; static final int CONNECT_TIMEOUT = 10 * 1000; private static final Logger logger = Logger.getLogger(Pool.class); // list of all joins, leaves, elections, etc. private final ArrayList<Event> events; // cache of election results we've seen. Optimization over searching all the // events each time an election result is requested. // map<election name, winner> private final Map<String, IbisIdentifier> elections; private final MemberSet members; // List of "suspect" ibisses we must ping private final List<IbisIdentifier> checkList; private final boolean keepNodeState; private final String name; private final ConnectionFactory connectionFactory; private int nextID; private long nextSequenceNr; private boolean ended = false; Pool(String name, ConnectionFactory connectionFactory, boolean gossip, boolean keepNodeState) { this.name = name; this.connectionFactory = connectionFactory; this.keepNodeState = keepNodeState; nextID = 0; nextSequenceNr = 0; events = new ArrayList<Event>(); elections = new HashMap<String, IbisIdentifier>(); members = new MemberSet(); checkList = new LinkedList<IbisIdentifier>(); if (gossip) { // ping iteratively new PeriodicNodeContactor(this, false, false, PING_INTERVAL, PING_THREADS); // gossip randomly new PeriodicNodeContactor(this, true, true, GOSSIP_INTERVAL, GOSSIP_THREADS); logger.info("created new central/gossiping pool " + name); } else { // central // ping iteratively new PeriodicNodeContactor(this, false, false, PING_INTERVAL, PING_THREADS); new EventPusher(this, PUSH_THREADS); logger.info("created new centralized pool " + name); } ThreadPool.createNew(this, "pool management thread"); } synchronized int getEventTime() { return events.size(); } synchronized void waitForEventTime(int time) { while (getEventTime() < time) { if (ended()) { return; } try { wait(); } catch (InterruptedException e) { // IGNORE } } } synchronized int getSize() { return members.size(); } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#ended() */ synchronized boolean ended() { return ended; } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#getName() */ String getName() { return name; } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#join(byte[], byte[], * ibis.ipl.impl.Location) */ synchronized IbisIdentifier join(byte[] implementationData, byte[] clientAddress, Location location) throws Exception { if (ended()) { throw new Exception("Pool already ended"); } String id = Integer.toString(nextID); nextID++; IbisIdentifier identifier = new IbisIdentifier(id, implementationData, clientAddress, location, name); members.add(new Member(identifier)); logger.info(identifier + " joined pool \"" + name + "\" now " + members.size() + " members"); events.add(new Event(events.size(), Event.JOIN, identifier, null)); notifyAll(); return identifier; } void writeBootstrap(DataOutputStream out) throws IOException { Member[] peers = getRandomMembers(Protocol.BOOTSTRAP_LIST_SIZE); out.writeInt(peers.length); for (Member member : peers) { member.ibis().writeTo(out); } } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#leave(ibis.ipl.impl.IbisIdentifier) */ synchronized void leave(IbisIdentifier identifier) throws Exception { if (!members.remove(identifier.myId)) { logger.error("unknown ibis " + identifier + " tried to leave"); throw new Exception("ibis unknown: " + identifier); } logger.info(identifier + " left pool \"" + name + "\" now " + members.size() + " members"); events.add(new Event(events.size(), Event.LEAVE, identifier, null)); notifyAll(); Iterator<Entry<String, IbisIdentifier>> iterator = elections.entrySet() .iterator(); while (iterator.hasNext()) { Entry<String, IbisIdentifier> entry = iterator.next(); if (entry.getValue().equals(identifier)) { iterator.remove(); events.add(new Event(events.size(), Event.UN_ELECT, identifier, entry.getKey())); notifyAll(); } } if (members.size() == 0) { ended = true; logger.info("pool " + name + " ended"); notifyAll(); } } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#dead(ibis.ipl.impl.IbisIdentifier) */ synchronized void dead(IbisIdentifier identifier) { if (!members.remove(identifier.myId)) { logger.warn(identifier + " dead, but not in pool (anymore)"); return; } logger.info(identifier + " left pool \"" + name + "\" now " + members.size() + " members"); events.add(new Event(events.size(), Event.DIED, identifier, null)); notifyAll(); Iterator<Map.Entry<String, IbisIdentifier>> iterator = elections .entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, IbisIdentifier> entry = iterator.next(); if (entry.getValue().equals(identifier)) { iterator.remove(); events.add(new Event(events.size(), Event.UN_ELECT, identifier, entry.getKey())); notifyAll(); } } if (members.size() == 0) { ended = true; logger.info("pool " + name + " ended"); notifyAll(); } } synchronized Event[] getEvents(int startTime, int maxSize) { // logger.debug("getting events, startTime = " + startTime // + ", maxSize = " + maxSize + // ", event time = " + events.size()); int resultSize = events.size() - startTime; if (resultSize > maxSize) { resultSize = maxSize; } if (resultSize < 0) { return new Event[0]; } return events.subList(startTime, startTime + resultSize).toArray( new Event[0]); } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#elect(java.lang.String, * ibis.ipl.impl.IbisIdentifier) */ synchronized IbisIdentifier elect(String election, IbisIdentifier candidate) { IbisIdentifier winner = elections.get(election); if (winner == null) { // Do the election now. The caller WINS! :) winner = candidate; elections.put(election, winner); logger.debug(winner + " won election \"" + election + "\" in pool \"" + name + "\""); events.add(new Event(events.size(), Event.ELECT, winner, election)); notifyAll(); } return winner; } synchronized long getSequenceNumber() { return nextSequenceNr++; } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#maybeDead(ibis.ipl.impl.IbisIdentifier) */ synchronized void maybeDead(IbisIdentifier identifier) { // add to todo list :) checkList.add(identifier); notifyAll(); } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#signal(java.lang.String, * ibis.ipl.impl.IbisIdentifier[]) */ synchronized void signal(String signal, IbisIdentifier[] victims) { ArrayList<IbisIdentifier> result = new ArrayList<IbisIdentifier>(); for (IbisIdentifier victim : victims) { if (members.contains(victim.myId)) { result.add(victim); } } events.add(new Event(events.size(), Event.SIGNAL, result .toArray(new IbisIdentifier[result.size()]), signal)); notifyAll(); } void ping(IbisIdentifier ibis) { logger.debug("pinging " + ibis); for (int i = 0; i < MAX_TRIES; i++) { Connection connection = null; try { connection = connectionFactory.connect(ibis, Protocol.OPCODE_PING, CONNECT_TIMEOUT); // get reply connection.getAndCheckReply(); IbisIdentifier result = new IbisIdentifier(connection.in()); connection.close(); if (result.equals(ibis)) { return; } } catch (Exception e) { logger.debug("error on pinging ibis", e); if (connection != null) { connection.close(); } } } logger.error("cannot reach " + ibis + ", removing from pool"); dead(ibis); } void push(Member member) { logger.debug("pushing entries to " + member); Connection connection = null; for (int tries = 0; tries < MAX_TRIES; tries++) { try { int localTime = getEventTime(); int peerTime = 0; if (keepNodeState) { peerTime = member.getCurrentTime(); if (peerTime >= localTime) { logger.debug("NOT pushing entries to " + member + ", nothing to do"); return; } } connection = connectionFactory.connect(member.ibis(), Protocol.OPCODE_PUSH, CONNECT_TIMEOUT); connection.out().writeUTF(getName()); if (!keepNodeState) { logger.debug("waiting for peer time"); connection.out().flush(); peerTime = connection.in().readInt(); } logger.debug("peer time = " + peerTime); int sendEntries = localTime - peerTime; logger.debug("sending " + sendEntries + " entries"); connection.out().writeInt(sendEntries); Event[] events = getEvents(peerTime, peerTime + sendEntries); for (int i = 0; i < events.length; i++) { events[i].writeTo(connection.out()); } connection.getAndCheckReply(); if (keepNodeState) { member.setCurrentTime(localTime); } connection.close(); return; } catch (IOException e) { logger.debug("error on pushing to ibis", e); if (connection != null) { connection.close(); } } } logger.error("cannot reach " + member + ", removing from pool"); dead(member.ibis()); } private synchronized IbisIdentifier getSuspectIbis() { while (checkList.size() == 0 && !ended()) { try { wait(); } catch (InterruptedException e) { // IGNORE } } if (ended()) { return null; } return checkList.remove(0); } /** * contacts any suspect nodes when asked */ public void run() { while (!ended()) { IbisIdentifier suspect = getSuspectIbis(); if (suspect != null) { ping(suspect); } } } synchronized Member[] getRandomMembers(int size) { return members.getRandom(size); } synchronized Member getRandomMember() { return members.getRandom(); } synchronized Member getMember(int index) { return members.get(index); } public String toString() { return "Pool " + name + ": size = " + getSize() + ", event time = " + getEventTime(); } }
package com.facebook.react.fabric.mounting; import static com.facebook.infer.annotation.ThreadConfined.ANY; import static com.facebook.infer.annotation.ThreadConfined.UI; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import androidx.annotation.AnyThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.UiThread; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.infer.annotation.ThreadConfined; import com.facebook.react.bridge.ReactSoftException; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableNativeMap; import com.facebook.react.bridge.RetryableMountingLayerException; import com.facebook.react.bridge.SoftAssertions; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.fabric.FabricUIManager; import com.facebook.react.fabric.events.EventEmitterWrapper; import com.facebook.react.fabric.mounting.mountitems.MountItem; import com.facebook.react.touch.JSResponderHandler; import com.facebook.react.uimanager.IllegalViewOperationException; import com.facebook.react.uimanager.ReactStylesDiffMap; import com.facebook.react.uimanager.RootView; import com.facebook.react.uimanager.RootViewManager; import com.facebook.react.uimanager.StateWrapper; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewGroupManager; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.uimanager.ViewManagerRegistry; import com.facebook.yoga.YogaMeasureMode; import java.util.concurrent.ConcurrentHashMap; /** * Class responsible for actually dispatching view updates enqueued via {@link * FabricUIManager#scheduleMountItems(int, MountItem[])} on the UI thread. */ public class MountingManager { public static final String TAG = MountingManager.class.getSimpleName(); @NonNull private final ConcurrentHashMap<Integer, ViewState> mTagToViewState; @NonNull private final JSResponderHandler mJSResponderHandler = new JSResponderHandler(); @NonNull private final ViewManagerRegistry mViewManagerRegistry; @NonNull private final RootViewManager mRootViewManager = new RootViewManager(); public MountingManager(@NonNull ViewManagerRegistry viewManagerRegistry) { mTagToViewState = new ConcurrentHashMap<>(); mViewManagerRegistry = viewManagerRegistry; } /** * This mutates the rootView, which is an Android View, so this should only be called on the UI * thread. * * @param reactRootTag * @param rootView */ @ThreadConfined(UI) public void addRootView(int reactRootTag, @NonNull View rootView) { if (rootView.getId() != View.NO_ID) { throw new IllegalViewOperationException( "Trying to add a root view with an explicit id already set. React Native uses " + "the id field to track react tags and will overwrite this field. If that is fine, " + "explicitly overwrite the id field to View.NO_ID before calling addRootView."); } mTagToViewState.put( reactRootTag, new ViewState(reactRootTag, rootView, mRootViewManager, true)); rootView.setId(reactRootTag); } /** Releases all references to given native View. */ @UiThread private void dropView(@NonNull View view) { UiThreadUtil.assertOnUiThread(); int reactTag = view.getId(); ViewState state = getViewState(reactTag); ViewManager viewManager = state.mViewManager; if (!state.mIsRoot && viewManager != null) { // For non-root views we notify viewmanager with {@link ViewManager#onDropInstance} viewManager.onDropViewInstance(view); } if (view instanceof ViewGroup && viewManager instanceof ViewGroupManager) { ViewGroup viewGroup = (ViewGroup) view; ViewGroupManager<ViewGroup> viewGroupManager = getViewGroupManager(state); for (int i = viewGroupManager.getChildCount(viewGroup) - 1; i >= 0; i View child = viewGroupManager.getChildAt(viewGroup, i); if (getNullableViewState(child.getId()) != null) { dropView(child); } viewGroupManager.removeViewAt(viewGroup, i); } } mTagToViewState.remove(reactTag); } @UiThread public void addViewAt(int parentTag, int tag, int index) { UiThreadUtil.assertOnUiThread(); ViewState parentViewState = getViewState(parentTag); if (!(parentViewState.mView instanceof ViewGroup)) { String message = "Unable to add a view into a view that is not a ViewGroup. ParentTag: " + parentTag + " - Tag: " + tag + " - Index: " + index; FLog.e(TAG, message); throw new IllegalStateException(message); } final ViewGroup parentView = (ViewGroup) parentViewState.mView; ViewState viewState = getViewState(tag); final View view = viewState.mView; if (view == null) { throw new IllegalStateException( "Unable to find view for viewState " + viewState + " and tag " + tag); } getViewGroupManager(parentViewState).addView(parentView, view, index); } private @NonNull ViewState getViewState(int tag) { ViewState viewState = mTagToViewState.get(tag); if (viewState == null) { throw new RetryableMountingLayerException("Unable to find viewState view for tag " + tag); } return viewState; } private @Nullable ViewState getNullableViewState(int tag) { return mTagToViewState.get(tag); } @Deprecated public void receiveCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) { ViewState viewState = getNullableViewState(reactTag); // It's not uncommon for JS to send events as/after a component is being removed from the // view hierarchy. For example, TextInput may send a "blur" command in response to the view // disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev // for now. if (viewState == null) { throw new RetryableMountingLayerException( "Unable to find viewState for tag: " + reactTag + " for commandId: " + commandId); } if (viewState.mViewManager == null) { throw new RetryableMountingLayerException("Unable to find viewManager for tag " + reactTag); } if (viewState.mView == null) { throw new RetryableMountingLayerException( "Unable to find viewState view for tag " + reactTag); } viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs); } public void receiveCommand( int reactTag, @NonNull String commandId, @Nullable ReadableArray commandArgs) { ViewState viewState = getNullableViewState(reactTag); // It's not uncommon for JS to send events as/after a component is being removed from the // view hierarchy. For example, TextInput may send a "blur" command in response to the view // disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev // for now. if (viewState == null) { throw new RetryableMountingLayerException( "Unable to find viewState for tag: " + reactTag + " for commandId: " + commandId); } if (viewState.mViewManager == null) { throw new RetryableMountingLayerException( "Unable to find viewState manager for tag " + reactTag); } if (viewState.mView == null) { throw new RetryableMountingLayerException( "Unable to find viewState view for tag " + reactTag); } viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs); } public void sendAccessibilityEvent(int reactTag, int eventType) { ViewState viewState = getViewState(reactTag); if (viewState.mViewManager == null) { throw new RetryableMountingLayerException( "Unable to find viewState manager for tag " + reactTag); } if (viewState.mView == null) { throw new RetryableMountingLayerException( "Unable to find viewState view for tag " + reactTag); } viewState.mView.sendAccessibilityEvent(eventType); } @SuppressWarnings("unchecked") // prevents unchecked conversion warn of the <ViewGroup> type private static @NonNull ViewGroupManager<ViewGroup> getViewGroupManager( @NonNull ViewState viewState) { if (viewState.mViewManager == null) { throw new IllegalStateException("Unable to find ViewManager for view: " + viewState); } return (ViewGroupManager<ViewGroup>) viewState.mViewManager; } @UiThread public void removeViewAt(int parentTag, int index) { UiThreadUtil.assertOnUiThread(); ViewState viewState = getNullableViewState(parentTag); if (viewState == null) { ReactSoftException.logSoftException( MountingManager.TAG, new IllegalStateException( "Unable to find viewState for tag: " + parentTag + " for removeViewAt")); return; } final ViewGroup parentView = (ViewGroup) viewState.mView; if (parentView == null) { throw new IllegalStateException("Unable to find view for tag " + parentTag); } ViewGroupManager<ViewGroup> viewGroupManager = getViewGroupManager(viewState); try { viewGroupManager.removeViewAt(parentView, index); } catch (RuntimeException e) { // Note: `getChildCount` may not always be accurate! // We don't currently have a good explanation other than, in situations where you // would empirically expect to see childCount > 0, the childCount is reported as 0. // This is likely due to a ViewManager overriding getChildCount or some other methods // in a way that is strictly incorrect, but potentially only visible here. // The failure mode is actually that in `removeViewAt`, a NullPointerException is // thrown when we try to perform an operation on a View that doesn't exist, and // is therefore null. // We try to add some extra diagnostics here, but we always try to remove the View // from the hierarchy first because detecting by looking at childCount will not work. // Note that the lesson here is that `getChildCount` is not /required/ to adhere to // any invariants. If you add 9 children to a parent, the `getChildCount` of the parent // may not be equal to 9. This apparently causes no issues with Android and is common // enough that we shouldn't try to change this invariant, without a lot of thought. int childCount = viewGroupManager.getChildCount(parentView); throw new IllegalStateException( "Cannot remove child at index " + index + " from parent ViewGroup [" + parentView.getId() + "], only " + childCount + " children in parent. Warning: childCount may be incorrect!", e); } } @UiThread public void createView( @NonNull ThemedReactContext themedReactContext, @NonNull String componentName, int reactTag, @Nullable ReadableMap props, @Nullable StateWrapper stateWrapper, boolean isLayoutable) { if (getNullableViewState(reactTag) != null) { return; } View view = null; ViewManager viewManager = null; ReactStylesDiffMap propsDiffMap = null; if (props != null) { propsDiffMap = new ReactStylesDiffMap(props); } if (isLayoutable) { viewManager = mViewManagerRegistry.get(componentName); // View Managers are responsible for dealing with initial state and props. view = viewManager.createView( themedReactContext, propsDiffMap, stateWrapper, mJSResponderHandler); view.setId(reactTag); } ViewState viewState = new ViewState(reactTag, view, viewManager); viewState.mCurrentProps = propsDiffMap; viewState.mCurrentState = (stateWrapper != null ? stateWrapper.getState() : null); mTagToViewState.put(reactTag, viewState); } @UiThread public void updateProps(int reactTag, @Nullable ReadableMap props) { if (props == null) { return; } UiThreadUtil.assertOnUiThread(); ViewState viewState = getViewState(reactTag); viewState.mCurrentProps = new ReactStylesDiffMap(props); View view = viewState.mView; if (view == null) { throw new IllegalStateException("Unable to find view for tag " + reactTag); } Assertions.assertNotNull(viewState.mViewManager) .updateProperties(view, viewState.mCurrentProps); } @UiThread public void updateLayout(int reactTag, int x, int y, int width, int height) { UiThreadUtil.assertOnUiThread(); ViewState viewState = getViewState(reactTag); // Do not layout Root Views if (viewState.mIsRoot) { return; } View viewToUpdate = viewState.mView; if (viewToUpdate == null) { throw new IllegalStateException("Unable to find View for tag: " + reactTag); } viewToUpdate.measure( View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)); ViewParent parent = viewToUpdate.getParent(); if (parent instanceof RootView) { parent.requestLayout(); } // TODO: T31905686 Check if the parent of the view has to layout the view, or the child has // to lay itself out. see NativeViewHierarchyManager.updateLayout viewToUpdate.layout(x, y, x + width, y + height); } @UiThread public void updatePadding(int reactTag, int left, int top, int right, int bottom) { UiThreadUtil.assertOnUiThread(); ViewState viewState = getViewState(reactTag); // Do not layout Root Views if (viewState.mIsRoot) { return; } View viewToUpdate = viewState.mView; if (viewToUpdate == null) { throw new IllegalStateException("Unable to find View for tag: " + reactTag); } ViewManager viewManager = viewState.mViewManager; if (viewManager == null) { throw new IllegalStateException("Unable to find ViewManager for view: " + viewState); } //noinspection unchecked viewManager.setPadding(viewToUpdate, left, top, right, bottom); } @UiThread public void deleteView(int reactTag) { UiThreadUtil.assertOnUiThread(); ViewState viewState = getNullableViewState(reactTag); if (viewState == null) { ReactSoftException.logSoftException( MountingManager.TAG, new IllegalStateException( "Unable to find viewState for tag: " + reactTag + " for deleteView")); return; } View view = viewState.mView; if (view != null) { dropView(view); } else { mTagToViewState.remove(reactTag); } } @UiThread public void updateState(final int reactTag, @Nullable StateWrapper stateWrapper) { UiThreadUtil.assertOnUiThread(); ViewState viewState = getViewState(reactTag); @Nullable ReadableNativeMap newState = stateWrapper == null ? null : stateWrapper.getState(); if ((viewState.mCurrentState != null && viewState.mCurrentState.equals(newState)) || (viewState.mCurrentState == null && stateWrapper == null)) { return; } viewState.mCurrentState = newState; ViewManager viewManager = viewState.mViewManager; if (viewManager == null) { throw new IllegalStateException("Unable to find ViewManager for tag: " + reactTag); } Object extraData = viewManager.updateState(viewState.mView, viewState.mCurrentProps, stateWrapper); if (extraData != null) { viewManager.updateExtraData(viewState.mView, extraData); } } @UiThread public void preallocateView( @NonNull ThemedReactContext reactContext, String componentName, int reactTag, @Nullable ReadableMap props, @Nullable StateWrapper stateWrapper, boolean isLayoutable) { if (getNullableViewState(reactTag) != null) { throw new IllegalStateException( "View for component " + componentName + " with tag " + reactTag + " already exists."); } createView(reactContext, componentName, reactTag, props, stateWrapper, isLayoutable); } @UiThread public void updateEventEmitter(int reactTag, @NonNull EventEmitterWrapper eventEmitter) { UiThreadUtil.assertOnUiThread(); ViewState viewState = mTagToViewState.get(reactTag); if (viewState == null) { // TODO T62717437 - Use a flag to determine that these event emitters belong to virtual nodes // only. viewState = new ViewState(reactTag, null, null); mTagToViewState.put(reactTag, viewState); } viewState.mEventEmitter = eventEmitter; } @UiThread public synchronized void setJSResponder( int reactTag, int initialReactTag, boolean blockNativeResponder) { if (!blockNativeResponder) { mJSResponderHandler.setJSResponder(initialReactTag, null); return; } ViewState viewState = getViewState(reactTag); View view = viewState.mView; if (initialReactTag != reactTag && view instanceof ViewParent) { // In this case, initialReactTag corresponds to a virtual/layout-only View, and we already // have a parent of that View in reactTag, so we can use it. mJSResponderHandler.setJSResponder(initialReactTag, (ViewParent) view); return; } else if (view == null) { SoftAssertions.assertUnreachable("Cannot find view for tag " + reactTag + "."); return; } if (viewState.mIsRoot) { SoftAssertions.assertUnreachable( "Cannot block native responder on " + reactTag + " that is a root view"); } mJSResponderHandler.setJSResponder(initialReactTag, view.getParent()); } /** * Clears the JS Responder specified by {@link #setJSResponder(int, int, boolean)}. After this * method is called, all the touch events are going to be handled by JS. */ @UiThread public void clearJSResponder() { mJSResponderHandler.clearJSResponder(); } @AnyThread public long measure( @NonNull Context context, @NonNull String componentName, @NonNull ReadableMap localData, @NonNull ReadableMap props, @NonNull ReadableMap state, float width, @NonNull YogaMeasureMode widthMode, float height, @NonNull YogaMeasureMode heightMode, @Nullable float[] attachmentsPositions) { return mViewManagerRegistry .get(componentName) .measure( context, localData, props, state, width, widthMode, height, heightMode, attachmentsPositions); } @AnyThread @ThreadConfined(ANY) public @Nullable EventEmitterWrapper getEventEmitter(int reactTag) { ViewState viewState = getNullableViewState(reactTag); return viewState == null ? null : viewState.mEventEmitter; } /** * This class holds view state for react tags. Objects of this class are stored into the {@link * #mTagToViewState}, and they should be updated in the same thread. */ private static class ViewState { @Nullable final View mView; final int mReactTag; final boolean mIsRoot; @Nullable final ViewManager mViewManager; @Nullable public ReactStylesDiffMap mCurrentProps = null; @Nullable public ReadableMap mCurrentLocalData = null; @Nullable public ReadableMap mCurrentState = null; @Nullable public EventEmitterWrapper mEventEmitter = null; private ViewState(int reactTag, @Nullable View view, @Nullable ViewManager viewManager) { this(reactTag, view, viewManager, false); } private ViewState(int reactTag, @Nullable View view, ViewManager viewManager, boolean isRoot) { mReactTag = reactTag; mView = view; mIsRoot = isRoot; mViewManager = viewManager; } @Override public String toString() { boolean isLayoutOnly = mViewManager == null; return "ViewState [" + mReactTag + "] - isRoot: " + mIsRoot + " - props: " + mCurrentProps + " - localData: " + mCurrentLocalData + " - viewManager: " + mViewManager + " - isLayoutOnly: " + isLayoutOnly; } } }
package monoxide.forgebackup; import java.util.Iterator; import java.util.logging.Level; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.command.ServerCommandManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntityCommandBlock; import cpw.mods.fml.common.registry.LanguageRegistry; public abstract class CommandBackupBase extends CommandBase { protected final MinecraftServer server; public CommandBackupBase(MinecraftServer server) { this.server = MinecraftServer.getServer(); ((ServerCommandManager) this.server.getCommandManager()).registerCommand(this); } @Override public int getRequiredPermissionLevel() { return !ForgeBackup.instance().config().onlyOperatorsCanManuallyBackup() ? 0 : (ForgeBackup.instance().config().canCommandBlocksUseCommands() ? 3 : 2); } public void notifyBackupAdmins(ICommandSender sender, String translationKey, Object... parameters) { notifyBackupAdmins(sender, Level.INFO, translationKey, parameters); } public void notifyBackupAdmins(ICommandSender sender, Level level, String translationKey, Object... parameters) { boolean var5 = true; String message = String.format(LanguageRegistry.instance().getStringLocalization(translationKey), parameters); if (sender instanceof TileEntityCommandBlock && !server.worldServers[0].getGameRules().getGameRuleBooleanValue("commandBlockOutput")) { var5 = false; } if (var5) { Iterator var6 = server.getConfigurationManager().playerEntityList.iterator(); while (var6.hasNext()) { EntityPlayerMP var7 = (EntityPlayerMP)var6.next(); if (server.getConfigurationManager().areCommandsAllowed(var7.username) && (ForgeBackup.instance().config().verboseLogging() || level != Level.FINE)) { var7.sendChatToPlayer("\u00a77\u00a7o[Backup: " + message + "]"); } } } if (sender != server) { if (ForgeBackup.instance().config().verboseLogging() && level == Level.FINE) { BackupLog.log(Level.INFO, message); } else { BackupLog.log(level, message); } } } }
package info.tregmine.commands; import java.util.List; import java.util.Map; import java.util.HashMap; import static org.bukkit.ChatColor.*; import org.bukkit.Server; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.*; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.PluginManager; import org.bukkit.event.Listener; import org.bukkit.event.EventHandler; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.AsyncPlayerChatEvent; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.database.DAOException; import info.tregmine.database.IContext; import info.tregmine.database.IWalletDAO; import info.tregmine.database.ITradeDAO; import info.tregmine.api.math.Distance; public class TradeCommand extends AbstractCommand implements Listener { String tradePre = YELLOW + "[Trade] "; private enum TradeState { ITEM_SELECT, BID, CONSIDER_BID; }; private static class TradeContext { Inventory inventory; TregminePlayer firstPlayer; TregminePlayer secondPlayer; TradeState state; int bid; } private Map<TregminePlayer, TradeContext> activeTrades; public TradeCommand(Tregmine tregmine) { super(tregmine, "trade"); activeTrades = new HashMap<TregminePlayer, TradeContext>(); PluginManager pluginMgm = tregmine.getServer().getPluginManager(); pluginMgm.registerEvents(this, tregmine); } @Override public boolean handlePlayer(TregminePlayer player, String[] args) { if (args.length != 1) { return false; } if (player.getChatState() != TregminePlayer.ChatState.CHAT) { player.sendMessage(RED + "A trade is already in progress!"); return true; } Server server = tregmine.getServer(); String pattern = args[0]; List<TregminePlayer> candidates = tregmine.matchPlayer(pattern); if (candidates.size() != 1) { // TODO: error message return true; } TregminePlayer target = candidates.get(0); if (target.getChatState() != TregminePlayer.ChatState.CHAT) { player.sendMessage(RED + target.getName() + "is in a trade!"); return true; } if (target.getId() == player.getId()) { player.sendMessage(RED + "You cannot trade with yourself!"); return true; } double distance = Distance.calc2d(player.getLocation(), target.getLocation()); if (distance > 100) { player.sendMessage(RED + "You can only trade with people less than " + "100 blocks away."); return true; } Inventory inv = server.createInventory(null, InventoryType.CHEST); player.openInventory(inv); TradeContext ctx = new TradeContext(); ctx.inventory = inv; ctx.firstPlayer = player; ctx.secondPlayer = target; ctx.state = TradeState.ITEM_SELECT; activeTrades.put(player, ctx); activeTrades.put(target, ctx); player.setChatState(TregminePlayer.ChatState.TRADE); target.setChatState(TregminePlayer.ChatState.TRADE); player.sendMessage(YELLOW + "[Trade] You are now trading with " + target.getChatName() + YELLOW + ". What do you want " + "to offer?"); target.sendMessage(YELLOW + "[Trade] You are now in a trade with " + player.getChatName() + YELLOW + ". To exit, type \"quit\"."); return true; } @EventHandler public void onInventoryClose(InventoryCloseEvent event) { TregminePlayer player = tregmine.getPlayer((Player) event.getPlayer()); TradeContext ctx = activeTrades.get(player); if (ctx == null) { return; } TregminePlayer target = ctx.secondPlayer; target.sendMessage(tradePre + player.getChatName() + " " + YELLOW + " is offering: "); player.sendMessage("[Trade] You are offering: "); ItemStack[] contents = ctx.inventory.getContents(); for (ItemStack stack : contents) { if (stack == null) { continue; } Material material = stack.getType(); int amount = stack.getAmount(); ItemMeta materialMeta = stack.getItemMeta(); int xpValue; try{ String[] materialLore = materialMeta.getLore().toString().split(" "); xpValue = Integer.parseInt(materialLore[2]); } catch (NullPointerException e) { xpValue = 0; } catch (NumberFormatException e) { xpValue = 0; } Map<Enchantment, Integer> enchantments = stack.getEnchantments(); if (material == Material.EXP_BOTTLE && xpValue > 0 && materialMeta.getDisplayName() == "Tregmine XP Bottle") { target.sendMessage(tradePre + amount + " XP Bottle holding " + xpValue + " levels"); player.sendMessage(tradePre + amount + " XP Bottle holding " + xpValue + " levels"); }else if(enchantments.size() > 0){ target.sendMessage(tradePre + " Enchanted " + material.toString() + " with: "); player.sendMessage(tradePre + " Enchanted " + material.toString() + " with: "); for( Enchantment i : enchantments.keySet() ){ String enchantName = i.getName().replace("_", " "); target.sendMessage("- " + enchantName + " LEVEL: " + enchantments.get(i).toString() ); player.sendMessage("- " + enchantName + " LEVEL: " + enchantments.get(i).toString() ); } }else{ target.sendMessage(tradePre + amount + " " + material.toString()); player.sendMessage(tradePre + amount + " " + material.toString()); } } target.sendMessage(YELLOW + "[Trade] To make a bid, type \"bid <tregs>\". " + "For example: bid 1000"); player.sendMessage(YELLOW + "[Trade] Waiting for " + target.getChatName() + YELLOW + " to make a bid. Type \"change\" to modify " + "your offer."); ctx.state = TradeState.BID; } @EventHandler public void onPlayerChat(AsyncPlayerChatEvent event) { TregminePlayer player = tregmine.getPlayer(event.getPlayer()); if (player.getChatState() != TregminePlayer.ChatState.TRADE) { return; } event.setCancelled(true); TradeContext ctx = activeTrades.get(player); if (ctx == null) { return; } TregminePlayer first = ctx.firstPlayer; TregminePlayer second = ctx.secondPlayer; String text = event.getMessage(); String[] args = text.split(" "); Tregmine.LOGGER.info("[TRADE " + first.getName() + ":" + second.getName() + "] <" + player.getName() + "> " + text); //Tregmine.LOGGER.info("state: " + ctx.state); if ("quit".equals(args[0]) && args.length == 1) { first.setChatState(TregminePlayer.ChatState.CHAT); second.setChatState(TregminePlayer.ChatState.CHAT); activeTrades.remove(first); activeTrades.remove(second); if (ctx.state == TradeState.ITEM_SELECT) { first.closeInventory(); } // Restore contents to player inventory ItemStack[] contents = ctx.inventory.getContents(); Inventory firstInv = first.getInventory(); for (ItemStack stack : contents) { if (stack == null) { continue; } firstInv.addItem(stack); } first.sendMessage(YELLOW + "[Trade] Trade ended."); second.sendMessage(YELLOW + "[Trade] Trade ended."); } else if ("bid".equalsIgnoreCase(args[0]) && args.length == 2) { if (second != player) { player.sendMessage(RED + "[Trade] You can't make a bid!"); return; } if (ctx.state != TradeState.BID) { player.sendMessage(RED + "[Trade] You can't make a bid right now."); return; } int amount = 0; try { amount = Integer.parseInt(args[1]); if (amount < 0) { player.sendMessage(RED + "[Trade] You have to bid an integer " + "number of tregs."); return; } } catch (NumberFormatException e) { player.sendMessage(RED + "[Trade] You have to bid an integer " + "number of tregs."); return; } try (IContext dbCtx = tregmine.createContext()) { IWalletDAO walletDAO = dbCtx.getWalletDAO(); long balance = walletDAO.balance(second); if (amount > balance) { player.sendMessage(RED + "[Trade] You only have " + balance + " tregs!"); return; } } catch (DAOException e) { throw new RuntimeException(e); } first.sendMessage(tradePre + second.getChatName() + YELLOW + " bid " + amount + " tregs. Type \"accept\" to " + "proceed with the trade. Type \"change\" to modify " + "your offer. Type \"quit\" to stop trading."); second.sendMessage(YELLOW + "[Trade] You bid " + amount + " tregs."); ctx.bid = amount; ctx.state = TradeState.CONSIDER_BID; } else if ("change".equalsIgnoreCase(args[0]) && args.length == 1) { if (first != player) { player.sendMessage(RED + "[Trade] You can't change the offer!"); return; } player.openInventory(ctx.inventory); ctx.state = TradeState.ITEM_SELECT; } else if ("accept".equals(args[0]) && args.length == 1) { if (first != player) { player.sendMessage(RED + "[Trade] You can't accept an offer!"); return; } ItemStack[] contents = ctx.inventory.getContents(); int t = 0; for (ItemStack tis : contents) { if (tis == null) { continue; } t++; } int p = 0; Inventory secondInv = second.getInventory(); for (ItemStack pis : secondInv.getContents()) { if (pis != null) { continue; } p++; } if (p < t) { int diff = t - p; first.sendMessage(tradePre + second.getChatName() + YELLOW + " doesn't have enough inventory space, please wait a " + "minute and try again :)"); second.sendMessage(tradePre + "You need to remove " + diff + " item stack(s) from your inventory to be able to recieve " + "the items!"); return; } // Withdraw ctx.bid tregs from second players wallet // Add ctx.bid tregs from first players wallet try (IContext dbCtx = tregmine.createContext()) { IWalletDAO walletDAO = dbCtx.getWalletDAO(); ITradeDAO tradeDAO = dbCtx.getTradeDAO(); if (walletDAO.take(second, ctx.bid)) { walletDAO.add(first, ctx.bid); walletDAO.insertTransaction(second.getId(), first.getId(), ctx.bid); int tradeId = tradeDAO.insertTrade(first.getId(), second.getId(), ctx.bid); tradeDAO.insertStacks(tradeId, contents); first.sendMessage(tradePre + ctx.bid + " tregs was " + "added to your wallet!"); second.sendMessage(tradePre + ctx.bid + " tregs was " + "withdrawn to your wallet!"); } else { first.sendMessage(RED + "[Trade] Failed to withdraw " + ctx.bid + " from the wallet of " + second.getChatName() + "!"); return; } } catch (DAOException e) { throw new RuntimeException(e); } // Move items to second players inventory for (ItemStack stack : contents) { if (stack == null) { continue; } secondInv.addItem(stack); } // Finalize first.setChatState(TregminePlayer.ChatState.CHAT); second.setChatState(TregminePlayer.ChatState.CHAT); activeTrades.remove(first); activeTrades.remove(second); first.giveExp(5); second.giveExp(5); } else { first.sendMessage(tradePre + WHITE + "<" + player.getChatName() + WHITE + "> " + text); second.sendMessage(tradePre + WHITE + "<" + player.getChatName() + WHITE + "> " + text); } } }
package net.mcft.copy.aho.entity; import java.lang.reflect.Field; import net.mcft.copy.aho.AdvHealthOptions; import net.mcft.copy.aho.config.AHOWorldConfig; import net.mcft.copy.aho.config.EnumHunger; import net.mcft.copy.aho.config.EnumShieldReq; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; import net.minecraft.util.FoodStats; import net.minecraft.world.World; import net.minecraftforge.common.IExtendedEntityProperties; import cpw.mods.fml.relauncher.ReflectionHelper; public class AHOProperties implements IExtendedEntityProperties { /** If enabled, prints debug messages about all players' regeneration progress. */ public static final boolean DEBUG = false; public static final String IDENTIFIER = AdvHealthOptions.MOD_ID; public static final String TAG_REGEN_TIMER = "regenTimer"; public static final String TAG_PENALTY_TIMER = "penaltyTimer"; public static final String TAG_SHIELD_TIMER = "shieldTimer"; public double regenTimer = 0; public double penaltyTimer = 0; public double shieldTimer = 0; private boolean hurt = false; private float healthBefore = 0; @Override public void init(Entity entity, World world) { } @Override public void saveNBTData(NBTTagCompound compound) { compound.setDouble(TAG_REGEN_TIMER, regenTimer); compound.setDouble(TAG_PENALTY_TIMER, penaltyTimer); compound.setDouble(TAG_SHIELD_TIMER, shieldTimer); } @Override public void loadNBTData(NBTTagCompound compound) { regenTimer = compound.getDouble(TAG_REGEN_TIMER); penaltyTimer = compound.getDouble(TAG_PENALTY_TIMER); shieldTimer = compound.getDouble(TAG_SHIELD_TIMER); } public void update(EntityPlayer player) { boolean wasHurt = hurt; hurt = false; FoodStats foodStats = player.getFoodStats(); boolean hungerEnabled = handleHunger(player, foodStats); boolean shieldPreventHeal = handleShield(player, wasHurt); resetFoodTimer(foodStats); // If the heal time is set to 0, disable all regeneration. double regenHealTime = AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.regenHealTime); if ((regenHealTime <= 0) && !DEBUG) return; if (wasHurt) increasePenaltyTimer(player); // Decrease penalty timer. penaltyTimer = Math.max(0, penaltyTimer - 1 / 20.0); // If player has full or no health, reset regeneration timer and return. if (!player.shouldHeal()) { regenTimer = 0; if (!DEBUG) return; } double foodFactor = (hungerEnabled ? calculateFoodFactor(foodStats.getFoodLevel()) : 1.0); double penaltyFactor = calculatePenaltyFactor(penaltyTimer); if (!shieldPreventHeal && (regenHealTime > 0) && ((regenTimer += (penaltyFactor * foodFactor) / 20.0) > regenHealTime)) { player.heal(1); double regenExhaustion = AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.regenExhaustion); foodStats.addExhaustion((float)regenExhaustion); regenTimer -= regenHealTime; } if (DEBUG) System.out.println(String.format("%s: Regen=%d/%d+%.2f Penalty=%d/%d/%d+%.2f Shield=%d/%d", player.getCommandSenderName(), (int)regenTimer, (int)regenHealTime, foodFactor, (int)penaltyTimer, (int)AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.hurtPenaltyBuffer), (int)AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.hurtPenaltyMaximum), penaltyFactor, (int)shieldTimer, (int)AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.shieldRechargeTime))); } public void hurt(EntityPlayer player) { if (hurt) return; hurt = true; healthBefore = player.getHealth(); } boolean foodLevelSet = false; /** Handles the hunger setting, returns if hunger is enabled. */ private boolean handleHunger(EntityPlayer player, FoodStats foodStats) { EnumHunger hunger = AdvHealthOptions.worldConfig.getEnum(AHOWorldConfig.hunger); if (hunger == EnumHunger.ENABLE) return true; // Make direct changes to the food meter affect health directly. if ((hunger == EnumHunger.HEALTH) && foodLevelSet) { int change = (foodStats.getFoodLevel() - 8); if (change > 0) player.heal(change); else if (change < 0) player.attackEntityFrom(DamageSource.starve, -change); } // Reset the food level and saturation. foodStats.setFoodLevel(0); foodStats.addStats(8, 20.0F); foodLevelSet = true; return false; } /** Handles the shield settings, returns if healing is paused. */ private boolean handleShield(EntityPlayer player, boolean wasHurt) { int maximum = AdvHealthOptions.worldConfig.getInteger(AHOWorldConfig.shieldMaximum); EnumShieldReq req = AdvHealthOptions.worldConfig.getEnum(AHOWorldConfig.shieldRequirement); boolean atMaximum = (player.getAbsorptionAmount() >= maximum); if (!wasHurt && !atMaximum && !((req == EnumShieldReq.SHIELD_REQ_HEALTH) && player.shouldHeal())) { double shieldRechargeTime = AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.shieldRechargeTime); if ((shieldTimer += 1 / 20.0) >= shieldRechargeTime) { player.setAbsorptionAmount(Math.min(maximum, player.getAbsorptionAmount() + 1)); shieldTimer -= shieldTimer; } } else shieldTimer = -AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.shieldTimeout); return ((req == EnumShieldReq.HEALTH_REQ_SHIELD) && !atMaximum); } private static Field foodTimerField = null; /** Reset the "food timer" to disable Vanilla natural regeneration. */ private void resetFoodTimer(FoodStats foodStats) { if (foodTimerField == null) foodTimerField = ReflectionHelper.findField(FoodStats.class, "field_75123_d", "foodTimer"); if (foodStats.getFoodLevel() > 0) { try { foodTimerField.set(foodStats, 0); } catch (Exception ex) { throw new RuntimeException(ex); } } } /** Increases the "penalty timer" when player was hurt. */ private void increasePenaltyTimer(EntityPlayer player) { float damageTaken = (healthBefore - player.getHealth()); double hurtTime = AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.hurtPenaltyTime); double hurtTimeMaximum = AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.hurtPenaltyTimeMaximum); double penaltyIncrease = Math.min(hurtTimeMaximum, Math.max(0.5, damageTaken) * hurtTime); double hurtMaximum = AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.hurtPenaltyMaximum); if (penaltyTimer < hurtMaximum) penaltyTimer = Math.min(hurtMaximum, penaltyTimer + penaltyIncrease); } private double calculateFoodFactor(int foodLevel) { int regenHungerMinimum = AdvHealthOptions.worldConfig.getInteger(AHOWorldConfig.regenHungerMinimum); if (foodLevel < regenHungerMinimum) return 0.0; int regenHungerMaximum = AdvHealthOptions.worldConfig.getInteger(AHOWorldConfig.regenHungerMaximum); if (foodLevel >= regenHungerMaximum) return 1.0; return ((foodLevel - regenHungerMinimum + 1.0) / (regenHungerMaximum - regenHungerMinimum + 1.0)); } private double calculatePenaltyFactor(double penaltyTimer) { if (penaltyTimer <= 0) return 1.0; double hurtBuffer = AdvHealthOptions.worldConfig.getDouble(AHOWorldConfig.hurtPenaltyBuffer); return ((penaltyTimer < hurtBuffer) ? (1 - (penaltyTimer / hurtBuffer)) : 0.0); } }
package opendap.aggregation; import java.io.*; import java.text.NumberFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipOutputStream; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import opendap.bes.BESError; import opendap.bes.BadConfigurationException; import opendap.bes.dap2Responders.BesApi; import opendap.coreServlet.ReqInfo; import opendap.coreServlet.RequestCache; import opendap.dap.User; import opendap.ppt.PPTException; import org.jdom.Document; import org.jdom.JDOMException; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AggregationServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Logger _log; private BesApi _besApi; private Set<String> _granuleNames; private static final String invocationError = "I expected '/version', '/file', or '/netcdf3', got: "; private static final String versionInfo = "Aggregation Interface Version: 1.0"; @Override public void init() throws ServletException { super.init(); _log = LoggerFactory.getLogger(this.getClass()); _besApi = new BesApi(); _granuleNames = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); _log.info(versionInfo); Runtime runtime = Runtime.getRuntime(); NumberFormat format = NumberFormat.getInstance(); StringBuilder sb = new StringBuilder(); long maxMemory = runtime.maxMemory(); long allocatedMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); sb.append("init() - free memory: " + format.format(freeMemory / 1024) + "\n"); sb.append("init() - allocated memory: " + format.format(allocatedMemory / 1024) + "\n"); sb.append("init() - max memory: " + format.format(maxMemory / 1024) + "\n"); sb.append("init() - total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024) + "\n"); _log.info(sb.toString()); } /** * Given a pathname, split it into two parts, the basename and the * directories leading up to that basename. * @param path The path to split up * @return A two element String array. */ private static String[] basename(String path) { String[] tokens = path.split("/(?=[^/]+$)"); return tokens; } /** * Keep from repeating the same i/o for logging.. * @param t The thrown object * @param msg A message to indicate where this happened. Ex: "in doHead():" */ private void logError(Throwable t, String msg) { _log.error("Error {}{}", msg, t.getMessage()); StringWriter writer = new StringWriter(); t.printStackTrace(new PrintWriter(writer)); _log.error("Stack trace: "); _log.error(writer.toString()); } /** * Given a granule name, and return a name that will not collide * with a file name already used in the Zip file. This is used * because Zip files don't tolerate duplicate entries, it's possible * to have the same files used with different CEs and users * on machines with case insensitive file systems will have duplicate * names even when Unix thinks they are unique... * * @param granule The name of the current granule, which is about * to be added to the Zip file * @return Use this name for the granule in the Zip file */ private String getNameForZip(String granule) { if (!_granuleNames.contains(granule)) { // In the simple case, don't fiddle with the name, just record that // it's been used. _granuleNames.add(granule); return granule; } else { // In the more complex case, make a new name and try again... int i = 1; while (_granuleNames.contains(granule + "_" + i)) ++i; return getNameForZip(granule + "_" + i); } } /** * Write the Aggregation Service endpoint's version. This was originally * written to demonstrate that simple interaction with the BES was working. * It may have a use in the future, and I've changed some of the more verbose * output so it only happens when logback's DEBUG mode is being used. * * @param request The HTTP Servlet Request object * @param response The HTTP Servlet Response object * @param out The Stream * @throws IOException * @throws ServletException * @throws PPTException * @throws BadConfigurationException * @throws JDOMException */ private void writeAggregationVersion(HttpServletRequest request, HttpServletResponse response, ServletOutputStream out) throws IOException, ServletException, PPTException, BadConfigurationException, JDOMException { response.setContentType("text/plain"); // These should always be true if (!_besApi.isConfigured() || !_besApi.isInitialized()) { String err = "BES is not configured or not initialized"; out.println(err); _log.error(err); } // This shows the whole request document if (_log.isDebugEnabled()) { StringBuilder echoText = new StringBuilder(); getPlainText(request, echoText); _log.debug(echoText.toString()); } // This response, when used in non-debug mode, returns the servlet's version and... out.println(versionInfo); // ...the bes version info. // This is here primarily to show that we are talking to the BES. Document version = new Document(); if (!_besApi.getBesVersion("/", version)) { String err = "Error getting version information from the BES"; out.println(err); _log.error(err); } XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); String besVer = xmlo.outputString(version); out.print(besVer); _log.debug("The BES Version information:\n"); _log.debug(besVer); } /** * Helper for writePlainGranules * * @param granule * @param os * @throws IOException * @throws PPTException * @throws BadConfigurationException * @throws BESError */ private void writeSinglePlainGranule(String granule, OutputStream os) throws IOException, PPTException, BadConfigurationException, BESError { ByteArrayOutputStream errors = new ByteArrayOutputStream(); if (!_besApi.writeFile(granule, os, errors)) { String msg = new String(errors.toByteArray()); os.write(msg.getBytes()); _log.error("Error in writeSinglePlainGranule(): {}", msg); } } /** * Test getting the BES to write several files to its output stream * * @param request * @param response * @param out * @throws Exception */ private void writePlainGranules(HttpServletRequest request, HttpServletResponse response, ServletOutputStream out) throws Exception { Map<String, String[]> queryParameters = request.getParameterMap(); response.setContentType("application/x-zip-compressed"); response.setHeader("Content-Disposition", "attachment; filename=file.zip"); ZipOutputStream zos = new ZipOutputStream(out); int N = queryParameters.get("file").length; for (int i = 0; i < N; ++i) { String granule = queryParameters.get("file")[i]; String granuleName = getNameForZip(basename(granule)[1]); try { zos.putNextEntry(new ZipEntry(granuleName)); writeSinglePlainGranule(granule, zos); zos.closeEntry(); } catch (ZipException ze) { out.println("Error: " + ze.getMessage()); logError(ze, "in writePlainGranules():"); } } zos.finish(); } /** * Helper - write a single netCDF3 file to the stream. If an error is * returned by the BES, use the value of the error message as the file * contents. * * @param granule The granule name in the BES's data tree * @param ce Apply this CE to the granule * @param os Write the result to this stream * @param maxResponseSize Use a value >0 to indicate an upper limit on * response sizes. * @throws IOException * @throws PPTException * @throws BadConfigurationException * @throws BESError */ private void writeSingleGranuleAsNetcdf(String granule, String ce, OutputStream os, int maxResponseSize) throws IOException, PPTException, BadConfigurationException, BESError { String xdap_accept = "3.2"; ByteArrayOutputStream errors = new ByteArrayOutputStream(); if (!_besApi.writeDap2DataAsNetcdf3(granule, ce, xdap_accept, maxResponseSize, os, errors)) { // Processing errors this way means that if the BES fails to perform // some function, e.g., the CE is bad, that error message will be used // as the value of the file in the Zip archive. This provides a way for // most of a request to work even if some of the files are broken. String msg = new String(errors.toByteArray()); os.write(msg.getBytes()); _log.error("Error in writeSingleGranuleAsNetcdf(): {}", msg); } } /** * Write a set of netCDF3 files to the client, wrapped up in a zip file. * * Each input file in included in the zip archive with the original * directory hierarchy information removed (but is protected from * name collisions). In addition, since this code will be transforming * the original file into a netCDF3, the extension '.nc' is appended, * even if the original file was a netCDF file. This provides a primitive * indication that the file differs from the original source file. * * @param request * @param response * @param out * @throws Exception */ private void writeGranulesAsNetcdf(HttpServletRequest request, HttpServletResponse response, ServletOutputStream out) throws Exception { Map<String, String[]> queryParameters = request.getParameterMap(); // Before we start trying to send back netCDF files, we check to make // sure that the parameters passed in are valid. There must be N values // for 'file' and either 1 or N values for 'ce' int N = queryParameters.get("file").length; if (!(queryParameters.get("ce").length == 1 || queryParameters.get("ce").length == N)) throw new Exception("Incorrect number of 'ce' parameters (found " + N + " instances of 'file' and " + queryParameters.get("ce").length + " of 'ce')."); // We have valid 'file' and 'ce' params... response.setContentType("application/x-zip-compressed"); response.setHeader("Content-Disposition", "attachment; filename=netcdf3.zip"); // TODO Better name? User user = new User(request); int maxResponse = user.getMaxResponseSize(); ZipOutputStream zos = new ZipOutputStream(out); String masterCE = new String(""); if (queryParameters.get("ce").length == 1) masterCE = queryParameters.get("ce")[0]; for (int i = 0; i < N; ++i) { String granule = queryParameters.get("file")[i]; String ce; if (masterCE.equals("")) ce = queryParameters.get("ce")[i]; else ce = masterCE; String granuleName = getNameForZip(basename(granule)[1]) + ".nc"; try { zos.putNextEntry(new ZipEntry(granuleName)); writeSingleGranuleAsNetcdf(granule, ce, zos, maxResponse); zos.closeEntry(); } catch (ZipException ze) { out.println("Error: " + ze.getMessage()); logError(ze, "in writeGranulesAsNetcdf():"); } } zos.finish(); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { _log.debug("doGet() - BEGIN"); // forget the names used in/by previous requests _granuleNames.clear(); ServletOutputStream out = response.getOutputStream(); try { RequestCache.openThreadCache(); String requestedResourceId = ReqInfo.getLocalUrl(request); _log.debug("The resource ID is: {}", requestedResourceId); if (requestedResourceId.equals("/version")) { writeAggregationVersion(request, response, out); } else if (requestedResourceId.equals("/file")) { writePlainGranules(request, response, out); } else if (requestedResourceId.equals("/netcdf3")) { writeGranulesAsNetcdf(request, response, out); } else { throw new Exception(invocationError + requestedResourceId); } } catch (BadConfigurationException | PPTException | JDOMException e) { out.println("Error: " + e.getMessage()); logError(e, "in doGet(), caught an BadConfiguration, PPT or JDOM Exception:"); } catch (Throwable t) { out.println("Error: " + t.getMessage()); logError(t, "in doGet():"); } finally { RequestCache.closeThreadCache(); } out.flush(); _log.debug("doGet() - END"); } @Override public void doHead(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { _log.debug("doHead() - BEGIN"); ServletOutputStream out = response.getOutputStream(); try { RequestCache.openThreadCache(); String requestedResourceId = ReqInfo.getLocalUrl(request); if (requestedResourceId.equals("/version")) { response.setContentType("text/plain"); } else if (requestedResourceId.equals("/text")) { response.setContentType("application/x-zip-compressed"); response.setHeader("Content-Disposition", "attachment; filename=text.zip"); } else if (requestedResourceId.equals("/netcdf3")) { response.setContentType("application/x-zip-compressed"); response.setHeader("Content-Disposition", "attachment; filename=netcdf3.zip"); } else { throw new Exception(invocationError + requestedResourceId); } } catch (Throwable t) { out.println("Error: " + t.getMessage()); logError(t, "in doHead():"); } finally { RequestCache.closeThreadCache(); } out.flush(); _log.debug("doHead() - END"); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { _log.debug("doPost() - BEGIN"); doGet(request, response); _log.debug("doPost() - END"); } /** * Copied from the EchoServlet written by Nathan, this was used to debug * processing GET and POST requests and is called only when the /version * response is requested and logback is in DEBUG mode. * * @param request * @param out * @return * @throws IOException * @throws ServletException */ private int getPlainText(HttpServletRequest request, StringBuilder out) throws IOException, ServletException { out.append("\n out.append("HTTP Method: ").append(request.getMethod()).append("\n"); out.append("\n"); out.append("HTTP Request Headers"); out.append("\n"); Enumeration<String> headers = request.getHeaderNames(); while(headers.hasMoreElements()){ String headerName = headers.nextElement(); String headerValue = request.getHeader(headerName); out.append(" ").append(headerName).append(": ").append(headerValue).append("\n"); } out.append("\n"); String queryString = request.getQueryString(); out.append("Query String and KVP Evaluation\n"); out.append("\n"); out.append(" HttpServletRequest.getQueryString(): ").append(queryString).append("\n"); out.append("\n"); out.append(" Decoded: ").append(java.net.URLDecoder.decode(queryString == null ? "null" : queryString, "UTF-8")).append("\n"); out.append("\n"); int contentLength = request.getContentLength(); out.append("request.getContentLength(): ").append(contentLength).append("\n"); out.append("\n"); if(contentLength==-1){ _log.info("getPlainText() - Retrieving Content-Length header."); String s = request.getHeader("Content-Length"); if(s!=null){ contentLength = Integer.parseInt(s); } } String ctype = request.getHeader("Content-Type"); if(ctype!=null && ctype.equalsIgnoreCase("application/x-www-form-urlencoded")){ out.append("Content-Type indicates that the request body is form url encoded. Utilizing Servlet API to evaluate parameters.\n"); out.append(" HttpServletRequest.getParameter()\n"); out.append(" keyName value \n"); Enumeration<String> paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()){ String paramName = paramNames.nextElement(); String paramValue = request.getParameter(paramName); out.append(" ").append(paramName).append(": ").append(paramValue).append("\n"); } out.append(" HttpServletRequest.getParameterMap()\n"); out.append("\n"); Map paramMap = request.getParameterMap(); out.append(" ParameterMap is an instance of: ").append(paramMap.getClass().getName()).append("\n"); out.append(" ParameterMap contains ").append(paramMap.size()).append(" element(s).\n"); out.append("\n"); out.append(" keyName value(s) \n"); for(Object o:paramMap.keySet()){ String key = (String) o; Object oo = paramMap.get(key); String[] values = (String[]) oo; out.append(" ").append(key).append(" "); boolean first=true; for(String value:values){ if(!first) out.append(", "); out.append("'").append(value).append("'"); first = false; } out.append("\n"); } out.append("\n"); } else { out.append("Content-Type indicates that the request body is NOT form url encoded.\n"); } return contentLength; } private StringBuilder convertStreamToString(ServletInputStream is, int size) throws IOException { StringBuilder result = new StringBuilder(size); int ret; boolean done = false; while(!done){ ret = is.read(); if(ret==-1) done = true; else result.append((char)ret); } return result; } }
package org.eclipse.che.selenium.refactor.types; import static org.testng.Assert.fail; import com.google.inject.Inject; import java.io.IOException; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import org.eclipse.che.commons.lang.NameGenerator; import org.eclipse.che.selenium.core.client.TestProjectServiceClient; import org.eclipse.che.selenium.core.constant.TestMenuCommandsConstants; import org.eclipse.che.selenium.core.project.ProjectTemplates; import org.eclipse.che.selenium.core.workspace.TestWorkspace; import org.eclipse.che.selenium.pageobject.AskDialog; import org.eclipse.che.selenium.pageobject.CodenvyEditor; import org.eclipse.che.selenium.pageobject.Consoles; import org.eclipse.che.selenium.pageobject.Ide; import org.eclipse.che.selenium.pageobject.Loader; import org.eclipse.che.selenium.pageobject.Menu; import org.eclipse.che.selenium.pageobject.ProjectExplorer; import org.eclipse.che.selenium.pageobject.Refactor; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriverException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** @author Musienko Maxim */ public class RenameTypeTest { private static final Logger LOG = LoggerFactory.getLogger(RenameTypeTest.class); private static final String NAME_OF_PROJECT = NameGenerator.generate(RenameTypeTest.class.getSimpleName(), 2); private static final String PATH_TO_PACKAGE_IN_CHE_PREFIX = NAME_OF_PROJECT + "/src/main/java/renametype"; private String pathToCurrentPackage; private String contentFromInA; private String contentFromOutB; @Inject private TestWorkspace workspace; @Inject private Ide ide; @Inject private ProjectExplorer projectExplorer; @Inject private Loader loader; @Inject private CodenvyEditor editor; @Inject private Refactor refactorPanel; @Inject private Consoles consoles; @Inject private Menu menu; @Inject private AskDialog askDialog; @Inject private TestProjectServiceClient testProjectServiceClient; @BeforeClass public void setup() throws Exception { URL resource = RenameTypeTest.this.getClass().getResource("/projects/RenameType"); testProjectServiceClient.importProject( workspace.getId(), Paths.get(resource.toURI()), NAME_OF_PROJECT, ProjectTemplates.MAVEN_SIMPLE); ide.open(workspace); projectExplorer.waitVisibleItem(NAME_OF_PROJECT); consoles.closeProcessesArea(); projectExplorer.quickExpandWithJavaScript(); loader.waitOnClosed(); } @BeforeMethod public void setCurrentFieldForTest(Method method) throws IOException, URISyntaxException { setFieldsForTest(method.getName()); } @AfterMethod public void closeForm() { try { if (refactorPanel.isWidgetOpened()) { loader.waitOnClosed(); refactorPanel.clickCancelButtonRefactorForm(); } editor.closeAllTabs(); } catch (WebDriverException e) { LOG.error(e.getLocalizedMessage(), e); } } @Test public void test0() { testCase(); } @Test(priority = 1) public void test1() { testCase(); } @Test(priority = 2) public void test2() { testCase(); } @Test(priority = 3) public void test3() { testCase(); } @Test(priority = 4) public void test4() { testCase(); } @Test(priority = 5) public void test5() { testCase(); } @Test(priority = 6) public void test6() { testCase(); } @Test(priority = 7) public void test7() { testCase(); } @Test(priority = 8) public void test8() { testCase(); } @Test(priority = 9) public void test9() { testCase(); } private void setFieldsForTest(String nameCurrentTest) throws URISyntaxException, IOException { pathToCurrentPackage = PATH_TO_PACKAGE_IN_CHE_PREFIX + "/" + nameCurrentTest; URL resourcesInA = getClass() .getResource( "/org/eclipse/che/selenium/refactor/types/" + nameCurrentTest + "/in/A.java"); URL resourcesOutA = getClass() .getResource( "/org/eclipse/che/selenium/refactor/types/" + nameCurrentTest + "/out/B.java"); contentFromInA = getTextFromFile(resourcesInA); contentFromOutB = getTextFromFile(resourcesOutA); } private String getTextFromFile(URL url) throws URISyntaxException, IOException { String result = ""; List<String> listWithAllLines = Files.readAllLines(Paths.get(url.toURI()), Charset.forName("UTF-8")); for (String buffer : listWithAllLines) { result += buffer + '\n'; } return result; } private void testCase() { projectExplorer.openItemByPath(pathToCurrentPackage + "/A.java"); editor.waitTextIntoEditor(contentFromInA); projectExplorer.waitAndSelectItem(pathToCurrentPackage + "/A.java"); menu.runCommand( TestMenuCommandsConstants.Assistant.ASSISTANT, TestMenuCommandsConstants.Assistant.Refactoring.REFACTORING, TestMenuCommandsConstants.Assistant.Refactoring.RENAME); refactorPanel.typeAndWaitNewName("B.java"); try { refactorPanel.clickOkButtonRefactorForm(); } catch (TimeoutException ex) { // remove try-catch block after issue has been resolved fail("Known issue https://github.com/eclipse/che/issues/7500", ex); } askDialog.waitFormToOpen(); askDialog.clickOkBtn(); askDialog.waitFormToClose(); refactorPanel.waitRefactorPreviewFormIsClosed(); projectExplorer.waitItem(pathToCurrentPackage + "/B.java", 6); editor.waitTextIntoEditor(contentFromOutB); } }
package dr.app.beauti.generator; import dr.app.beast.BeastVersion; import dr.app.beauti.BeautiFrame; import dr.app.beauti.components.ComponentFactory; import dr.app.beauti.options.*; import dr.app.beauti.types.*; import dr.app.beauti.util.XMLWriter; import dr.app.util.Arguments; import dr.evolution.alignment.Alignment; import dr.evolution.alignment.Patterns; import dr.evolution.datatype.ContinuousDataType; import dr.evolution.datatype.DataType; import dr.evolution.datatype.GeneralDataType; import dr.evolution.datatype.Microsatellite; import dr.evolution.util.Taxa; import dr.evolution.util.Taxon; import dr.evolution.util.TaxonList; import dr.evolution.util.Units; import dr.evomodelxml.speciation.MultiSpeciesCoalescentParser; import dr.evomodelxml.speciation.SpeciationLikelihoodParser; import dr.evoxml.AlignmentParser; import dr.evoxml.DateParser; import dr.evoxml.TaxaParser; import dr.evoxml.TaxonParser; import dr.inferencexml.distribution.MixedDistributionLikelihoodParser; import dr.inferencexml.model.CompoundLikelihoodParser; import dr.inferencexml.model.CompoundParameterParser; import dr.inferencexml.operators.SimpleOperatorScheduleParser; import dr.util.Attribute; import dr.util.Version; import dr.xml.AttributeParser; import dr.xml.XMLParser; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This class holds all the data for the current BEAUti Document * * @author Andrew Rambaut * @author Alexei Drummond * @author Walter Xie * @version $Id: BeastGenerator.java,v 1.4 2006/09/05 13:29:34 rambaut Exp $ */ public class BeastGenerator extends Generator { private final static Version version = new BeastVersion(); private static final String MESSAGE_CAL_YULE = "Calibrated Yule requires 1 calibrated internal node \n" + "with a proper prior and monophyly enforced for each tree."; private final String MESSAGE_CAL = "\nas another element (taxon, sequence, taxon set, species, etc.):\nAll ids should be unique."; private final AlignmentGenerator alignmentGenerator; private final PatternListGenerator patternListGenerator; private final TreePriorGenerator treePriorGenerator; private final TreeLikelihoodGenerator treeLikelihoodGenerator; private final SubstitutionModelGenerator substitutionModelGenerator; private final InitialTreeGenerator initialTreeGenerator; private final TreeModelGenerator treeModelGenerator; private final BranchRatesModelGenerator branchRatesModelGenerator; private final OperatorsGenerator operatorsGenerator; private final ParameterPriorGenerator parameterPriorGenerator; private final LogGenerator logGenerator; // private final DiscreteTraitGenerator discreteTraitGenerator; private final STARBEASTGenerator starBeastGenerator; private final TMRCAStatisticsGenerator tmrcaStatisticsGenerator; public BeastGenerator(BeautiOptions options, ComponentFactory[] components) { super(options, components); alignmentGenerator = new AlignmentGenerator(options, components); patternListGenerator = new PatternListGenerator(options, components); tmrcaStatisticsGenerator = new TMRCAStatisticsGenerator(options, components); substitutionModelGenerator = new SubstitutionModelGenerator(options, components); treePriorGenerator = new TreePriorGenerator(options, components); treeLikelihoodGenerator = new TreeLikelihoodGenerator(options, components); initialTreeGenerator = new InitialTreeGenerator(options, components); treeModelGenerator = new TreeModelGenerator(options, components); branchRatesModelGenerator = new BranchRatesModelGenerator(options, components); operatorsGenerator = new OperatorsGenerator(options, components); parameterPriorGenerator = new ParameterPriorGenerator(options, components); logGenerator = new LogGenerator(options, components); // this has moved into the component system... // discreteTraitGenerator = new DiscreteTraitGenerator(options, components); starBeastGenerator = new STARBEASTGenerator(options, components); } public void checkOptions() throws GeneratorException { //++++++++++++++ Microsatellite +++++++++++++++ // this has to execute before all checking below // mask all ? from microsatellite data for whose tree only has 1 data partition try{ if (options.contains(Microsatellite.INSTANCE)) { // clear all masks for (PartitionPattern partitionPattern : options.getPartitionPattern()) { partitionPattern.getPatterns().clearMask(); } // set mask for (PartitionTreeModel model : options.getPartitionTreeModels()) { // if a tree only has 1 data partition, which mostly mean unlinked trees if (options.getDataPartitions(model).size() == 1) { PartitionPattern partition = (PartitionPattern) options.getDataPartitions(model).get(0); Patterns patterns = partition.getPatterns(); for (int i = 0; i < patterns.getTaxonCount(); i++) { int state = patterns.getPatternState(i, 0); // mask ? from data if (state < 0) { patterns.addMask(i); } } // System.out.println("mask set = " + patterns.getMaskSet() + " in partition " + partition.getName()); } } } } catch (Exception e) { throw new GeneratorException(e.getMessage()); } //++++++++++++++++ Taxon List ++++++++++++++++++ TaxonList taxonList = options.taxonList; Set<String> ids = new HashSet<String>(); ids.add(TaxaParser.TAXA); ids.add(AlignmentParser.ALIGNMENT); ids.add(TraitData.TRAIT_SPECIES); if (taxonList != null) { if (taxonList.getTaxonCount() < 2) { throw new GeneratorException("BEAST requires at least two taxa to run."); } for (int i = 0; i < taxonList.getTaxonCount(); i++) { Taxon taxon = taxonList.getTaxon(i); if (ids.contains(taxon.getId())) { throw new GeneratorException("A taxon has the same id," + taxon.getId() + MESSAGE_CAL); } ids.add(taxon.getId()); } } //++++++++++++++++ Taxon Sets ++++++++++++++++++ for (PartitionTreeModel model : options.getPartitionTreeModels()) { // should be only 1 calibrated internal node with a proper prior and monophyletic for each tree at moment if (model.getPartitionTreePrior().getNodeHeightPrior() == TreePriorType.YULE_CALIBRATION) { if (options.treeModelOptions.isNodeCalibrated(model) < 0) // invalid node calibration throw new GeneratorException(MESSAGE_CAL_YULE); if (options.treeModelOptions.isNodeCalibrated(model) > 0) { // internal node calibration List taxonSetsList = options.getKeysFromValue(options.taxonSetsTreeModel, model); if (taxonSetsList.size() != 1 || !options.taxonSetsMono.get(taxonSetsList.get(0))) { // 1 tmrca per tree && monophyletic throw new GeneratorException(MESSAGE_CAL_YULE, BeautiFrame.TAXON_SETS); } } } } for (Taxa taxa : options.taxonSets) { // AR - we should allow single taxon taxon sets... if (taxa.getTaxonCount() < 1 // && !options.taxonSetsIncludeStem.get(taxa) ) { throw new GeneratorException( "Taxon set, " + taxa.getId() + ", should contain \n" + "at least one taxa. Please go back to Taxon Sets \n" + "panel to correct this.", BeautiFrame.TAXON_SETS); } if (ids.contains(taxa.getId())) { throw new GeneratorException("A taxon set has the same id," + taxa.getId() + MESSAGE_CAL, BeautiFrame.TAXON_SETS); } ids.add(taxa.getId()); } //++++++++++++++++ *BEAST ++++++++++++++++++ if (options.useStarBEAST) { if (!options.traitExists(TraitData.TRAIT_SPECIES)) throw new GeneratorException("A trait labelled \"species\" is required for *BEAST species designations." + "\nPlease create or import the species designations in the Traits table.", BeautiFrame.TRAITS); //++++++++++++++++ Species Sets ++++++++++++++++++ // should be only 1 calibrated internal node with monophyletic at moment if (options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_YULE_CALIBRATION) { if (options.speciesSets.size() != 1 || !options.speciesSetsMono.get(options.speciesSets.get(0))) { throw new GeneratorException(MESSAGE_CAL_YULE, BeautiFrame.TAXON_SETS); } } for (Taxa species : options.speciesSets) { if (species.getTaxonCount() < 2) { throw new GeneratorException("Species set, " + species.getId() + ",\n should contain" + "at least two species. \nPlease go back to Species Sets panel to select included species.", BeautiFrame.TAXON_SETS); } if (ids.contains(species.getId())) { throw new GeneratorException("A species set has the same id," + species.getId() + MESSAGE_CAL, BeautiFrame.TAXON_SETS); } ids.add(species.getId()); } int tId = options.starBEASTOptions.getEmptySpeciesIndex(); if (tId >= 0) { throw new GeneratorException("The taxon " + options.taxonList.getTaxonId(tId) + " has NULL value for \"species\" trait", BeautiFrame.TRAITS); } } //++++++++++++++++ Traits ++++++++++++++++++ // missing data is not necessarily an issue... // for (TraitData trait : options.traits) { // for (int i = 0; i < trait.getTaxaCount(); i++) { //// System.out.println("Taxon " + trait.getTaxon(i).getId() + " : [" + trait.getTaxon(i).getAttribute(trait.getName()) + "]"); // if (!trait.hasValue(i)) // " has no value for Trait " + trait.getName()); //++++++++++++++++ Tree Prior ++++++++++++++++++ // if (options.isShareSameTreePrior()) { if (options.getPartitionTreeModels().size() > 1) { //TODO not allowed multi-prior yet for (PartitionTreePrior prior : options.getPartitionTreePriors()) { if (prior.getNodeHeightPrior() == TreePriorType.GMRF_SKYRIDE) { throw new GeneratorException("For GMRF, tree model/tree prior combination not implemented by BEAST yet" + "\nIt is only available for single tree model partition for this release.", BeautiFrame.TREES); } } } //+++++++++++++++ Starting tree ++++++++++++++++ for (PartitionTreeModel model : options.getPartitionTreeModels()) { if (model.getStartingTreeType() == StartingTreeType.USER) { if (model.getUserStartingTree() == null) { throw new GeneratorException("Please select a starting tree in " + BeautiFrame.TREES + " panel, " + "\nwhen choosing user specified starting tree option.", BeautiFrame.TREES); } } } //++++++++++++++++ Random local clock model validation ++++++++++++++++++ for (PartitionClockModel model : options.getPartitionClockModels()) { // 1 random local clock CANNOT have different tree models if (model.getClockType() == ClockType.RANDOM_LOCAL_CLOCK) { // || AUTOCORRELATED_LOGNORMAL PartitionTreeModel treeModel = null; for (AbstractPartitionData pd : options.getDataPartitions(model)) { // only the PDs linked to this tree model if (treeModel != null && treeModel != pd.getPartitionTreeModel()) { throw new GeneratorException("A single random local clock cannot be applied to multiple trees.", BeautiFrame.CLOCK_MODELS); } treeModel = pd.getPartitionTreeModel(); } } } //++++++++++++++++ Tree Model ++++++++++++++++++ for (PartitionTreeModel model : options.getPartitionTreeModels()) { int numOfTaxa = -1; for (AbstractPartitionData pd : options.getDataPartitions(model)) { if (pd.getTaxonCount() > 0) { if (numOfTaxa > 0) { if (numOfTaxa != pd.getTaxonCount()) { throw new GeneratorException("Partitions with different taxa cannot share the same tree.", BeautiFrame.DATA_PARTITIONS); } } else { numOfTaxa = pd.getTaxonCount(); } } } } //++++++++++++++++ Prior Bounds ++++++++++++++++++ for (Parameter param : options.selectParameters()) { if (param.initial != Double.NaN) { if (param.isTruncated && (param.initial < param.truncationLower || param.initial > param.truncationUpper)) { throw new GeneratorException("Parameter \"" + param.getName() + "\":" + "\ninitial value " + param.initial + " is NOT in the range [" + param.truncationLower + ", " + param.truncationUpper + "]," + "\nor this range is wrong. Please check the Prior panel.", BeautiFrame.PRIORS); } else if (param.priorType == PriorType.UNIFORM_PRIOR && (param.initial < param.uniformLower || param.initial > param.uniformUpper)) { throw new GeneratorException("Parameter \"" + param.getName() + "\":" + "\ninitial value " + param.initial + " is NOT in the range [" + param.uniformLower + ", " + param.uniformUpper + "]," + "\nor this range is wrong. Please check the Prior panel.", BeautiFrame.PRIORS); } if (param.isNonNegative && param.initial < 0.0) { throw new GeneratorException("Parameter \"" + param.getName() + "\":" + "\ninitial value " + param.initial + " should be non-negative. Please check the Prior panel.", BeautiFrame.PRIORS); } if (param.isZeroOne && (param.initial < 0.0 || param.initial > 1.0)) { throw new GeneratorException("Parameter \"" + param.getName() + "\":" + "\ninitial value " + param.initial + " should lie in the interval [0, 1]. Please check the Prior panel.", BeautiFrame.PRIORS); } } } // add other tests and warnings here // Speciation model with dated tips // Sampling rates without dated tips or priors on rate or nodes } /** * Generate a beast xml file from these beast options * * @param file File * @throws java.io.IOException IOException * @throws dr.app.util.Arguments.ArgumentException * ArgumentException */ public void generateXML(File file) throws GeneratorException, IOException, Arguments.ArgumentException { XMLWriter writer = new XMLWriter(new BufferedWriter(new FileWriter(file))); writer.writeText("<?xml version=\"1.0\" standalone=\"yes\"?>"); writer.writeComment("Generated by BEAUTi " + version.getVersionString(), " by Alexei J. Drummond, Andrew Rambaut and Marc A. Suchard", " Department of Computer Science, University of Auckland and", " Institute of Evolutionary Biology, University of Edinburgh", " David Geffen School of Medicine, University of California, Los Angeles", " http://beast.bio.ed.ac.uk/"); writer.writeOpenTag("beast"); writer.writeText(""); // this gives any added implementations of the 'Component' interface a // chance to generate XML at this point in the BEAST file. generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_TAXA, writer); if (options.originDate != null) { // Create a dummy taxon whose job is to specify the origin date Taxon originTaxon = new Taxon("originTaxon"); options.originDate.setUnits(options.units); originTaxon.setDate(options.originDate); writeTaxon(originTaxon, true, false, writer); } //++++++++++++++++ Taxon List ++++++++++++++++++ try { // write complete taxon list writeTaxa(options.taxonList, writer); writer.writeText(""); if (!options.hasIdenticalTaxa()) { // write all taxa in each gene tree regarding each data partition, for (AbstractPartitionData partition : options.dataPartitions) { if (partition.getTaxonList() != null) { writeDifferentTaxa(partition, writer); } } } else { // microsat for (PartitionPattern partitionPattern : options.getPartitionPattern()) { if (partitionPattern.getTaxonList() != null && partitionPattern.getPatterns().hasMask()) { writeDifferentTaxa(partitionPattern, writer); } } } } catch (Exception e) { System.err.println(e); throw new GeneratorException("Taxon list generation has failed:\n" + e.getMessage()); } //++++++++++++++++ Taxon Sets ++++++++++++++++++ List<Taxa> taxonSets = options.taxonSets; try { if (taxonSets != null && taxonSets.size() > 0 && !options.useStarBEAST) { tmrcaStatisticsGenerator.writeTaxonSets(writer, taxonSets); } } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Taxon sets generation has failed:\n" + e.getMessage()); } generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TAXA, writer); //++++++++++++++++ Alignments ++++++++++++++++++ List<Alignment> alignments = new ArrayList<Alignment>(); try { for (AbstractPartitionData partition : options.dataPartitions) { Alignment alignment = null; if (partition instanceof PartitionData) { // microsat has no alignment alignment = ((PartitionData) partition).getAlignment(); } if (alignment != null && !alignments.contains(alignment)) { alignments.add(alignment); } } if (alignments.size() > 0) { alignmentGenerator.writeAlignments(alignments, writer); generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer); } } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Alignments generation has failed:\n" + e.getMessage()); } //++++++++++++++++ Pattern Lists ++++++++++++++++++ try { if (!options.samplePriorOnly) { List<Microsatellite> microsatList = new ArrayList<Microsatellite>(); for (AbstractPartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood if (partition.getTaxonList() != null) { switch (partition.getDataType().getType()) { case DataType.NUCLEOTIDES: case DataType.AMINO_ACIDS: case DataType.CODONS: case DataType.COVARION: case DataType.TWO_STATES: patternListGenerator.writePatternList((PartitionData) partition, writer); break; case DataType.GENERAL: case DataType.CONTINUOUS: // no patternlist for trait data - discrete (general) data type uses an // attribute patterns which is generated next bit of this method. break; case DataType.MICRO_SAT: // microsat does not have alignment patternListGenerator.writePatternList((PartitionPattern) partition, microsatList, writer); break; default: throw new IllegalArgumentException("Unsupported data type"); } writer.writeText(""); } } } } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Pattern lists generation has failed:\n" + e.getMessage()); } generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer); //++++++++++++++++ Tree Prior Model ++++++++++++++++++ try { for (PartitionTreePrior prior : options.getPartitionTreePriors()) { treePriorGenerator.writeTreePriorModel(prior, writer); writer.writeText(""); } } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Tree prior model generation has failed:\n" + e.getMessage()); } //++++++++++++++++ Starting Tree ++++++++++++++++++ try { for (PartitionTreeModel model : options.getPartitionTreeModels()) { initialTreeGenerator.writeStartingTree(model, writer); writer.writeText(""); } } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Starting tree generation has failed:\n" + e.getMessage()); } //++++++++++++++++ Tree Model +++++++++++++++++++ try { for (PartitionTreeModel model : options.getPartitionTreeModels()) { treeModelGenerator.writeTreeModel(model, writer); writer.writeText(""); } generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_MODEL, writer); } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Tree model generation has failed:\n" + e.getMessage()); } //++++++++++++++++ Statistics ++++++++++++++++++ try { if (taxonSets != null && taxonSets.size() > 0 && !options.useStarBEAST) { tmrcaStatisticsGenerator.writeTMRCAStatistics(writer); } } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("TMRCA statistics generation has failed:\n" + e.getMessage()); } //++++++++++++++++ Tree Prior Likelihood ++++++++++++++++++ try { for (PartitionTreeModel model : options.getPartitionTreeModels()) { treePriorGenerator.writePriorLikelihood(model, writer); writer.writeText(""); } for (PartitionTreePrior prior : options.getPartitionTreePriors()) { treePriorGenerator.writeEBSPVariableDemographic(prior, writer); } generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_PRIOR, writer); } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Tree prior likelihood generation has failed:\n" + e.getMessage()); } //++++++++++++++++ Branch Rates Model ++++++++++++++++++ try { for (PartitionClockModel model : options.getPartitionClockModels()) { branchRatesModelGenerator.writeBranchRatesModel(model, writer); writer.writeText(""); } // write allClockRate for fix mean option in clock model panel for (ClockModelGroup clockModelGroup : options.clockModelOptions.getClockModelGroups()) { if (clockModelGroup.getRateTypeOption() == FixRateType.FIX_MEAN) { writer.writeOpenTag(CompoundParameterParser.COMPOUND_PARAMETER, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, clockModelGroup.getName())}); for (PartitionClockModel model : options.getPartitionClockModels(clockModelGroup)) { branchRatesModelGenerator.writeAllClockRateRefs(model, writer); } writer.writeCloseTag(CompoundParameterParser.COMPOUND_PARAMETER); writer.writeText(""); } } } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Branch rates model generation is failed:\n" + e.getMessage()); } //++++++++++++++++ Substitution Model & Site Model ++++++++++++++++++ try { for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) { substitutionModelGenerator.writeSubstitutionSiteModel(model, writer); substitutionModelGenerator.writeAllMus(model, writer); // allMus writer.writeText(""); } generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SUBSTITUTION_MODEL, writer); } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Substitution model or site model generation has failed:\n" + e.getMessage()); } //++++++++++++++++ Site Model ++++++++++++++++++ // for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) { // substitutionModelGenerator.writeSiteModel(model, writer); // site model // substitutionModelGenerator.writeAllMus(model, writer); // allMus // writer.writeText(""); generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SITE_MODEL, writer); //++++++++++++++++ Tree Likelihood ++++++++++++++++++ try { for (AbstractPartitionData partition : options.dataPartitions) { // generate tree likelihoods for alignment data partitions if (partition.getTaxonList() != null) { if (partition instanceof PartitionData) { if (partition.getDataType() != GeneralDataType.INSTANCE && partition.getDataType() != ContinuousDataType.INSTANCE) { treeLikelihoodGenerator.writeTreeLikelihood((PartitionData) partition, writer); writer.writeText(""); } } else if (partition instanceof PartitionPattern) { // microsat treeLikelihoodGenerator.writeTreeLikelihood((PartitionPattern) partition, writer); writer.writeText(""); } else { throw new GeneratorException("Find unrecognized partition:\n" + partition.getName()); } } } generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_LIKELIHOOD, writer); } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Tree likelihood generation has failed:\n" + e.getMessage()); } //++++++++++++++++ *BEAST ++++++++++++++++++ if (options.useStarBEAST) { //++++++++++++++++ species ++++++++++++++++++ try { starBeastGenerator.writeSpecies(writer); } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("*BEAST species section generation has failed:\n" + e.getMessage()); } //++++++++++++++++ Species Sets ++++++++++++++++++ List<Taxa> speciesSets = options.speciesSets; try { if (speciesSets != null && speciesSets.size() > 0) { tmrcaStatisticsGenerator.writeTaxonSets(writer, speciesSets); } } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Species sets generation has failed:\n" + e.getMessage()); } //++++++++++++++++ trees ++++++++++++++++++ try { if (speciesSets != null && speciesSets.size() > 0) { starBeastGenerator.writeStartingTreeForCalibration(writer); } starBeastGenerator.writeSpeciesTree(writer, speciesSets != null && speciesSets.size() > 0); } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("*BEAST trees generation has failed:\n" + e.getMessage()); } //++++++++++++++++ Statistics ++++++++++++++++++ try { if (speciesSets != null && speciesSets.size() > 0) { tmrcaStatisticsGenerator.writeTMRCAStatistics(writer); } } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("*BEAST TMRCA statistics generation has failed:\n" + e.getMessage()); } //++++++++++++++++ prior and likelihood ++++++++++++++++++ try { starBeastGenerator.writeSTARBEAST(writer); } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("*BEAST trees section generation has failed:\n" + e.getMessage()); } } generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TRAITS, writer); //++++++++++++++++ Operators ++++++++++++++++++ try { List<Operator> operators = options.selectOperators(); operatorsGenerator.writeOperatorSchedule(operators, writer); writer.writeText(""); generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_OPERATORS, writer); } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("Operators generation has failed:\n" + e.getMessage()); } //++++++++++++++++ MCMC ++++++++++++++++++ try { // XMLWriter writer, List<PartitionSubstitutionModel> models, writeMCMC(writer); writer.writeText(""); generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_MCMC, writer); } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("MCMC or log generation has failed:\n" + e.getMessage()); } try { writeTimerReport(writer); writer.writeText(""); if (options.performTraceAnalysis) { writeTraceAnalysis(writer); } if (options.generateCSV) { for (PartitionTreePrior prior : options.getPartitionTreePriors()) { treePriorGenerator.writeEBSPAnalysisToCSVfile(prior, writer); } } } catch (Exception e) { e.printStackTrace(); throw new GeneratorException("The last part of XML generation has failed:\n" + e.getMessage()); } writer.writeCloseTag("beast"); writer.flush(); writer.close(); } /** * Generate a taxa block from these beast options * * @param writer the writer * @param taxonList the taxon list to write * @throws dr.app.util.Arguments.ArgumentException * ArgumentException */ private void writeTaxa(TaxonList taxonList, XMLWriter writer) throws Arguments.ArgumentException { // -1 (single taxa), 0 (1st gene of multi-taxa) writer.writeComment("The list of taxa to be analysed (can also include dates/ages).", "ntax=" + taxonList.getTaxonCount()); writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, TaxaParser.TAXA)}); boolean hasAttr = options.traits.size() > 0; boolean firstDate = true; for (int i = 0; i < taxonList.getTaxonCount(); i++) { Taxon taxon = taxonList.getTaxon(i); boolean hasDate = false; if (options.clockModelOptions.isTipCalibrated()) { hasDate = TaxonList.Utils.hasAttribute(taxonList, i, dr.evolution.util.Date.DATE); } if (hasDate) { dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE); if (firstDate) { options.units = date.getUnits(); firstDate = false; } else { if (options.units != date.getUnits()) { System.err.println("Error: Units in dates do not match."); } } } writeTaxon(taxon, hasDate, hasAttr, writer); } writer.writeCloseTag(TaxaParser.TAXA); } /** * Generate a taxa block from these beast options * * @param writer the writer * @param taxon the taxon to write * @throws dr.app.util.Arguments.ArgumentException * ArgumentException */ private void writeTaxon(Taxon taxon, boolean hasDate, boolean hasAttr, XMLWriter writer) throws Arguments.ArgumentException { writer.writeTag(TaxonParser.TAXON, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, taxon.getId())}, !(hasDate || hasAttr)); // false if any of hasDate or hasAttr is true if (hasDate) { dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE); Attribute[] attributes; if (date.getPrecision() > 0.0) { attributes = new Attribute[] { new Attribute.Default<Double>(DateParser.VALUE, date.getTimeValue()), new Attribute.Default<String>(DateParser.DIRECTION, date.isBackwards() ? DateParser.BACKWARDS : DateParser.FORWARDS), new Attribute.Default<String>(DateParser.UNITS, Units.Utils.getDefaultUnitName(options.units)), new Attribute.Default<Double>(DateParser.PRECISION, date.getPrecision()) }; } else { attributes = new Attribute[] { new Attribute.Default<Double>(DateParser.VALUE, date.getTimeValue()), new Attribute.Default<String>(DateParser.DIRECTION, date.isBackwards() ? DateParser.BACKWARDS : DateParser.FORWARDS), new Attribute.Default<String>(DateParser.UNITS, Units.Utils.getDefaultUnitName(options.units)) //new Attribute.Default("origin", date.getOrigin()+"") }; } writer.writeTag(dr.evolution.util.Date.DATE, attributes, true); } for (TraitData trait : options.traits) { // there is no harm in allowing the species trait to be listed in the taxa // if (!trait.getName().equalsIgnoreCase(TraitData.TRAIT_SPECIES)) { writer.writeOpenTag(AttributeParser.ATTRIBUTE, new Attribute[]{ new Attribute.Default<String>(Attribute.NAME, trait.getName())}); // denotes missing data using '?' writer.writeText(taxon.containsAttribute(trait.getName()) ? taxon.getAttribute(trait.getName()).toString() : "?"); writer.writeCloseTag(AttributeParser.ATTRIBUTE); } generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TAXON, taxon, writer); if (hasDate || hasAttr) writer.writeCloseTag(TaxonParser.TAXON); } public void writeDifferentTaxa(AbstractPartitionData dataPartition, XMLWriter writer) { TaxonList taxonList = dataPartition.getTaxonList(); String name = dataPartition.getName(); writer.writeComment("gene name = " + name + ", ntax= " + taxonList.getTaxonCount()); writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, name + "." + TaxaParser.TAXA)}); for (int i = 0; i < taxonList.getTaxonCount(); i++) { if ( !(dataPartition instanceof PartitionPattern && ((PartitionPattern) dataPartition).getPatterns().isMasked(i) ) ) { final Taxon taxon = taxonList.getTaxon(i); writer.writeIDref(TaxonParser.TAXON, taxon.getId()); } } writer.writeCloseTag(TaxaParser.TAXA); } /** * Write the timer report block. * * @param writer the writer */ public void writeTimerReport(XMLWriter writer) { writer.writeOpenTag("report"); writer.writeOpenTag("property", new Attribute.Default<String>("name", "timer")); writer.writeIDref("mcmc", "mcmc"); writer.writeCloseTag("property"); writer.writeCloseTag("report"); } /** * Write the trace analysis block. * * @param writer the writer */ public void writeTraceAnalysis(XMLWriter writer) { writer.writeTag( "traceAnalysis", new Attribute[]{ new Attribute.Default<String>("fileName", options.logFileName) }, true ); } /** * Write the MCMC block. * * @param writer XMLWriter */ public void writeMCMC(XMLWriter writer) { writer.writeComment("Define MCMC"); List<Attribute> attributes = new ArrayList<Attribute>(); attributes.add(new Attribute.Default<String>(XMLParser.ID, "mcmc")); attributes.add(new Attribute.Default<Integer>("chainLength", options.chainLength)); attributes.add(new Attribute.Default<String>("autoOptimize", options.autoOptimize ? "true" : "false")); if (options.operatorAnalysis) { attributes.add(new Attribute.Default<String>("operatorAnalysis", options.operatorAnalysisFileName)); } writer.writeOpenTag("mcmc", attributes); if (options.hasData()) { writer.writeOpenTag(CompoundLikelihoodParser.POSTERIOR, new Attribute.Default<String>(XMLParser.ID, "posterior")); } // write prior block writer.writeOpenTag(CompoundLikelihoodParser.PRIOR, new Attribute.Default<String>(XMLParser.ID, "prior")); if (options.useStarBEAST) { // species // coalescent prior writer.writeIDref(MultiSpeciesCoalescentParser.SPECIES_COALESCENT, TraitData.TRAIT_SPECIES + "." + COALESCENT); // prior on population sizes // if (options.speciesTreePrior == TreePriorType.SPECIES_YULE) { writer.writeIDref(MixedDistributionLikelihoodParser.DISTRIBUTION_LIKELIHOOD, SPOPS); // } else { // writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP); // prior on species tree writer.writeIDref(SpeciationLikelihoodParser.SPECIATION_LIKELIHOOD, SPECIATION_LIKE); } parameterPriorGenerator.writeParameterPriors(writer, options.useStarBEAST); for (PartitionTreeModel model : options.getPartitionTreeModels()) { PartitionTreePrior prior = model.getPartitionTreePrior(); treePriorGenerator.writePriorLikelihoodReference(prior, model, writer); writer.writeText(""); } for (PartitionTreePrior prior : options.getPartitionTreePriors()) { treePriorGenerator.writeEBSPVariableDemographicReference(prior, writer); writer.writeText(""); } generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_PRIOR, writer); writer.writeCloseTag(CompoundLikelihoodParser.PRIOR); if (options.hasData()) { // write likelihood block writer.writeOpenTag(CompoundLikelihoodParser.LIKELIHOOD, new Attribute.Default<String>(XMLParser.ID, "likelihood")); treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer); branchRatesModelGenerator.writeClockLikelihoodReferences(writer); generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_LIKELIHOOD, writer); writer.writeCloseTag(CompoundLikelihoodParser.LIKELIHOOD); writer.writeCloseTag(CompoundLikelihoodParser.POSTERIOR); } writer.writeIDref(SimpleOperatorScheduleParser.OPERATOR_SCHEDULE, "operators"); // write log to screen logGenerator.writeLogToScreen(writer, branchRatesModelGenerator, substitutionModelGenerator); // write log to file logGenerator.writeLogToFile(writer, treePriorGenerator, branchRatesModelGenerator, substitutionModelGenerator, treeLikelihoodGenerator); // write tree log to file logGenerator.writeTreeLogToFile(writer); writer.writeCloseTag("mcmc"); } }
package org.beanmaker.util; import org.dbbeans.util.Strings; import org.jcodegen.html.ATag; import org.jcodegen.html.InputTag; import org.jcodegen.html.OptionTag; import org.jcodegen.html.SelectTag; import org.jcodegen.html.SpanTag; import org.jcodegen.html.TableTag; import org.jcodegen.html.Tag; import org.jcodegen.html.TbodyTag; import org.jcodegen.html.TdTag; import org.jcodegen.html.ThTag; import org.jcodegen.html.TheadTag; import org.jcodegen.html.TrTag; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.text.DateFormat; import java.util.List; public abstract class BaseMasterTableView extends BaseView { protected final String tableId; protected String tableCssClass = "cctable"; protected String thResetCssClass = null; protected String tdResetCssClass = null; protected String thFilterCssClass = null; protected String tdFilterCssClass = null; protected String thTitleCssClass = "tb-sort"; protected String formElementFilterCssClass = "tb-filter"; protected String removeFilteringLinkCssClass = "tb-nofilter"; protected Tag removeFilteringHtmlTags = new SpanTag().cssClass("glyphicon glyphicon-remove").title("Remove Filtering"); protected String yesName = "yes"; protected String noName = "no"; protected String yesValue = "A"; protected String noValue = "Z"; protected String yesDisplay = ""; protected String noDisplay = ""; protected DateFormat dateFormat = null; protected DateFormat timeFormat = null; protected DateFormat datetimeFormat = null; protected String booleanCenterValueCssClass = "center"; protected int zeroFilledMaxDigits = 18; protected boolean displayId = false; public BaseMasterTableView(final String resourceBundleName, final String tableId) { super(resourceBundleName); this.tableId = tableId; } public String getMasterTable() { return getTable().child(getHead()).child(getBody()).toString(); } protected TableTag getTable() { return new TableTag().cssClass(tableCssClass).id(tableId); } protected TheadTag getHead() { final TheadTag head = new TheadTag(); head.child(getFilterRow()); head.child(getTitleRow()); return head; } protected TbodyTag getBody() { final TbodyTag body = new TbodyTag(); for (TrTag tr: getData()) body.child(tr); return body; } protected abstract List<TrTag> getData(); protected TrTag getFilterRow() { return getDefaultStartOfFilterRow(); } protected TrTag getTitleRow() { return getDefaultStartOfTitleRow(); } protected TrTag getDefaultStartOfFilterRow() { return new TrTag().child(getRemoveFilteringCellWithLink()); } protected TrTag getDefaultStartOfTitleRow() { return new TrTag().child(getRemoveFilteringCell()); } protected ThTag getRemoveFilteringCellWithLink() { return getRemoveFilteringCell().child( new ATag().href("#").cssClass(removeFilteringLinkCssClass).child(removeFilteringHtmlTags) ); } protected ThTag getRemoveFilteringCell() { final ThTag cell = new ThTag(); if (thResetCssClass != null) cell.cssClass(thResetCssClass); return cell; } protected ThTag getTableFilterCell() { final ThTag cell = new ThTag(); if (thFilterCssClass != null) cell.cssClass(thFilterCssClass); return cell; } protected ThTag getStringFilterCell(final String name) { return getTableFilterCell().child( new InputTag(InputTag.InputType.TEXT).name("tb-" + name).cssClass(formElementFilterCssClass).attribute("autocomplete", "off") ); } protected ThTag getBooleanFilterCell(final String name) { return getTableFilterCell().child( new SelectTag().name(name).cssClass(formElementFilterCssClass).child( new OptionTag("", "").selected() ).child( new OptionTag(yesName, yesValue) ).child( new OptionTag(noName, noValue) ) ); } protected ThTag getTitleCell(final String name) { return getTitleCell(name, resourceBundle.getString(name)); } protected ThTag getTitleCell(final String name, final String adhocTitle) { return new ThTag(adhocTitle).cssClass(thTitleCssClass).attribute("data-sort-class", "tb-" + name); } protected ThTag getTitleCell(final String name, final Tag adhocTitle) { return new ThTag().cssClass(thTitleCssClass).attribute("data-sort-class", "tb-" + name).child(adhocTitle); } protected TrTag getTableLine() { final TrTag line = new TrTag(); line.child(getTableCellForRemoveFilteringPlaceholder()); return line; } protected TdTag getTableCellForRemoveFilteringPlaceholder() { final TdTag cell = new TdTag(); if (tdResetCssClass != null) cell.cssClass(tdResetCssClass); return cell; } protected TdTag getTableCell(final String name, final Tag content) { return new TdTag().child(content).cssClass("tb-" + name); } protected TdTag getTableCell(final String name, final String value) { return new TdTag(value).cssClass("tb-" + name); } protected TdTag getTableCell(final String name, final Date value) { if (dateFormat == null) dateFormat = DateFormat.getDateInstance(); return getTableCell(name, dateFormat.format(value)).attribute("data-sort-value", value.toString()); } protected TdTag getTableCell(final String name, final Time value) { if (timeFormat == null) timeFormat = DateFormat.getTimeInstance(); return getTableCell(name, timeFormat.format(value)).attribute("data-sort-value", value.toString()); } protected TdTag getTableCell(final String name, final Timestamp value) { if (datetimeFormat == null) datetimeFormat = DateFormat.getDateTimeInstance(); return getTableCell(name, datetimeFormat.format(value)).attribute("data-sort-value", value.toString()); } protected TdTag getTableCell(final String name, final boolean value) { if (value) return getTableBooleanCell(name, yesDisplay, yesValue); return getTableBooleanCell(name, noDisplay, noValue); } protected TdTag getTableBooleanCell(final String name, final String value, final String sortnfilter) { return new TdTag(value).cssClass(booleanCenterValueCssClass + " tb-" + name) .attribute("data-filter-value", sortnfilter).attribute("data-sort-value", sortnfilter); } protected TdTag getTableCell(final String name, final long value) { return getTableCell(name, Long.toString(value)).attribute("data-sort-value", Strings.zeroFill(value, zeroFilledMaxDigits)); } }
package dr.evomodel.operators; import dr.evolution.tree.NodeRef; import dr.evomodel.tree.TreeModel; import dr.inference.operators.OperatorFailedException; import dr.math.MathUtils; import dr.xml.*; /** * Implements branch exchange operations. There is a NARROW and WIDE variety. * The narrow exchange is very similar to a rooted-tree nearest-neighbour * interchange but with the restriction that node height must remain consistent. * <p/> * KNOWN BUGS: WIDE operator cannot be used on trees with 4 or less tips! */ public class ExchangeOperator extends AbstractTreeOperator { public static final String NARROW_EXCHANGE = "narrowExchange"; public static final String WIDE_EXCHANGE = "wideExchange"; public static final String INTERMEDIATE_EXCHANGE = "intermediateExchange"; public static final int NARROW = 0; public static final int WIDE = 1; public static final int INTERMEDIATE = 2; private static final int MAX_TRIES = 100; private int mode = NARROW; private final TreeModel tree; private double[] distances; public ExchangeOperator(int mode, TreeModel tree, double weight) { this.mode = mode; this.tree = tree; setWeight(weight); } public double doOperation() throws OperatorFailedException { final int tipCount = tree.getExternalNodeCount(); double hastingsRatio = 0; switch( mode ) { case NARROW: narrow(); break; case WIDE: wide(); break; case INTERMEDIATE: hastingsRatio = intermediate(); break; } assert tree.getExternalNodeCount() == tipCount : "Lost some tips in " + ((mode == NARROW) ? "NARROW mode." : "WIDE mode."); return hastingsRatio; } /** * WARNING: Assumes strictly bifurcating tree. */ public void narrow() throws OperatorFailedException { final int nNodes = tree.getNodeCount(); final NodeRef root = tree.getRoot(); NodeRef i = root; while( root == i || tree.getParent(i) == root ) { i = tree.getNode(MathUtils.nextInt(nNodes)); } final NodeRef iParent = tree.getParent(i); final NodeRef iGrandParent = tree.getParent(iParent); NodeRef iUncle = tree.getChild(iGrandParent, 0); if( iUncle == iParent ) { iUncle = tree.getChild(iGrandParent, 1); } assert iUncle == getOtherChild(tree, iGrandParent, iParent); assert tree.getNodeHeight(i) < tree.getNodeHeight(iGrandParent); if( tree.getNodeHeight(iUncle) < tree.getNodeHeight(iParent) ) { exchangeNodes(tree, i, iUncle, iParent, iGrandParent); // exchangeNodes generates the events //tree.pushTreeChangedEvent(iParent); //tree.pushTreeChangedEvent(iGrandParent); } else { throw new OperatorFailedException("Couldn't find valid narrow move on this tree!!"); } } /** * WARNING: Assumes strictly bifurcating tree. */ public void wide() throws OperatorFailedException { final int nodeCount = tree.getNodeCount(); final NodeRef root = tree.getRoot(); NodeRef i = root; while( root == i ) { i = tree.getNode(MathUtils.nextInt(nodeCount)); } NodeRef j = i; while( j == i || j == root ) { j = tree.getNode(MathUtils.nextInt(nodeCount)); } final NodeRef iP = tree.getParent(i); final NodeRef jP = tree.getParent(j); if( (iP != jP) && (i != jP) && (j != iP) && (tree.getNodeHeight(j) < tree.getNodeHeight(iP)) && (tree.getNodeHeight(i) < tree.getNodeHeight(jP)) ) { exchangeNodes(tree, i, j, iP, jP); // System.out.println("tries = " + tries+1); return; } throw new OperatorFailedException("Couldn't find valid wide move on this tree!"); } /** * @deprecated WARNING: SHOULD NOT BE USED! * WARNING: Assumes strictly bifurcating tree. */ public double intermediate() throws OperatorFailedException { final int nodeCount = tree.getNodeCount(); final NodeRef root = tree.getRoot(); for(int tries = 0; tries < MAX_TRIES; ++tries) { NodeRef i, j; NodeRef[] possibleNodes; do { // get a random node i = root; // tree.getNode(MathUtils.nextInt(nodeCount)); // if (root != i) { // possibleNodes = tree.getNodes(); // check if we got the root while( root == i ) { // if so get another one till we haven't got anymore the // root i = tree.getNode(MathUtils.nextInt(nodeCount)); // if (root != i) { // possibleNodes = tree.getNodes(); } possibleNodes = tree.getNodes(); // get another random node // NodeRef j = tree.getNode(MathUtils.nextInt(nodeCount)); j = getRandomNode(possibleNodes, i); // check if they are the same and if the new node is the root } while( j == null || j == i || j == root ); double forward = getWinningChance(indexOf(possibleNodes, j)); // possibleNodes = getPossibleNodes(j); calcDistances(possibleNodes, j); forward += getWinningChance(indexOf(possibleNodes, i)); // get the parent of both of them final NodeRef iP = tree.getParent(i); final NodeRef jP = tree.getParent(j); // check if both parents are equal -> we are siblings :) (this // wouldnt effect a change on topology) // check if I m your parent or vice versa (this would destroy the // tree) // check if you are younger then my father // check if I m younger then your father if( (iP != jP) && (i != jP) && (j != iP) && (tree.getNodeHeight(j) < tree.getNodeHeight(iP)) && (tree.getNodeHeight(i) < tree.getNodeHeight(jP)) ) { // if 1 & 2 are false and 3 & 4 are true then we found a valid // candidate exchangeNodes(tree, i, j, iP, jP); // possibleNodes = getPossibleNodes(i); calcDistances(possibleNodes, i); double backward = getWinningChance(indexOf(possibleNodes, j)); // possibleNodes = getPossibleNodes(j); calcDistances(possibleNodes, j); backward += getWinningChance(indexOf(possibleNodes, i)); // System.out.println("tries = " + tries+1); return Math.log(Math.min(1, (backward) / (forward))); // return 0.0; } } throw new OperatorFailedException("Couldn't find valid wide move on this tree!"); } /* why not use Arrays.asList(a).indexOf(n) ? */ private int indexOf(NodeRef[] a, NodeRef n) { for(int i = 0; i < a.length; i++) { if( a[i] == n ) { return i; } } return -1; } private double getWinningChance(int index) { double sum = 0; for( double distance : distances ) { sum += (1.0 / distance); } return (1.0 / distances[index]) / sum; } private void calcDistances(NodeRef[] nodes, NodeRef ref) { distances = new double[nodes.length]; for(int i = 0; i < nodes.length; i++) { distances[i] = getNodeDistance(ref, nodes[i]) + 1; } } private NodeRef getRandomNode(NodeRef[] nodes, NodeRef ref) { calcDistances(nodes, ref); double sum = 0; for( double distance : distances ) { sum += 1.0 / distance; } double randomValue = MathUtils.nextDouble() * sum; NodeRef n = null; for(int i = 0; i < distances.length; i++) { randomValue -= 1.0 / distances[i]; if( randomValue <= 0 ) { n = nodes[i]; break; } } return n; } private int getNodeDistance(NodeRef i, NodeRef j) { int count = 0; while( i != j ) { count++; if( tree.getNodeHeight(i) < tree.getNodeHeight(j) ) { i = tree.getParent(i); } else { j = tree.getParent(j); } } return count; } public int getMode() { return mode; } public String getOperatorName() { return ((mode == NARROW) ? "Narrow" : "Wide") + " Exchange" + "(" + tree.getId() + ")"; } public double getMinimumAcceptanceLevel() { if( mode == NARROW ) { return 0.05; } else { return 0.01; } } public double getMinimumGoodAcceptanceLevel() { if( mode == NARROW ) { return 0.05; } else { return 0.01; } } public String getPerformanceSuggestion() { return ""; // if( MCMCOperator.Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel() ) { // return ""; // } else if( MCMCOperator.Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel() ) { // return ""; // } else { // return ""; } public static XMLObjectParser NARROW_EXCHANGE_PARSER = new AbstractXMLObjectParser() { public String getParserName() { return NARROW_EXCHANGE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { final TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); final double weight = xo.getDoubleAttribute("weight"); return new ExchangeOperator(NARROW, treeModel, weight); } // AbstractXMLObjectParser implementation public String getParserDescription() { return "This element represents a narrow exchange operator. " + "This operator swaps a random subtree with its uncle."; } public Class getReturnType() { return ExchangeOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { AttributeRule.newDoubleRule("weight"), new ElementRule(TreeModel.class)}; }; public static XMLObjectParser WIDE_EXCHANGE_PARSER = new AbstractXMLObjectParser() { public String getParserName() { return WIDE_EXCHANGE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { final TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); final double weight = xo.getDoubleAttribute("weight"); return new ExchangeOperator(WIDE, treeModel, weight); } // AbstractXMLObjectParser implementation public String getParserDescription() { return "This element represents a wide exchange operator. " + "This operator swaps two random subtrees."; } public Class getReturnType() { return ExchangeOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules;{ rules = new XMLSyntaxRule[]{ AttributeRule.newDoubleRule("weight"), new ElementRule(TreeModel.class)}; } }; public static XMLObjectParser INTERMEDIATE_EXCHANGE_PARSER = new AbstractXMLObjectParser() { public String getParserName() { return INTERMEDIATE_EXCHANGE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { final TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); final double weight = xo.getDoubleAttribute("weight"); return new ExchangeOperator(INTERMEDIATE, treeModel, weight); } // AbstractXMLObjectParser implementation public String getParserDescription() { return "This element represents a intermediate exchange operator. " + "This operator swaps two random subtrees."; } public Class getReturnType() { return ExchangeOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { AttributeRule.newDoubleRule("weight"), new ElementRule(TreeModel.class)}; }; }
package org.broad.igv.session; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.cli_plugin.PluginSource; import org.broad.igv.feature.Locus; import org.broad.igv.feature.RegionOfInterest; import org.broad.igv.feature.genome.Genome; import org.broad.igv.feature.genome.GenomeManager; import org.broad.igv.lists.GeneList; import org.broad.igv.lists.GeneListManager; import org.broad.igv.renderer.ColorScale; import org.broad.igv.renderer.ColorScaleFactory; import org.broad.igv.renderer.ContinuousColorScale; import org.broad.igv.track.*; import org.broad.igv.ui.IGV; import org.broad.igv.ui.TrackFilter; import org.broad.igv.ui.TrackFilterElement; import org.broad.igv.ui.color.ColorUtilities; import org.broad.igv.ui.panel.FrameManager; import org.broad.igv.ui.panel.ReferenceFrame; import org.broad.igv.ui.panel.TrackPanel; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.FileUtils; import org.broad.igv.util.FilterElement.BooleanOperator; import org.broad.igv.util.FilterElement.Operator; import org.broad.igv.util.ParsingUtils; import org.broad.igv.util.ResourceLocator; import org.broad.igv.util.Utilities; import org.broad.igv.util.collections.CollUtils; import org.w3c.dom.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.List; /** * Class to parse an IGV session file */ public class IGVSessionReader implements SessionReader { private static Logger log = Logger.getLogger(IGVSessionReader.class); private static String INPUT_FILE_KEY = "INPUT_FILE_KEY"; // Temporary values used in processing //package-private for unit testing Collection<ResourceLocator> dataFiles; private Collection<ResourceLocator> missingDataFiles; private static Map<String, String> attributeSynonymMap = new HashMap(); private boolean panelElementPresent = false; private int version; private IGV igv; /** * Classes that have been registered for use with JAXB */ private static List<Class> registeredClasses = new ArrayList<Class>(); /** * Map of track id -> track. It is important to maintain the order in which tracks are added, thus * the use of LinkedHashMap. We add tracks here when loaded and remove them when attributes are specified. */ private final Map<String, List<Track>> leftoverTrackDictionary = Collections.synchronizedMap(new LinkedHashMap()); /** * Map of id -> track, for second pass through when tracks reference each other */ private final Map<String, List<Track>> allTracks = Collections.synchronizedMap(new LinkedHashMap<String, List<Track>>()); public List<Track> getTracksById(String trackId){ return allTracks.get(trackId); } /** * Map of full path -> relative path. */ Map<String, String> fullToRelPathMap = new HashMap<String, String>(); private Track geneTrack = null; private Track seqTrack = null; private boolean hasTrackElments; //Temporary holder for generating tracks protected static AbstractTrack nextTrack; static { attributeSynonymMap.put("DATA FILE", "DATA SET"); attributeSynonymMap.put("TRACK NAME", "NAME"); registerClass(AbstractTrack.class); } /** * Session Element types */ public static enum SessionElement { PANEL("Panel"), PANEL_LAYOUT("PanelLayout"), TRACK("Track"), COLOR_SCALE("ColorScale"), COLOR_SCALES("ColorScales"), DATA_TRACK("DataTrack"), DATA_TRACKS("DataTracks"), FEATURE_TRACKS("FeatureTracks"), DATA_FILE("DataFile"), RESOURCE("Resource"), RESOURCES("Resources"), FILES("Files"), FILTER_ELEMENT("FilterElement"), FILTER("Filter"), SESSION("Session"), GLOBAL("Global"), REGION("Region"), REGIONS("Regions"), DATA_RANGE("DataRange"), PREFERENCES("Preferences"), PROPERTY("Property"), GENE_LIST("GeneList"), HIDDEN_ATTRIBUTES("HiddenAttributes"), VISIBLE_ATTRIBUTES("VisibleAttributes"), ATTRIBUTE("Attribute"), VISIBLE_ATTRIBUTE("VisibleAttribute"), FRAME("Frame"); private String name; SessionElement(String name) { this.name = name; } public String getText() { return name; } @Override public String toString() { return getText(); } static public SessionElement findEnum(String value) { if (value == null) { return null; } else { return SessionElement.valueOf(value); } } } /** * Session Attribute types */ public static enum SessionAttribute { BOOLEAN_OPERATOR("booleanOperator"), COLOR("color"), ALT_COLOR("altColor"), COLOR_MODE("colorMode"), CHROMOSOME("chromosome"), END_INDEX("end"), EXPAND("expand"), SQUISH("squish"), DISPLAY_MODE("displayMode"), FILTER_MATCH("match"), FILTER_SHOW_ALL_TRACKS("showTracks"), GENOME("genome"), GROUP_TRACKS_BY("groupTracksBy"), HEIGHT("height"), ID("id"), ITEM("item"), LOCUS("locus"), NAME("name"), SAMPLE_ID("sampleID"), RESOURCE_TYPE("resourceType"), OPERATOR("operator"), RELATIVE_PATH("relativePath"), RENDERER("renderer"), SCALE("scale"), START_INDEX("start"), VALUE("value"), VERSION("version"), VISIBLE("visible"), WINDOW_FUNCTION("windowFunction"), RENDER_NAME("renderName"), GENOTYPE_HEIGHT("genotypeHeight"), VARIANT_HEIGHT("variantHeight"), PREVIOUS_HEIGHT("previousHeight"), FEATURE_WINDOW("featureVisibilityWindow"), DISPLAY_NAME("displayName"), COLOR_SCALE("colorScale"), //RESOURCE ATTRIBUTES PATH("path"), LABEL("label"), SERVER_URL("serverURL"), HYPERLINK("hyperlink"), INFOLINK("infolink"), URL("url"), FEATURE_URL("featureURL"), DESCRIPTION("description"), TYPE("type"), COVERAGE("coverage"), TRACK_LINE("trackLine"), CHR("chr"), START("start"), END("end"); //TODO Add the following into the Attributes /* ShadeBasesOption shadeBases; boolean shadeCenters; boolean flagUnmappedPairs; boolean showAllBases; int insertSizeThreshold; boolean colorByStrand; boolean colorByAmpliconStrand; */ private String name; SessionAttribute(String name) { this.name = name; } public String getText() { return name; } @Override public String toString() { return getText(); } } public IGVSessionReader(IGV igv) { this.igv = igv; PluginSource.MyMapAdapter.setSessionReader(this); } /** * @param inputStream * @param session * @param sessionPath @return * @throws RuntimeException */ public void loadSession(InputStream inputStream, Session session, String sessionPath) { log.debug("Load session"); Document document = null; try { document = Utilities.createDOMDocumentFromXmlStream(inputStream); } catch (Exception e) { log.error("Load session error", e); throw new RuntimeException(e); } NodeList tracks = document.getElementsByTagName("Track"); hasTrackElments = tracks.getLength() > 0; HashMap additionalInformation = new HashMap(); additionalInformation.put(INPUT_FILE_KEY, sessionPath); NodeList nodes = document.getElementsByTagName(SessionElement.GLOBAL.getText()); if (nodes == null || nodes.getLength() == 0) { nodes = document.getElementsByTagName(SessionElement.SESSION.getText()); } processRootNode(session, nodes.item(0), additionalInformation, sessionPath); // section only (no Panel or Track elements). addLeftoverTracks(leftoverTrackDictionary.values()); if (igv != null) { if (session.getGroupTracksBy() != null && session.getGroupTracksBy().length() > 0) { igv.setGroupByAttribute(session.getGroupTracksBy()); } if (session.isRemoveEmptyPanels()) { igv.getMainPanel().removeEmptyDataPanels(); } igv.resetOverlayTracks(); } } private void processRootNode(Session session, Node node, HashMap additionalInformation, String rootPath) { if ((node == null) || (session == null)) { MessageUtils.showMessage("Invalid session file: root node not found"); return; } String nodeName = node.getNodeName(); if (!(nodeName.equalsIgnoreCase(SessionElement.GLOBAL.getText()) || nodeName.equalsIgnoreCase(SessionElement.SESSION.getText()))) { MessageUtils.showMessage("Session files must begin with a \"Global\" or \"Session\" element. Found: " + nodeName); } process(session, node, additionalInformation, rootPath); Element element = (Element) node; // Load the genome, which can be an ID, or a path or URL to a .genome or indexed fasta file. String genomeId = getAttribute(element, SessionAttribute.GENOME.getText()); if (genomeId != null && genomeId.length() > 0) { if (genomeId.equals(GenomeManager.getInstance().getGenomeId())) { // We don't have to reload the genome, but the gene track for the current genome should be restored. Genome genome = GenomeManager.getInstance().getCurrentGenome(); IGV.getInstance().setGenomeTracks(genome.getGeneTrack()); } else { // Selecting a genome will actually "reset" the session so we have to // save the path and restore it. String sessionPath = session.getPath(); //Loads genome from list, or from server or cache igv.selectGenomeFromList(genomeId); if (!GenomeManager.getInstance().getGenomeId().equals(genomeId)) { String genomePath = genomeId; if (!ParsingUtils.pathExists(genomePath)) { genomePath = FileUtils.getAbsolutePath(genomeId, session.getPath()); } if (ParsingUtils.pathExists(genomePath)) { try { IGV.getInstance().loadGenome(genomePath, null); } catch (IOException e) { throw new RuntimeException("Error loading genome: " + genomeId); } } else { MessageUtils.showMessage("Warning: Could not locate genome: " + genomeId); } } session.setPath(sessionPath); } } //For later lookup and to prevent dual adding, we keep a reference to the gene track geneTrack = GenomeManager.getInstance().getCurrentGenome().getGeneTrack(); if(geneTrack != null){ allTracks.put(geneTrack.getId(), Arrays.asList(geneTrack)); } session.setLocus(getAttribute(element, SessionAttribute.LOCUS.getText())); session.setGroupTracksBy(getAttribute(element, SessionAttribute.GROUP_TRACKS_BY.getText())); String removeEmptyTracks = getAttribute(element, "removeEmptyTracks"); if (removeEmptyTracks != null) { try { Boolean b = Boolean.parseBoolean(removeEmptyTracks); session.setRemoveEmptyPanels(b); } catch (Exception e) { log.error("Error parsing removeEmptyTracks string: " + removeEmptyTracks, e); } } String versionString = getAttribute(element, SessionAttribute.VERSION.getText()); try { version = Integer.parseInt(versionString); } catch (NumberFormatException e) { log.error("Non integer version number in session file: " + versionString); } session.setVersion(version); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation, rootPath); // ReferenceFrame.getInstance().invalidateLocationScale(); } //TODO Check to make sure tracks are not being created twice //TODO -- DONT DO THIS FOR NEW SESSIONS private void addLeftoverTracks(Collection<List<Track>> tmp) { Map<String, TrackPanel> trackPanelCache = new HashMap(); if (version < 3 || !panelElementPresent) { for (List<Track> tracks : tmp) { for (Track track : tracks) { if (track != geneTrack && track != seqTrack && track.getResourceLocator() != null) { TrackPanel panel = trackPanelCache.get(track.getResourceLocator().getPath()); if (panel == null) { panel = IGV.getInstance().getPanelFor(track.getResourceLocator()); trackPanelCache.put(track.getResourceLocator().getPath(), panel); } panel.addTrack(track); } } } } } /** * Process a single session element node. * * @param session * @param element */ private void process(Session session, Node element, HashMap additionalInformation, String rootPath) { if ((element == null) || (session == null)) { return; } String nodeName = element.getNodeName(); if (nodeName.equalsIgnoreCase(SessionElement.RESOURCES.getText()) || nodeName.equalsIgnoreCase(SessionElement.FILES.getText())) { processResources(session, (Element) element, additionalInformation, rootPath); } else if (nodeName.equalsIgnoreCase(SessionElement.RESOURCE.getText()) || nodeName.equalsIgnoreCase(SessionElement.DATA_FILE.getText())) { processResource(session, (Element) element, additionalInformation, rootPath); } else if (nodeName.equalsIgnoreCase(SessionElement.REGIONS.getText())) { processRegions(session, (Element) element, additionalInformation, rootPath); } else if (nodeName.equalsIgnoreCase(SessionElement.REGION.getText())) { processRegion(session, (Element) element, additionalInformation, rootPath); } else if (nodeName.equalsIgnoreCase(SessionElement.GENE_LIST.getText())) { processGeneList(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.FILTER.getText())) { processFilter(session, (Element) element, additionalInformation, rootPath); } else if (nodeName.equalsIgnoreCase(SessionElement.FILTER_ELEMENT.getText())) { processFilterElement(session, (Element) element, additionalInformation, rootPath); } else if (nodeName.equalsIgnoreCase(SessionElement.COLOR_SCALES.getText())) { processColorScales(session, (Element) element, additionalInformation, rootPath); } else if (nodeName.equalsIgnoreCase(SessionElement.COLOR_SCALE.getText())) { processColorScale(session, (Element) element, additionalInformation, rootPath); } else if (nodeName.equalsIgnoreCase(SessionElement.PREFERENCES.getText())) { processPreferences(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.DATA_TRACKS.getText()) || nodeName.equalsIgnoreCase(SessionElement.FEATURE_TRACKS.getText()) || nodeName.equalsIgnoreCase(SessionElement.PANEL.getText())) { processPanel(session, (Element) element, additionalInformation, rootPath); } else if (nodeName.equalsIgnoreCase(SessionElement.PANEL_LAYOUT.getText())) { processPanelLayout(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.HIDDEN_ATTRIBUTES.getText())) { processHiddenAttributes(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.VISIBLE_ATTRIBUTES.getText())) { processVisibleAttributes(session, (Element) element, additionalInformation); } } private void processResources(Session session, Element element, HashMap additionalInformation, String rootPath) { dataFiles = new ArrayList(); missingDataFiles = new ArrayList(); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation, rootPath); if (missingDataFiles.size() > 0) { StringBuffer message = new StringBuffer(); message.append("<html>The following data file(s) could not be located.<ul>"); for (ResourceLocator file : missingDataFiles) { if (file.isLocal()) { message.append("<li>"); message.append(file.getPath()); message.append("</li>"); } else { message.append("<li>Server: "); message.append(file.getServerURL()); message.append(" Path: "); message.append(file.getPath()); message.append("</li>"); } } message.append("</ul>"); message.append("Common reasons for this include: "); message.append("<ul><li>The session or data files have been moved.</li> "); message.append("<li>The data files are located on a drive that is not currently accessible.</li></ul>"); message.append("</html>"); MessageUtils.showMessage(message.toString()); } if (dataFiles.size() > 0) { final List<String> errors = new ArrayList<String>(); // Load files concurrently -- TODO, put a limit on # of threads? List<Thread> threads = new ArrayList(dataFiles.size()); long t0 = System.currentTimeMillis(); int i = 0; List<Runnable> synchronousLoads = new ArrayList<Runnable>(); for (final ResourceLocator locator : dataFiles) { final String suppliedPath = locator.getPath(); final String relPath = fullToRelPathMap.get(suppliedPath); Runnable runnable = new Runnable() { public void run() { List<Track> tracks = null; try { tracks = igv.load(locator); for (Track track : tracks) { if (track == null) { log.info("Null track for resource " + locator.getPath()); continue; } String id = track.getId(); if (id == null) { log.info("Null track id for resource " + locator.getPath()); continue; } if (relPath != null) { id = id.replace(suppliedPath, relPath); } List<Track> trackList = leftoverTrackDictionary.get(id); if (trackList == null) { trackList = new ArrayList(); leftoverTrackDictionary.put(id, trackList); allTracks.put(id, trackList); } trackList.add(track); } } catch (Exception e) { log.error("Error loading resource " + locator.getPath(), e); String ms = "<b>" + locator.getPath() + "</b><br>&nbs;p&nbsp;" + e.toString() + "<br>"; errors.add(ms); } } }; boolean isAlignment = locator.getPath().endsWith(".bam") || locator.getPath().endsWith(".entries") || locator.getPath().endsWith(".sam"); // Run synchronously if in batch mode or if there are no "track" elments, or if this is an alignment file // EVERYTHING IS RUN SYNCHRONOUSLY FOR NOW UNTIL WE CAN FIGURE OUT WHAT TO DO TO PREVENT MULTIPLE // AUTHENTICATION DIALOGS if (isAlignment || Globals.isBatch() || !hasTrackElments) { synchronousLoads.add(runnable); } else { Thread t = new Thread(runnable); threads.add(t); t.start(); } i++; } // Wait for all threads to complete for (Thread t : threads) { try { t.join(); } catch (InterruptedException ignore) { } } // Now load data that must be loaded synchronously for (Runnable runnable : synchronousLoads) { runnable.run(); } long dt = System.currentTimeMillis() - t0; log.debug("Total load time = " + dt); if (errors.size() > 0) { StringBuffer buf = new StringBuffer(); buf.append("<html>Errors were encountered loading the session:<br>"); for (String msg : errors) { buf.append(msg); } MessageUtils.showMessage(buf.toString()); } } dataFiles = null; } /** * Load a single resource. * <p/> * Package private for unit testing * * @param session * @param element * @param additionalInformation */ void processResource(Session session, Element element, HashMap additionalInformation, String rootPath) { String nodeName = element.getNodeName(); boolean oldSession = nodeName.equals(SessionElement.DATA_FILE.getText()); String label = getAttribute(element, SessionAttribute.LABEL.getText()); String name = getAttribute(element, SessionAttribute.NAME.getText()); String sampleId = getAttribute(element, SessionAttribute.SAMPLE_ID.getText()); String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText()); String type = getAttribute(element, SessionAttribute.TYPE.getText()); String coverage = getAttribute(element, SessionAttribute.COVERAGE.getText()); String trackLine = getAttribute(element, SessionAttribute.TRACK_LINE.getText()); String colorString = getAttribute(element, SessionAttribute.COLOR.getText()); //String relPathValue = getAttribute(element, SessionAttribute.RELATIVE_PATH.getText()); //boolean isRelativePath = ((relPathValue != null) && relPathValue.equalsIgnoreCase("true")); String serverURL = getAttribute(element, SessionAttribute.SERVER_URL.getText()); // Older sessions used the "name" attribute for the path. String path = getAttribute(element, SessionAttribute.PATH.getText()); if (oldSession && name != null) { path = name; int idx = name.lastIndexOf("/"); if (idx > 0 && idx + 1 < name.length()) { name = name.substring(idx + 1); } } if (rootPath == null) { log.error("Null root path -- this is not expected"); MessageUtils.showMessage("Unexpected error loading session: null root path"); return; } String absolutePath = FileUtils.getAbsolutePath(path, rootPath); fullToRelPathMap.put(absolutePath, path); ResourceLocator resourceLocator = new ResourceLocator(serverURL, absolutePath); if (coverage != null) { String absoluteCoveragePath = FileUtils.getAbsolutePath(coverage, rootPath); resourceLocator.setCoverage(absoluteCoveragePath); } String url = getAttribute(element, SessionAttribute.URL.getText()); if (url == null) { url = getAttribute(element, SessionAttribute.FEATURE_URL.getText()); } resourceLocator.setUrl(url); String infolink = getAttribute(element, SessionAttribute.HYPERLINK.getText()); if (infolink == null) { infolink = getAttribute(element, SessionAttribute.INFOLINK.getText()); } resourceLocator.setInfolink(infolink); // Label is deprecated in favor of name. if (name != null) { resourceLocator.setName(name); } else { resourceLocator.setName(label); } resourceLocator.setSampleId(sampleId); resourceLocator.setDescription(description); // This test added to get around earlier bug in the writer if (type != null && !type.equals("local")) { resourceLocator.setType(type); } resourceLocator.setCoverage(coverage); resourceLocator.setTrackLine(trackLine); if (colorString != null) { try { Color c = ColorUtilities.stringToColor(colorString); resourceLocator.setColor(c); } catch (Exception e) { log.error("Error setting color: ", e); } } dataFiles.add(resourceLocator); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation, rootPath); } private void processRegions(Session session, Element element, HashMap additionalInformation, String rootPath) { session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation, rootPath); } private void processRegion(Session session, Element element, HashMap additionalInformation, String rootPath) { String chromosome = getAttribute(element, SessionAttribute.CHROMOSOME.getText()); String start = getAttribute(element, SessionAttribute.START_INDEX.getText()); String end = getAttribute(element, SessionAttribute.END_INDEX.getText()); String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText()); RegionOfInterest region = new RegionOfInterest(chromosome, new Integer(start), new Integer(end), description); IGV.getInstance().addRegionOfInterest(region); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation, rootPath); } private void processHiddenAttributes(Session session, Element element, HashMap additionalInformation) { // session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Set<String> attributes = new HashSet(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.ATTRIBUTE.getText())) { attributes.add(((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText())); } } session.setHiddenAttributes(attributes); } } /** * For backward compatibility * * @param session * @param element * @param additionalInformation */ private void processVisibleAttributes(Session session, Element element, HashMap additionalInformation) { // session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Set<String> visibleAttributes = new HashSet(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.VISIBLE_ATTRIBUTE.getText())) { visibleAttributes.add(((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText())); } } final List<String> attributeNames = AttributeManager.getInstance().getAttributeNames(); Set<String> hiddenAttributes = new HashSet<String>(attributeNames); hiddenAttributes.removeAll(visibleAttributes); session.setHiddenAttributes(hiddenAttributes); } } private void processGeneList(Session session, Element element, HashMap additionalInformation) { String name = getAttribute(element, SessionAttribute.NAME.getText()); String txt = element.getTextContent(); String[] genes = txt.trim().split("\\s+"); GeneList gl = new GeneList(name, Arrays.asList(genes)); GeneListManager.getInstance().addGeneList(gl); session.setCurrentGeneList(gl); // Adjust frames processFrames(element); } private void processFrames(Element element) { NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Map<String, ReferenceFrame> frames = new HashMap(); for (ReferenceFrame f : FrameManager.getFrames()) { frames.put(f.getName(), f); } List<ReferenceFrame> reorderedFrames = new ArrayList(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equalsIgnoreCase(SessionElement.FRAME.getText())) { String frameName = getAttribute((Element) childNode, SessionAttribute.NAME.getText()); ReferenceFrame f = frames.get(frameName); if (f != null) { reorderedFrames.add(f); try { String chr = getAttribute((Element) childNode, SessionAttribute.CHR.getText()); final String startString = getAttribute((Element) childNode, SessionAttribute.START.getText()).replace(",", ""); final String endString = getAttribute((Element) childNode, SessionAttribute.END.getText()).replace(",", ""); int start = ParsingUtils.parseInt(startString); int end = ParsingUtils.parseInt(endString); org.broad.igv.feature.Locus locus = new Locus(chr, start, end); f.jumpTo(locus); } catch (NumberFormatException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } } if (reorderedFrames.size() > 0) { FrameManager.setFrames(reorderedFrames); } } IGV.getInstance().resetFrames(); } private void processFilter(Session session, Element element, HashMap additionalInformation, String rootPath) { String match = getAttribute(element, SessionAttribute.FILTER_MATCH.getText()); String showAllTracks = getAttribute(element, SessionAttribute.FILTER_SHOW_ALL_TRACKS.getText()); String filterName = getAttribute(element, SessionAttribute.NAME.getText()); TrackFilter filter = new TrackFilter(filterName, null); additionalInformation.put(SessionElement.FILTER, filter); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation, rootPath); // Save the filter session.setFilter(filter); // Set filter properties if ("all".equalsIgnoreCase(match)) { IGV.getInstance().setFilterMatchAll(true); } else if ("any".equalsIgnoreCase(match)) { IGV.getInstance().setFilterMatchAll(false); } if ("true".equalsIgnoreCase(showAllTracks)) { IGV.getInstance().setFilterShowAllTracks(true); } else { IGV.getInstance().setFilterShowAllTracks(false); } } private void processFilterElement(Session session, Element element, HashMap additionalInformation, String rootPath) { TrackFilter filter = (TrackFilter) additionalInformation.get(SessionElement.FILTER); String item = getAttribute(element, SessionAttribute.ITEM.getText()); String operator = getAttribute(element, SessionAttribute.OPERATOR.getText()); String value = getAttribute(element, SessionAttribute.VALUE.getText()); String booleanOperator = getAttribute(element, SessionAttribute.BOOLEAN_OPERATOR.getText()); Operator opEnum = CollUtils.findValueOf(Operator.class, operator); BooleanOperator boolEnum = BooleanOperator.valueOf(booleanOperator.toUpperCase()); TrackFilterElement trackFilterElement = new TrackFilterElement(filter, item, opEnum, value, boolEnum); filter.add(trackFilterElement); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation, rootPath); } /** * A counter to generate unique panel names. Needed for backward-compatibility of old session files. */ private int panelCounter = 1; private void processPanel(Session session, Element element, HashMap additionalInformation, String rootPath) { panelElementPresent = true; String panelName = element.getAttribute("name"); if (panelName == null) { panelName = "Panel" + panelCounter++; } List<Track> panelTracks = new ArrayList(); NodeList elements = element.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equalsIgnoreCase(SessionElement.DATA_TRACK.getText()) || // Is this a track? childNode.getNodeName().equalsIgnoreCase(SessionElement.TRACK.getText())) { List<Track> tracks = processTrack(session, (Element) childNode, additionalInformation, rootPath); if (tracks != null) { panelTracks.addAll(tracks); } } else { process(session, childNode, additionalInformation, rootPath); } } //We make a second pass through, resolving references to tracks which may have been processed afterwards. //For instance if Track 2 referenced Track 4 //TODO Make this less hacky for (Track track: panelTracks){ if(track instanceof FeatureTrack){ FeatureTrack featureTrack = (FeatureTrack) track; featureTrack.updateTrackReferences(panelTracks); } } TrackPanel panel = IGV.getInstance().getTrackPanel(panelName); panel.addTracks(panelTracks); } private void processPanelLayout(Session session, Element element, HashMap additionalInformation) { String nodeName = element.getNodeName(); String panelName = nodeName; NamedNodeMap tNodeMap = element.getAttributes(); for (int i = 0; i < tNodeMap.getLength(); i++) { Node node = tNodeMap.item(i); String name = node.getNodeName(); if (name.equals("dividerFractions")) { String value = node.getNodeValue(); String[] tokens = value.split(","); double[] divs = new double[tokens.length]; try { for (int j = 0; j < tokens.length; j++) { divs[j] = Double.parseDouble(tokens[j]); } session.setDividerFractions(divs); } catch (NumberFormatException e) { log.error("Error parsing divider locations", e); } } } } /** * Process a track element. This should return a single track, but could return multiple tracks since the * uniqueness of the track id is not enforced. * * @param session * @param element * @param additionalInformation * @return */ private List<Track> processTrack(Session session, Element element, HashMap additionalInformation, String rootPath) { String id = getAttribute(element, SessionAttribute.ID.getText()); // Get matching tracks. List<Track> matchedTracks = allTracks.get(id); if (matchedTracks == null) { log.info("Warning. No tracks were found with id: " + id + " in session file"); String className = getAttribute(element, "clazz"); //We try anyway, some tracks can be reconstructed without a resource element //They must have a source, though try{ if(className != null && className.contains("FeatureTrack") && element.hasChildNodes()){ Class clazz = Class.forName(className); Unmarshaller u = getJAXBContext().createUnmarshaller(); Track track = unmarshalTrackElement(u, element, null, clazz); matchedTracks = new ArrayList<Track>(Arrays.asList(track)); allTracks.put(track.getId(), matchedTracks); } } catch (JAXBException e) { //pass } catch (ClassNotFoundException e) { //pass } } else { try { Unmarshaller u = getJAXBContext().createUnmarshaller(); for (final Track track : matchedTracks) { // Special case for sequence & gene tracks, they need to be removed before being placed. if (igv != null && version >= 4 && (track == geneTrack || track == seqTrack)) { igv.removeTracks(Arrays.asList(track)); } unmarshalTrackElement(u, element, (AbstractTrack) track); } } catch (JAXBException e) { throw new RuntimeException(e); } leftoverTrackDictionary.remove(id); } NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation, rootPath); return matchedTracks; } private static void setNextTrack(AbstractTrack track){ nextTrack = track; } /** * Used for unmarshalling track; JAXB needs a static no-arg factory method * @return */ public static AbstractTrack getNextTrack(){ return nextTrack; } /** * Unmarshal element into specified class * @param u * @param e * @param track * @return * @throws JAXBException */ protected Track unmarshalTrackElement(Unmarshaller u, Element e, AbstractTrack track) throws JAXBException{ return unmarshalTrackElement(u, e, track, track.getClass()); } /** * * @param u * @param element * @param track The track into which to unmarshal. Can be null if the relevant static factory method can handle * creating a new instance * @param trackClass Class of track to use for unmarshalling * @return The unmarshalled track * @throws JAXBException */ protected Track unmarshalTrackElement(Unmarshaller u, Element element, AbstractTrack track, Class trackClass) throws JAXBException{ AbstractTrack ut; synchronized (IGVSessionReader.class){ setNextTrack(track); ut = unmarshalTrack(u, element, trackClass, trackClass); } ut.restorePersistentState(element); return ut; } private void processColorScales(Session session, Element element, HashMap additionalInformation, String rootPath) { NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation, rootPath); } private void processColorScale(Session session, Element element, HashMap additionalInformation, String rootPath) { String trackType = getAttribute(element, SessionAttribute.TYPE.getText()); String value = getAttribute(element, SessionAttribute.VALUE.getText()); setColorScaleSet(session, trackType, value); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation, rootPath); } private void processPreferences(Session session, Element element, HashMap additionalInformation) { NodeList elements = element.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node child = elements.item(i); if (child.getNodeName().equalsIgnoreCase(SessionElement.PROPERTY.getText())) { Element childNode = (Element) child; String name = getAttribute(childNode, SessionAttribute.NAME.getText()); String value = getAttribute(childNode, SessionAttribute.VALUE.getText()); session.setPreference(name, value); } } } /** * Process a list of session element nodes. * * @param session * @param elements */ private void process(Session session, NodeList elements, HashMap additionalInformation, String rootPath) { for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); process(session, childNode, additionalInformation, rootPath); } } public void setColorScaleSet(Session session, String type, String value) { if (type == null | value == null) { return; } TrackType trackType = CollUtils.valueOf(TrackType.class, type.toUpperCase(), TrackType.OTHER); // TODO -- refactor to remove instanceof / cast. Currently only ContinuousColorScale is handled ColorScale colorScale = ColorScaleFactory.getScaleFromString(value); if (colorScale instanceof ContinuousColorScale) { session.setColorScale(trackType, (ContinuousColorScale) colorScale); } // ColorScaleFactory.setColorScale(trackType, colorScale); } private String getAttribute(Element element, String key) { String value = element.getAttribute(key); if (value != null) { if (value.trim().equals("")) { value = null; } } return value; } private static JAXBContext jc = null; public static synchronized JAXBContext getJAXBContext() throws JAXBException { if(jc == null){ jc = JAXBContext.newInstance(registeredClasses.toArray(new Class[0]), new HashMap<String, Object>()); } return jc; } /** * Register this class with JAXB, so it can be saved and restored to a session. * The class must conform the JAXBs requirements (e.g. no-arg constructor or factory method) * @param clazz */ //@api public static synchronized void registerClass(Class clazz){ registeredClasses.add(clazz); jc = null; } /** * Unmarshal node. We first attempt to unmarshal into the specified {@code clazz} * if that fails, we try the superclass, and so on up. * * @param node * @param unmarshalClass Class to which to use for unmarshalling * @param firstClass The first class used for invocation. For helpful error message only * * @return */ public static AbstractTrack unmarshalTrack(Unmarshaller u, Node node, Class unmarshalClass,Class firstClass) throws JAXBException{ if(unmarshalClass == null || unmarshalClass.equals(Object.class)){ throw new JAXBException(firstClass + " and none of its superclasses are known"); } if(AbstractTrack.knownUnknownTrackClasses.contains(unmarshalClass)){ return unmarshalTrack(u, node, firstClass, unmarshalClass.getSuperclass()); } JAXBElement el; try { el = u.unmarshal(node, unmarshalClass); } catch (JAXBException e) { AbstractTrack.knownUnknownTrackClasses.add(unmarshalClass); return unmarshalTrack(u, node, firstClass, unmarshalClass.getSuperclass()); } return (AbstractTrack) el.getValue(); } }
package dr.app.beauti.components.marginalLikelihoodEstimation; import dr.app.beauti.generator.BaseComponentGenerator; import dr.app.beauti.options.BeautiOptions; import dr.app.beauti.options.Parameter; import dr.app.beauti.types.PriorType; import dr.app.beauti.types.TreePriorType; import dr.app.beauti.util.XMLWriter; import dr.evolution.util.Units; import dr.evomodel.tree.TreeModel; import dr.evomodelxml.TreeWorkingPriorParsers; import dr.evomodelxml.coalescent.*; import dr.inference.mcmc.MarginalLikelihoodEstimator; import dr.inference.model.ParameterParser; import dr.inference.model.PathLikelihood; import dr.inference.trace.GeneralizedSteppingStoneSamplingAnalysis; import dr.inference.trace.PathSamplingAnalysis; import dr.inference.trace.SteppingStoneSamplingAnalysis; import dr.inferencexml.distribution.WorkingPriorParsers; import dr.inferencexml.model.CompoundLikelihoodParser; import dr.util.Attribute; import dr.xml.XMLParser; import java.util.ArrayList; import java.util.List; /** * @author Andrew Rambaut * @version $Id$ */ public class MarginalLikelihoodEstimationGenerator extends BaseComponentGenerator { public static final boolean DEBUG = true; private BeautiOptions beautiOptions = null; MarginalLikelihoodEstimationGenerator(final BeautiOptions options) { super(options); this.beautiOptions = options; } public boolean usesInsertionPoint(final InsertionPoint point) { MarginalLikelihoodEstimationOptions component = (MarginalLikelihoodEstimationOptions) options.getComponentOptions(MarginalLikelihoodEstimationOptions.class); if (!component.performMLE && !component.performMLEGSS) { return false; } switch (point) { case AFTER_MCMC: return true; } return false; } protected void generate(final InsertionPoint point, final Object item, final String prefix, final XMLWriter writer) { MarginalLikelihoodEstimationOptions component = (MarginalLikelihoodEstimationOptions) options.getComponentOptions(MarginalLikelihoodEstimationOptions.class); switch (point) { case AFTER_MCMC: writeMLE(writer, component); break; default: throw new IllegalArgumentException("This insertion point is not implemented for " + this.getClass().getName()); } } protected String getCommentLabel() { return "Marginal Likelihood Estimator"; } /** * Write the marginalLikelihoodEstimator, pathSamplingAnalysis and steppingStoneSamplingAnalysis blocks. * * @param writer XMLWriter */ public void writeMLE(XMLWriter writer, MarginalLikelihoodEstimationOptions options) { if (options.performMLE) { writer.writeComment("Define marginal likelihood estimator (PS/SS) settings"); List<Attribute> attributes = new ArrayList<Attribute>(); //attributes.add(new Attribute.Default<String>(XMLParser.ID, "mcmc")); attributes.add(new Attribute.Default<Integer>(MarginalLikelihoodEstimator.CHAIN_LENGTH, options.mleChainLength)); attributes.add(new Attribute.Default<Integer>(MarginalLikelihoodEstimator.PATH_STEPS, options.pathSteps)); attributes.add(new Attribute.Default<String>(MarginalLikelihoodEstimator.PATH_SCHEME, options.pathScheme)); if (!options.pathScheme.equals(MarginalLikelihoodEstimator.LINEAR)) { attributes.add(new Attribute.Default<Double>(MarginalLikelihoodEstimator.ALPHA, options.schemeParameter)); } writer.writeOpenTag(MarginalLikelihoodEstimator.MARGINAL_LIKELIHOOD_ESTIMATOR, attributes); writer.writeOpenTag("samplers"); writer.writeIDref("mcmc", "mcmc"); writer.writeCloseTag("samplers"); attributes = new ArrayList<Attribute>(); attributes.add(new Attribute.Default<String>(XMLParser.ID, "pathLikelihood")); writer.writeOpenTag(PathLikelihood.PATH_LIKELIHOOD, attributes); writer.writeOpenTag(PathLikelihood.SOURCE); writer.writeIDref(CompoundLikelihoodParser.POSTERIOR, CompoundLikelihoodParser.POSTERIOR); writer.writeCloseTag(PathLikelihood.SOURCE); writer.writeOpenTag(PathLikelihood.DESTINATION); writer.writeIDref(CompoundLikelihoodParser.PRIOR, CompoundLikelihoodParser.PRIOR); writer.writeCloseTag(PathLikelihood.DESTINATION); writer.writeCloseTag(PathLikelihood.PATH_LIKELIHOOD); attributes = new ArrayList<Attribute>(); attributes.add(new Attribute.Default<String>(XMLParser.ID, "MLELog")); attributes.add(new Attribute.Default<Integer>("logEvery", options.mleLogEvery)); attributes.add(new Attribute.Default<String>("fileName", options.mleFileName)); writer.writeOpenTag("log", attributes); writer.writeIDref("pathLikelihood", "pathLikelihood"); writer.writeCloseTag("log"); writer.writeCloseTag(MarginalLikelihoodEstimator.MARGINAL_LIKELIHOOD_ESTIMATOR); writer.writeComment("Path sampling estimator from collected samples"); attributes = new ArrayList<Attribute>(); attributes.add(new Attribute.Default<String>("fileName", options.mleFileName)); writer.writeOpenTag(PathSamplingAnalysis.PATH_SAMPLING_ANALYSIS, attributes); writer.writeTag("likelihoodColumn", new Attribute.Default<String>("name", "pathLikelihood.delta"), true); writer.writeTag("thetaColumn", new Attribute.Default<String>("name", "pathLikelihood.theta"), true); writer.writeCloseTag(PathSamplingAnalysis.PATH_SAMPLING_ANALYSIS); writer.writeComment("Stepping-stone sampling estimator from collected samples"); attributes = new ArrayList<Attribute>(); attributes.add(new Attribute.Default<String>("fileName", options.mleFileName)); writer.writeOpenTag(SteppingStoneSamplingAnalysis.STEPPING_STONE_SAMPLING_ANALYSIS, attributes); writer.writeTag("likelihoodColumn", new Attribute.Default<String>("name", "pathLikelihood.delta"), true); writer.writeTag("thetaColumn", new Attribute.Default<String>("name", "pathLikelihood.theta"), true); writer.writeCloseTag(SteppingStoneSamplingAnalysis.STEPPING_STONE_SAMPLING_ANALYSIS); } else if (options.performMLEGSS) { //First define necessary components for the tree working prior if (options.choiceTreeWorkingPrior.equals("Product of exponential distributions")) { //more general product of exponentials needs to be constructed if (DEBUG) { System.err.println("productOfExponentials selected: " + options.choiceTreeWorkingPrior); } List<Attribute> attributes = new ArrayList<Attribute>(); attributes.add(new Attribute.Default<String>(XMLParser.ID, "exponentials")); attributes.add(new Attribute.Default<String>("fileName", beautiOptions.logFileName)); attributes.add(new Attribute.Default<String>("burnin", "" + beautiOptions.chainLength*0.10)); attributes.add(new Attribute.Default<String>("parameterColumn", "coalescentEventsStatistic")); attributes.add(new Attribute.Default<String>("dimension", "" + (beautiOptions.taxonList.getTaxonCount()-1))); writer.writeOpenTag(TreeWorkingPriorParsers.PRODUCT_OF_EXPONENTIALS_POSTERIOR_MEANS_LOESS, attributes); writer.writeTag(TreeModel.TREE_MODEL, new Attribute.Default<String>(XMLParser.ID, TreeModel.TREE_MODEL), true); writer.writeCloseTag(TreeWorkingPriorParsers.PRODUCT_OF_EXPONENTIALS_POSTERIOR_MEANS_LOESS); } else { //matching coalescent model has to be constructed //getting the coalescent model if (DEBUG) { System.err.println("matching coalescent model selected: " + options.choiceTreeWorkingPrior); System.err.println(beautiOptions.getPartitionTreePriors().get(0).getNodeHeightPrior()); } /*for (PartitionTreePrior prior : options.getPartitionTreePriors()) { treePriorGenerator.writeTreePriorModel(prior, writer); writer.writeText(""); }*/ //TODO: extend for more than 1 coalescent model? TreePriorType nodeHeightPrior = beautiOptions.getPartitionTreePriors().get(0).getNodeHeightPrior(); switch (nodeHeightPrior) { case CONSTANT: writer.writeComment("A working prior for the constant population size model."); writer.writeOpenTag( ConstantPopulationModelParser.CONSTANT_POPULATION_MODEL, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, modelPrefix + "constantReference"), new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(beautiOptions.units)) } ); writer.writeOpenTag(ConstantPopulationModelParser.POPULATION_SIZE); writeParameter("constantReference.popSize", "constant.popSize", beautiOptions.logFileName, (int) (options.mleChainLength * 0.10), writer); writer.writeCloseTag(ConstantPopulationModelParser.POPULATION_SIZE); writer.writeCloseTag(ConstantPopulationModelParser.CONSTANT_POPULATION_MODEL); writer.writeComment("A working prior for the coalescent."); writer.writeOpenTag( CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, modelPrefix + "coalescentReference") } ); writer.writeOpenTag(CoalescentLikelihoodParser.MODEL); writer.writeIDref(ConstantPopulationModelParser.CONSTANT_POPULATION_MODEL, beautiOptions.getPartitionTreePriors().get(0).getPrefix() + "constantReference"); writer.writeCloseTag(CoalescentLikelihoodParser.MODEL); writer.writeOpenTag(CoalescentLikelihoodParser.POPULATION_TREE); writer.writeIDref(TreeModel.TREE_MODEL, modelPrefix + TreeModel.TREE_MODEL); writer.writeCloseTag(CoalescentLikelihoodParser.POPULATION_TREE); writer.writeCloseTag(CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD); break; case EXPONENTIAL: writer.writeComment("A working prior for the exponential growth model."); writer.writeOpenTag( ExponentialGrowthModelParser.EXPONENTIAL_GROWTH_MODEL, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, modelPrefix + "exponentialReference"), new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(beautiOptions.units)) } ); writer.writeOpenTag(ExponentialGrowthModelParser.POPULATION_SIZE); writeParameter("exponentialReference.popSize", "exponential.popSize", beautiOptions.logFileName, (int) (options.mleChainLength * 0.10), writer); writer.writeCloseTag(ExponentialGrowthModelParser.POPULATION_SIZE); writer.writeOpenTag(ExponentialGrowthModelParser.GROWTH_RATE); writeParameter("exponentialReference.growthRate", "exponential.growthRate", beautiOptions.logFileName, (int) (options.mleChainLength * 0.10), writer); writer.writeCloseTag(ExponentialGrowthModelParser.GROWTH_RATE); writer.writeCloseTag(ExponentialGrowthModelParser.EXPONENTIAL_GROWTH_MODEL); writer.writeComment("A working prior for the coalescent."); writer.writeOpenTag( CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, modelPrefix + "coalescentReference") } ); writer.writeOpenTag(CoalescentLikelihoodParser.MODEL); writer.writeIDref(ExponentialGrowthModelParser.EXPONENTIAL_GROWTH_MODEL, beautiOptions.getPartitionTreePriors().get(0).getPrefix() + "constantReference"); writer.writeCloseTag(CoalescentLikelihoodParser.MODEL); writer.writeOpenTag(CoalescentLikelihoodParser.POPULATION_TREE); writer.writeIDref(TreeModel.TREE_MODEL, modelPrefix + TreeModel.TREE_MODEL); writer.writeCloseTag(CoalescentLikelihoodParser.POPULATION_TREE); writer.writeCloseTag(CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD); break; case LOGISTIC: writer.writeComment("A working prior for the logistic growth model."); writer.writeOpenTag( LogisticGrowthModelParser.LOGISTIC_GROWTH_MODEL, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, modelPrefix + "logisticReference"), new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(beautiOptions.units)) } ); writer.writeOpenTag(LogisticGrowthModelParser.POPULATION_SIZE); writeParameter("logisticReference.popSize", "logistic.popSize", beautiOptions.logFileName, (int) (options.mleChainLength * 0.10), writer); writer.writeCloseTag(LogisticGrowthModelParser.POPULATION_SIZE); writer.writeOpenTag(LogisticGrowthModelParser.GROWTH_RATE); writeParameter("logisticReference.growthRate", "logistic.growthRate", beautiOptions.logFileName, (int) (options.mleChainLength * 0.10), writer); writer.writeCloseTag(LogisticGrowthModelParser.GROWTH_RATE); writer.writeOpenTag(LogisticGrowthModelParser.TIME_50); writeParameter("logisticReference.t50", "logistic.t50", beautiOptions.logFileName, (int) (options.mleChainLength * 0.10), writer); writer.writeCloseTag(LogisticGrowthModelParser.TIME_50); writer.writeCloseTag(LogisticGrowthModelParser.LOGISTIC_GROWTH_MODEL); writer.writeComment("A working prior for the coalescent."); writer.writeOpenTag( CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, modelPrefix + "coalescentReference") } ); writer.writeOpenTag(CoalescentLikelihoodParser.MODEL); writer.writeIDref(LogisticGrowthModelParser.LOGISTIC_GROWTH_MODEL, beautiOptions.getPartitionTreePriors().get(0).getPrefix() + "constantReference"); writer.writeCloseTag(CoalescentLikelihoodParser.MODEL); writer.writeOpenTag(CoalescentLikelihoodParser.POPULATION_TREE); writer.writeIDref(TreeModel.TREE_MODEL, modelPrefix + TreeModel.TREE_MODEL); writer.writeCloseTag(CoalescentLikelihoodParser.POPULATION_TREE); writer.writeCloseTag(CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD); break; case EXPANSION: writer.writeComment("A working prior for the expansion growth model."); writer.writeOpenTag( ExpansionModelParser.EXPANSION_MODEL, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, modelPrefix + "expansionReference"), new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(beautiOptions.units)) } ); writer.writeOpenTag(ExpansionModelParser.POPULATION_SIZE); writeParameter("expansionReference.popSize", "expansion.popSize", beautiOptions.logFileName, (int) (options.mleChainLength * 0.10), writer); writer.writeCloseTag(ExpansionModelParser.POPULATION_SIZE); writer.writeOpenTag(ExpansionModelParser.GROWTH_RATE); writeParameter("expansionReference.growthRate", "expansion.growthRate", beautiOptions.logFileName, (int) (options.mleChainLength * 0.10), writer); writer.writeCloseTag(ExpansionModelParser.GROWTH_RATE); writer.writeOpenTag(ExpansionModelParser.ANCESTRAL_POPULATION_PROPORTION); writeParameter("expansionReference.ancestralProportion", "expansion.ancestralProportion", beautiOptions.logFileName, (int) (options.mleChainLength * 0.10), writer); writer.writeCloseTag(ExpansionModelParser.ANCESTRAL_POPULATION_PROPORTION); writer.writeCloseTag(ExpansionModelParser.EXPANSION_MODEL); writer.writeComment("A working prior for the coalescent."); writer.writeOpenTag( CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, modelPrefix + "coalescentReference") } ); writer.writeOpenTag(CoalescentLikelihoodParser.MODEL); writer.writeIDref(ExpansionModelParser.EXPANSION_MODEL, beautiOptions.getPartitionTreePriors().get(0).getPrefix() + "constantReference"); writer.writeCloseTag(CoalescentLikelihoodParser.MODEL); writer.writeOpenTag(CoalescentLikelihoodParser.POPULATION_TREE); writer.writeIDref(TreeModel.TREE_MODEL, modelPrefix + TreeModel.TREE_MODEL); writer.writeCloseTag(CoalescentLikelihoodParser.POPULATION_TREE); writer.writeCloseTag(CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD); break; default: //Do not switch to product of exponentials as the coalescentEventsStatistic has not been logged //TODO: show menu that explains mismatch between prior and working prior? //TODO: but show it when the MCM option is wrongfully being selected, don't do anything here } } writer.writeComment("Define marginal likelihood estimator (GSS) settings"); List<Attribute> attributes = new ArrayList<Attribute>(); attributes.add(new Attribute.Default<Integer>(MarginalLikelihoodEstimator.CHAIN_LENGTH, options.mleChainLength)); attributes.add(new Attribute.Default<Integer>(MarginalLikelihoodEstimator.PATH_STEPS, options.pathSteps)); attributes.add(new Attribute.Default<String>(MarginalLikelihoodEstimator.PATH_SCHEME, options.pathScheme)); if (!options.pathScheme.equals(MarginalLikelihoodEstimator.LINEAR)) { attributes.add(new Attribute.Default<Double>(MarginalLikelihoodEstimator.ALPHA, options.schemeParameter)); } writer.writeOpenTag(MarginalLikelihoodEstimator.MARGINAL_LIKELIHOOD_ESTIMATOR, attributes); writer.writeOpenTag("samplers"); writer.writeIDref("mcmc", "mcmc"); writer.writeCloseTag("samplers"); attributes = new ArrayList<Attribute>(); attributes.add(new Attribute.Default<String>(XMLParser.ID, "pathLikelihood")); writer.writeOpenTag(PathLikelihood.PATH_LIKELIHOOD, attributes); writer.writeOpenTag(PathLikelihood.SOURCE); writer.writeIDref(CompoundLikelihoodParser.POSTERIOR, CompoundLikelihoodParser.POSTERIOR); writer.writeCloseTag(PathLikelihood.SOURCE); writer.writeOpenTag(PathLikelihood.DESTINATION); writer.writeOpenTag(CompoundLikelihoodParser.WORKING_PRIOR); ArrayList<Parameter> parameters = beautiOptions.selectParameters(); for (Parameter param : parameters) { if (DEBUG) { System.err.println(param.toString() + " " + param.priorType.toString()); } //should leave out those parameters set by the coalescent if (param.priorType != PriorType.NONE_TREE_PRIOR) { //TODO: frequencies is multidimensional, is that automatically dealt with? writer.writeOpenTag(WorkingPriorParsers.NORMAL_REFERENCE_PRIOR, new Attribute[]{ new Attribute.Default<String>("fileName", beautiOptions.logFileName), new Attribute.Default<String>("parameterColumn", param.getName()), new Attribute.Default<String>("burnin", "" + beautiOptions.chainLength*0.10) }); writeParameterIdref(writer, param); writer.writeCloseTag(WorkingPriorParsers.NORMAL_REFERENCE_PRIOR); } } if (options.choiceTreeWorkingPrior.equals("Product of exponential distributions")) { writer.writeIDref("productOfExponentialsPosteriorMeansLoess", "exponentials"); } else { writer.writeIDref(CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD, "coalescentReference"); } writer.writeCloseTag(CompoundLikelihoodParser.WORKING_PRIOR); writer.writeCloseTag(PathLikelihood.DESTINATION); writer.writeCloseTag(PathLikelihood.PATH_LIKELIHOOD); attributes = new ArrayList<Attribute>(); attributes.add(new Attribute.Default<String>(XMLParser.ID, "MLELog")); attributes.add(new Attribute.Default<Integer>("logEvery", options.mleLogEvery)); attributes.add(new Attribute.Default<String>("fileName", options.mleFileName)); writer.writeOpenTag("log", attributes); writer.writeIDref("pathLikelihood", "pathLikelihood"); writer.writeCloseTag("log"); writer.writeCloseTag(MarginalLikelihoodEstimator.MARGINAL_LIKELIHOOD_ESTIMATOR); writer.writeComment("Generalized stepping-stone sampling estimator from collected samples"); attributes = new ArrayList<Attribute>(); attributes.add(new Attribute.Default<String>("fileName", options.mleFileName)); writer.writeOpenTag(GeneralizedSteppingStoneSamplingAnalysis.GENERALIZED_STEPPING_STONE_SAMPLING_ANALYSIS, attributes); writer.writeTag("sourceColumn", new Attribute.Default<String>("name", "pathLikelihood.source"), true); writer.writeTag("destinationColumn", new Attribute.Default<String>("name", "pathLikelihood.destination"), true); writer.writeTag("thetaColumn", new Attribute.Default<String>("name", "pathLikelihood.theta"), true); writer.writeCloseTag(GeneralizedSteppingStoneSamplingAnalysis.GENERALIZED_STEPPING_STONE_SAMPLING_ANALYSIS); } } private void writeParameterIdref(XMLWriter writer, Parameter parameter) { if (parameter.isStatistic) { writer.writeIDref("statistic", parameter.getName()); } else { writer.writeIDref(ParameterParser.PARAMETER, parameter.getName()); } } }
package org.exist.util.hashtable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * A hash set on objects. Objects are compared for equality by * calling Object.equals(). * calling Object.equals(). * * @author Wolfgang Meier (wolfgang@exist-db.org) */ public class ObjectHashSet<K> extends AbstractHashSet<K> { protected K[] keys; public ObjectHashSet() { super(); keys = (K[]) new Object[tabSize]; } /** * @param iSize */ public ObjectHashSet(int iSize) { super(iSize); keys = (K[]) new Object[tabSize]; } public void add(K key) { try { insert(key); } catch (final HashtableOverflowException e) { final K[] copyKeys = keys; // enlarge the table with a prime value tabSize = (int) nextPrime(tabSize + tabSize / 2); keys = (K[]) new Object[tabSize]; items = 0; for (int k = 0; k < copyKeys.length; k++) { if (copyKeys[k] != null && copyKeys[k] != REMOVED) {add(copyKeys[k]);} } add(key); } } protected void insert(K key) throws HashtableOverflowException { if (key == null) {throw new IllegalArgumentException("Illegal value: null");} int idx = hash(key) % tabSize; if (idx < 0) {idx *= -1;} int bucket = -1; // look for an empty bucket if (keys[idx] == null) { keys[idx] = key; ++items; return; } else if (keys[idx] == REMOVED) { // remember the bucket, but continue to check // for duplicate keys bucket = idx; } else if (keys[idx].equals(key)) { // duplicate value return; } final int rehashVal = rehash(idx); int rehashCnt = 1; for (int i = 0; i < tabSize; i++) { idx = (idx + rehashVal) % tabSize; if (keys[idx] == REMOVED) { bucket = idx; } else if (keys[idx] == null) { if (bucket > -1) { // store key into the empty bucket first found idx = bucket; } keys[idx] = key; ++items; return; } else if (keys[idx].equals(key)) { // duplicate value return; } ++rehashCnt; } // should never happen, but just to be sure: // if the key has not been inserted yet, do it now if (bucket > -1) { keys[bucket] = key; ++items; return; } throw new HashtableOverflowException(); } public boolean contains(K key) { int idx = hash(key) % tabSize; if (idx < 0) {idx *= -1;} if (keys[idx] == null) {return false;} // key does not exist else if (keys[idx].equals(key)) { return true; } final int rehashVal = rehash(idx); for (int i = 0; i < tabSize; i++) { idx = (idx + rehashVal) % tabSize; if (keys[idx] == null) { return false; // key not found } else if (keys[idx].equals(key)) { return true; } } return false; } public K remove(K key) { int idx = hash(key) % tabSize; if (idx < 0) {idx *= -1;} if (keys[idx] == null) { return null; // key does not exist } else if (keys[idx].equals(key)) { key = keys[idx]; keys[idx] = (K) REMOVED; --items; return key; } final int rehashVal = rehash(idx); for (int i = 0; i < tabSize; i++) { idx = (idx + rehashVal) % tabSize; if (keys[idx] == null) { return null; // key not found } else if (keys[idx].equals(key)) { key = keys[idx]; keys[idx] = (K) REMOVED; --items; return key; } } return null; } protected int rehash(int iVal) { int retVal = (iVal + iVal / 2) % tabSize; if (retVal == 0) {retVal = 1;} return retVal; } protected final static int hash(Object o) { return o.hashCode(); } public List<K> keys() { final ArrayList<K> list = new ArrayList<K>(items); for (int i = 0; i < tabSize; i++) { if (keys[i] != null && keys[i] != REMOVED) {list.add(keys[i]);} } return Collections.unmodifiableList(list); } /* (non-Javadoc) * @see org.exist.util.hashtable.AbstractHashtable#iterator() */ public Iterator<K> iterator() { return new ObjectHashSetIterator(); } public Iterator<K> stableIterator() { return new ObjectHashSetStableIterator(); } /* (non-Javadoc) * @see org.exist.util.hashtable.AbstractHashtable#valueIterator() */ public Iterator valueIterator() { return null; } protected class ObjectHashSetIterator implements Iterator<K> { int idx = 0; public ObjectHashSetIterator() { } /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { if (idx == tabSize) {return false;} while (keys[idx] == null || keys[idx] == REMOVED) { ++idx; if (idx == tabSize) {return false;} } return true; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public K next() { if (idx == tabSize) {return null;} while (keys[idx] == null || keys[idx] == REMOVED) { ++idx; if (idx == tabSize) {return null;} } return keys[idx++]; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { } } protected class ObjectHashSetStableIterator implements Iterator<K> { int idx = 0; K mKeys[]; public ObjectHashSetStableIterator() { mKeys = (K[]) new Object[tabSize]; System.arraycopy(keys, 0, mKeys, 0, tabSize); } /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { if (idx == mKeys.length) {return false;} while (mKeys[idx] == null || mKeys[idx] == REMOVED) { ++idx; if (idx == mKeys.length) {return false;} } return true; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public K next() { if (idx == mKeys.length) {return null;} while (mKeys[idx] == null || mKeys[idx] == REMOVED) { ++idx; if (idx == mKeys.length) {return null;} } return mKeys[idx++]; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { } } }
package edu.jhu.sa.util.suffix_array; import java.io.IOException; import java.util.Date; import joshua.util.sentence.Vocabulary; public class Benchmark { public static void main(String[] args) throws IOException { int cachePrecomputationFrequencyThreshold = 1000; System.err.println(new Date() + " Constructing source language vocabulary."); String sourceFileName = (args.length==0) ? "data/europarl001.en" : args[0]; Vocabulary sourceVocab = new Vocabulary(); int[] sourceWordsSentences = SuffixArrayFactory.createVocabulary(sourceFileName, sourceVocab); System.err.println(new Date() + " Constructing source language corpus array."); CorpusArray sourceCorpusArray = SuffixArrayFactory.createCorpusArray(sourceFileName, sourceVocab, sourceWordsSentences[0], sourceWordsSentences[1]); System.err.println(new Date() + " Constructing source language suffix array."); //SuffixArray sourceSuffixArray = SuffixArrayFactory.createSuffixArray(sourceCorpusArray, cachePrecomputationFrequencyThreshold); System.err.println(new Date() + " Done"); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.mod.hrs.form; import erp.mod.SModConsts; import erp.mod.SModSysConsts; import erp.mod.hrs.db.SDbAbsence; import erp.mod.hrs.db.SDbAbsenceConsumption; import erp.mod.hrs.db.SDbBenefitTable; import erp.mod.hrs.db.SDbDeduction; import erp.mod.hrs.db.SDbEarning; import erp.mod.hrs.db.SDbEmployee; import erp.mod.hrs.db.SDbLoan; import erp.mod.hrs.db.SDbPayrollReceiptDeduction; import erp.mod.hrs.db.SDbPayrollReceiptEarning; import erp.mod.hrs.db.SHrsBenefit; import erp.mod.hrs.db.SHrsBenefitParams; import erp.mod.hrs.db.SHrsEmployeeDays; import erp.mod.hrs.db.SHrsReceipt; import erp.mod.hrs.db.SHrsReceiptDeduction; import erp.mod.hrs.db.SHrsReceiptEarning; import erp.mod.hrs.db.SHrsUtils; import erp.mod.hrs.utils.SPayrollBonusUtils; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Vector; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import sa.lib.SLibConsts; import sa.lib.SLibTimeUtils; import sa.lib.SLibUtils; import sa.lib.db.SDbConsts; import sa.lib.db.SDbRegistry; import sa.lib.grid.SGridColumnForm; import sa.lib.grid.SGridConsts; import sa.lib.grid.SGridPaneForm; import sa.lib.grid.SGridPaneFormOwner; import sa.lib.grid.SGridRow; import sa.lib.gui.SGuiClient; import sa.lib.gui.SGuiConsts; import sa.lib.gui.SGuiParams; import sa.lib.gui.SGuiUtils; import sa.lib.gui.SGuiValidation; import sa.lib.gui.bean.SBeanFieldKey; import sa.lib.gui.bean.SBeanFieldText; import sa.lib.gui.bean.SBeanFormDialog; /** * * @author Juan Barajas, Sergio Flores */ public class SDialogPayrollReceipt extends SBeanFormDialog implements SGridPaneFormOwner, ActionListener, ItemListener, FocusListener, CellEditorListener { private static final int COL_VAL = 2; private static final int COL_AMT_UNT = 4; public static final String LABEL_AUX_AMT = "Monto auxiliar"; public static final String LABEL_AUX_VAL = "Valor auxiliar"; protected SHrsReceipt moHrsReceipt; protected SHrsBenefit moHrsBenefit; /** Key: ID of earning. */ protected HashMap<Integer, SDbEarning> moEarnigsMap; /** Key: ID of deduction. */ protected HashMap<Integer, SDbDeduction> moDeductionsMap; protected SDbEarning moEarning; protected SDbDeduction moDeduction; protected String msOriginalEarningCode; protected String msOriginalDeductionCode; protected SGridPaneForm moGridReceiptEarnings; protected SGridPaneForm moGridReceiptDeductions; protected SGridPaneForm moGridAbsenceConsumptions; protected boolean mbEditable; /** * Creates new form SDialogPayrollReceipt * @param client * @param title */ public SDialogPayrollReceipt(SGuiClient client, String title) { setFormSettings(client, SGuiConsts.BEAN_FORM_EDIT, SModConsts.HRS_PAY_RCP, SLibConsts.UNDEFINED, title); initComponents(); initComponentsCustom(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel12 = new javax.swing.JPanel(); jPanel15 = new javax.swing.JPanel(); jPanel16 = new javax.swing.JPanel(); jlName = new javax.swing.JLabel(); moTextName = new sa.lib.gui.bean.SBeanFieldText(); moTextNumber = new sa.lib.gui.bean.SBeanFieldText(); moTextId = new sa.lib.gui.bean.SBeanFieldText(); jPanel17 = new javax.swing.JPanel(); jlPaymentType = new javax.swing.JLabel(); moTextPaymentType = new sa.lib.gui.bean.SBeanFieldText(); jlDateBirth = new javax.swing.JLabel(); moTextDateBirth = new sa.lib.gui.bean.SBeanFieldText(); jlDepartament = new javax.swing.JLabel(); moTextDepartament = new sa.lib.gui.bean.SBeanFieldText(); jlSalaryType = new javax.swing.JLabel(); moTextSalaryType = new sa.lib.gui.bean.SBeanFieldText(); jlFiscalId = new javax.swing.JLabel(); moTextFiscalId = new sa.lib.gui.bean.SBeanFieldText(); jPanel29 = new javax.swing.JPanel(); jlSalary = new javax.swing.JLabel(); moDecSalary = new sa.lib.gui.bean.SBeanFieldDecimal(); jlDateBenefits = new javax.swing.JLabel(); moTextDateBenefits = new sa.lib.gui.bean.SBeanFieldText(); jlPosition = new javax.swing.JLabel(); moTextPosition = new sa.lib.gui.bean.SBeanFieldText(); jlEmployeeType = new javax.swing.JLabel(); moTextEmployeeType = new sa.lib.gui.bean.SBeanFieldText(); jlAlternativeId = new javax.swing.JLabel(); moTextAlternativeId = new sa.lib.gui.bean.SBeanFieldText(); jPanel18 = new javax.swing.JPanel(); jlWage = new javax.swing.JLabel(); moDecWage = new sa.lib.gui.bean.SBeanFieldDecimal(); jlDateLastHire = new javax.swing.JLabel(); moTextDateLastHire = new sa.lib.gui.bean.SBeanFieldText(); jlShift = new javax.swing.JLabel(); moTextShift = new sa.lib.gui.bean.SBeanFieldText(); jlWorkerType = new javax.swing.JLabel(); moTextWorkerType = new sa.lib.gui.bean.SBeanFieldText(); jlSocialSecurityNumber = new javax.swing.JLabel(); moTextSocialSecurityNumber = new sa.lib.gui.bean.SBeanFieldText(); jPanel19 = new javax.swing.JPanel(); jlSalarySscBase = new javax.swing.JLabel(); moDecSalarySscBase = new sa.lib.gui.bean.SBeanFieldDecimal(); jlDateLastDismissal_n = new javax.swing.JLabel(); moTextDateLastDismissal_n = new sa.lib.gui.bean.SBeanFieldText(); jlWorkingHoursDay = new javax.swing.JLabel(); moIntWorkingHoursDay = new sa.lib.gui.bean.SBeanFieldInteger(); jLabel1 = new javax.swing.JLabel(); jlRecruitmentSchemeType = new javax.swing.JLabel(); moTextRecruitmentSchemeType = new sa.lib.gui.bean.SBeanFieldText(); jPanel14 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jpEarnings = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jPanel8 = new javax.swing.JPanel(); moTextEarningCode = new sa.lib.gui.bean.SBeanFieldText(); jbPickEarning = new javax.swing.JButton(); moTextEarningName = new sa.lib.gui.bean.SBeanFieldText(); jlBonus = new javax.swing.JLabel(); moKeyBonusType = new sa.lib.gui.bean.SBeanFieldKey(); jPanel28 = new javax.swing.JPanel(); jlEarningLoan_n1 = new javax.swing.JLabel(); moKeyEarningOtherPaymentType = new sa.lib.gui.bean.SBeanFieldKey(); jPanel2 = new javax.swing.JPanel(); jlEarningLoan_n = new javax.swing.JLabel(); moKeyEarningLoan_n = new sa.lib.gui.bean.SBeanFieldKey(); jPanel25 = new javax.swing.JPanel(); jlEarningValue = new javax.swing.JLabel(); moCompEarningValue = new sa.lib.gui.bean.SBeanCompoundField(); jLabel2 = new javax.swing.JLabel(); jlEarningAuxAmount1 = new javax.swing.JLabel(); moCurEarningAuxAmount1 = new sa.lib.gui.bean.SBeanCompoundFieldCurrency(); jlEarningAuxAmount1Hint = new javax.swing.JLabel(); jPanel10 = new javax.swing.JPanel(); jbAddEarning = new javax.swing.JButton(); jPanel27 = new javax.swing.JPanel(); jlEarningAuxValue = new javax.swing.JLabel(); moCompEarningAuxValue = new sa.lib.gui.bean.SBeanCompoundField(); jlEarningAuxValueHint = new javax.swing.JLabel(); jlEarningAuxAmount2 = new javax.swing.JLabel(); moCurEarningAuxAmount2 = new sa.lib.gui.bean.SBeanCompoundFieldCurrency(); jlEarningAuxAmount2Hint = new javax.swing.JLabel(); jpDeductions = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jPanel9 = new javax.swing.JPanel(); moTextDeductionCode = new sa.lib.gui.bean.SBeanFieldText(); jbPickDeduction = new javax.swing.JButton(); moTextDeductionName = new sa.lib.gui.bean.SBeanFieldText(); jPanel30 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jlDeductionLoan_n = new javax.swing.JLabel(); moKeyDeductionLoan_n = new sa.lib.gui.bean.SBeanFieldKey(); jPanel26 = new javax.swing.JPanel(); jlDeductionValue = new javax.swing.JLabel(); moCompDeductionValue = new sa.lib.gui.bean.SBeanCompoundField(); jPanel11 = new javax.swing.JPanel(); jbAddDeduction = new javax.swing.JButton(); jPanel21 = new javax.swing.JPanel(); jPanel20 = new javax.swing.JPanel(); jpAbsenceConsumption = new javax.swing.JPanel(); jPanel13 = new javax.swing.JPanel(); jPanel22 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jlEarningsTotal = new javax.swing.JLabel(); moCurEarningsTotal = new sa.lib.gui.bean.SBeanCompoundFieldCurrency(); jPanel23 = new javax.swing.JPanel(); jlDeductionsTotal = new javax.swing.JLabel(); moCurDeductionsTotal = new sa.lib.gui.bean.SBeanCompoundFieldCurrency(); jPanel24 = new javax.swing.JPanel(); jlNetTotal = new javax.swing.JLabel(); moCurNetTotal = new sa.lib.gui.bean.SBeanCompoundFieldCurrency(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Recibo de nómina"); jPanel1.setLayout(new java.awt.BorderLayout()); jPanel12.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del empleado:")); jPanel12.setLayout(new java.awt.BorderLayout()); jPanel15.setLayout(new java.awt.GridLayout(5, 1, 0, 5)); jPanel16.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0)); jlName.setText("Nombre:"); jlName.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel16.add(jlName); moTextName.setEditable(false); moTextName.setText("TEXT"); moTextName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N moTextName.setPreferredSize(new java.awt.Dimension(385, 23)); jPanel16.add(moTextName); moTextNumber.setEditable(false); moTextNumber.setText("TEXT"); moTextNumber.setToolTipText("Clave"); moTextNumber.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N moTextNumber.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel16.add(moTextNumber); moTextId.setEditable(false); moTextId.setForeground(java.awt.SystemColor.textInactiveText); moTextId.setHorizontalAlignment(javax.swing.JTextField.TRAILING); moTextId.setText("TEXT"); moTextId.setToolTipText("ID"); moTextId.setPreferredSize(new java.awt.Dimension(50, 23)); jPanel16.add(moTextId); jPanel15.add(jPanel16); jPanel17.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0)); jlPaymentType.setText("Período pago:"); jlPaymentType.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel17.add(jlPaymentType); moTextPaymentType.setEditable(false); moTextPaymentType.setText("TEXT"); moTextPaymentType.setPreferredSize(new java.awt.Dimension(85, 23)); jPanel17.add(moTextPaymentType); jlDateBirth.setText("Nacimiento:"); jlDateBirth.setPreferredSize(new java.awt.Dimension(90, 23)); jPanel17.add(jlDateBirth); moTextDateBirth.setEditable(false); moTextDateBirth.setText("TEXT"); moTextDateBirth.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel17.add(moTextDateBirth); jlDepartament.setText("Departamento:"); jlDepartament.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel17.add(jlDepartament); moTextDepartament.setEditable(false); moTextDepartament.setText("TEXT"); moTextDepartament.setPreferredSize(new java.awt.Dimension(175, 23)); jPanel17.add(moTextDepartament); jlSalaryType.setText("Tipo salario:"); jlSalaryType.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel17.add(jlSalaryType); moTextSalaryType.setEditable(false); moTextSalaryType.setText("TEXT"); jPanel17.add(moTextSalaryType); jlFiscalId.setText("RFC:"); jlFiscalId.setPreferredSize(new java.awt.Dimension(40, 23)); jPanel17.add(jlFiscalId); moTextFiscalId.setEditable(false); moTextFiscalId.setText("XAXX010101000"); moTextFiscalId.setPreferredSize(new java.awt.Dimension(105, 23)); jPanel17.add(moTextFiscalId); jPanel15.add(jPanel17); jPanel29.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlSalary.setText("Salario diario:"); jlSalary.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel29.add(jlSalary); moDecSalary.setEditable(false); moDecSalary.setPreferredSize(new java.awt.Dimension(85, 23)); jPanel29.add(moDecSalary); jlDateBenefits.setText("Inicio beneficios:"); jlDateBenefits.setPreferredSize(new java.awt.Dimension(90, 23)); jPanel29.add(jlDateBenefits); moTextDateBenefits.setEditable(false); moTextDateBenefits.setText("TEXT"); moTextDateBenefits.setToolTipText(""); moTextDateBenefits.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel29.add(moTextDateBenefits); jlPosition.setText("Puesto:"); jlPosition.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel29.add(jlPosition); moTextPosition.setEditable(false); moTextPosition.setText("TEXT"); moTextPosition.setPreferredSize(new java.awt.Dimension(175, 23)); jPanel29.add(moTextPosition); jlEmployeeType.setText("Tipo empleado:"); jlEmployeeType.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel29.add(jlEmployeeType); moTextEmployeeType.setEditable(false); moTextEmployeeType.setText("TEXT"); jPanel29.add(moTextEmployeeType); jlAlternativeId.setText("CURP:"); jlAlternativeId.setPreferredSize(new java.awt.Dimension(40, 23)); jPanel29.add(jlAlternativeId); moTextAlternativeId.setEditable(false); moTextAlternativeId.setText("XAXX010101XXXXXX00"); moTextAlternativeId.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel29.add(moTextAlternativeId); jPanel15.add(jPanel29); jPanel18.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0)); jlWage.setText("Sueldo mensual:"); jlWage.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel18.add(jlWage); moDecWage.setEditable(false); moDecWage.setText("0"); moDecWage.setPreferredSize(new java.awt.Dimension(85, 23)); jPanel18.add(moDecWage); jlDateLastHire.setText("Última alta:"); jlDateLastHire.setPreferredSize(new java.awt.Dimension(90, 23)); jPanel18.add(jlDateLastHire); moTextDateLastHire.setEditable(false); moTextDateLastHire.setText("TEXT"); moTextDateLastHire.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel18.add(moTextDateLastHire); jlShift.setText("Turno:"); jlShift.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel18.add(jlShift); moTextShift.setEditable(false); moTextShift.setText("TEXT"); moTextShift.setPreferredSize(new java.awt.Dimension(175, 23)); jPanel18.add(moTextShift); jlWorkerType.setText("Tipo obrero:"); jlWorkerType.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel18.add(jlWorkerType); moTextWorkerType.setEditable(false); moTextWorkerType.setText("TEXT"); jPanel18.add(moTextWorkerType); jlSocialSecurityNumber.setText("NSS:"); jlSocialSecurityNumber.setPreferredSize(new java.awt.Dimension(40, 23)); jPanel18.add(jlSocialSecurityNumber); moTextSocialSecurityNumber.setEditable(false); moTextSocialSecurityNumber.setText("00000000000"); moTextSocialSecurityNumber.setPreferredSize(new java.awt.Dimension(85, 23)); jPanel18.add(moTextSocialSecurityNumber); jPanel15.add(jPanel18); jPanel19.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0)); jlSalarySscBase.setText("SBC:"); jlSalarySscBase.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel19.add(jlSalarySscBase); moDecSalarySscBase.setEditable(false); moDecSalarySscBase.setPreferredSize(new java.awt.Dimension(85, 23)); jPanel19.add(moDecSalarySscBase); jlDateLastDismissal_n.setText("Última baja:"); jlDateLastDismissal_n.setPreferredSize(new java.awt.Dimension(90, 23)); jPanel19.add(jlDateLastDismissal_n); moTextDateLastDismissal_n.setEditable(false); moTextDateLastDismissal_n.setText("TEXT"); moTextDateLastDismissal_n.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel19.add(moTextDateLastDismissal_n); jlWorkingHoursDay.setText("Horas jornada:"); jlWorkingHoursDay.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel19.add(jlWorkingHoursDay); moIntWorkingHoursDay.setEditable(false); moIntWorkingHoursDay.setPreferredSize(new java.awt.Dimension(50, 23)); jPanel19.add(moIntWorkingHoursDay); jLabel1.setPreferredSize(new java.awt.Dimension(120, 23)); jPanel19.add(jLabel1); jlRecruitmentSchemeType.setText("Régimen:"); jlRecruitmentSchemeType.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel19.add(jlRecruitmentSchemeType); moTextRecruitmentSchemeType.setEditable(false); moTextRecruitmentSchemeType.setText("TEXT"); moTextRecruitmentSchemeType.setPreferredSize(new java.awt.Dimension(275, 23)); jPanel19.add(moTextRecruitmentSchemeType); jPanel15.add(jPanel19); jPanel12.add(jPanel15, java.awt.BorderLayout.CENTER); jPanel1.add(jPanel12, java.awt.BorderLayout.NORTH); jPanel14.setLayout(new java.awt.BorderLayout()); jPanel4.setPreferredSize(new java.awt.Dimension(100, 325)); jPanel4.setLayout(new java.awt.BorderLayout()); jpEarnings.setBorder(javax.swing.BorderFactory.createTitledBorder("Percepciones:")); jpEarnings.setLayout(new java.awt.BorderLayout()); jPanel6.setLayout(new java.awt.GridLayout(5, 1, 0, 5)); jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0)); moTextEarningCode.setText("TEXT"); moTextEarningCode.setToolTipText("Código percepción"); moTextEarningCode.setPreferredSize(new java.awt.Dimension(72, 23)); jPanel8.add(moTextEarningCode); jbPickEarning.setText("..."); jbPickEarning.setToolTipText("Seleccionar percepción"); jbPickEarning.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel8.add(jbPickEarning); moTextEarningName.setEditable(false); moTextEarningName.setText("TEXT"); moTextEarningName.setToolTipText("Nombre percepción"); moTextEarningName.setPreferredSize(new java.awt.Dimension(250, 23)); jPanel8.add(moTextEarningName); jlBonus.setText("Bono:"); jlBonus.setPreferredSize(new java.awt.Dimension(40, 23)); jPanel8.add(jlBonus); moKeyBonusType.setToolTipText("Pago de bono"); moKeyBonusType.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel8.add(moKeyBonusType); jPanel6.add(jPanel8); jPanel28.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlEarningLoan_n1.setText("Tipo otro pago:*"); jlEarningLoan_n1.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel28.add(jlEarningLoan_n1); moKeyEarningOtherPaymentType.setToolTipText("Tipo otro pago"); moKeyEarningOtherPaymentType.setPreferredSize(new java.awt.Dimension(450, 23)); jPanel28.add(moKeyEarningOtherPaymentType); jPanel6.add(jPanel28); jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0)); jlEarningLoan_n.setText("Crédito/préstamo:*"); jlEarningLoan_n.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel2.add(jlEarningLoan_n); moKeyEarningLoan_n.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel2.add(moKeyEarningLoan_n); jPanel6.add(jPanel2); jPanel25.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0)); jlEarningValue.setText("Cantidad/monto:"); jlEarningValue.setToolTipText(""); jlEarningValue.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel25.add(jlEarningValue); moCompEarningValue.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel25.add(moCompEarningValue); jLabel2.setPreferredSize(new java.awt.Dimension(15, 23)); jPanel25.add(jLabel2); jlEarningAuxAmount1.setText("Monto auxiliar:"); jlEarningAuxAmount1.setToolTipText(""); jlEarningAuxAmount1.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel25.add(jlEarningAuxAmount1); moCurEarningAuxAmount1.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel25.add(moCurEarningAuxAmount1); jlEarningAuxAmount1Hint.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jlEarningAuxAmount1Hint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_view_help.png"))); // NOI18N jlEarningAuxAmount1Hint.setToolTipText("Monto auxiliar"); jlEarningAuxAmount1Hint.setPreferredSize(new java.awt.Dimension(15, 23)); jPanel25.add(jlEarningAuxAmount1Hint); jPanel6.add(jPanel25); jPanel10.setLayout(new java.awt.BorderLayout()); jbAddEarning.setText("Agregar"); jbAddEarning.setMargin(new java.awt.Insets(2, 0, 2, 0)); jbAddEarning.setPreferredSize(new java.awt.Dimension(65, 23)); jPanel10.add(jbAddEarning, java.awt.BorderLayout.EAST); jPanel27.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlEarningAuxValue.setText("Valor auxiliar:"); jlEarningAuxValue.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel27.add(jlEarningAuxValue); moCompEarningAuxValue.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel27.add(moCompEarningAuxValue); jlEarningAuxValueHint.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jlEarningAuxValueHint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_view_help.png"))); // NOI18N jlEarningAuxValueHint.setToolTipText("Monto auxiliar"); jlEarningAuxValueHint.setPreferredSize(new java.awt.Dimension(15, 23)); jPanel27.add(jlEarningAuxValueHint); jlEarningAuxAmount2.setText("Monto auxiliar:"); jlEarningAuxAmount2.setToolTipText(""); jlEarningAuxAmount2.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel27.add(jlEarningAuxAmount2); moCurEarningAuxAmount2.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel27.add(moCurEarningAuxAmount2); jlEarningAuxAmount2Hint.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jlEarningAuxAmount2Hint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_view_help.png"))); // NOI18N jlEarningAuxAmount2Hint.setToolTipText("Monto auxiliar"); jlEarningAuxAmount2Hint.setPreferredSize(new java.awt.Dimension(15, 23)); jPanel27.add(jlEarningAuxAmount2Hint); jPanel10.add(jPanel27, java.awt.BorderLayout.CENTER); jPanel6.add(jPanel10); jpEarnings.add(jPanel6, java.awt.BorderLayout.NORTH); jPanel4.add(jpEarnings, java.awt.BorderLayout.CENTER); jpDeductions.setBorder(javax.swing.BorderFactory.createTitledBorder("Deducciones:")); jpDeductions.setPreferredSize(new java.awt.Dimension(425, 1)); jpDeductions.setLayout(new java.awt.BorderLayout()); jPanel7.setLayout(new java.awt.GridLayout(5, 1, 0, 5)); jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0)); moTextDeductionCode.setText("TEXT"); moTextDeductionCode.setToolTipText("Código deducción"); moTextDeductionCode.setPreferredSize(new java.awt.Dimension(72, 23)); jPanel9.add(moTextDeductionCode); jbPickDeduction.setText("..."); jbPickDeduction.setToolTipText("Seleccionar deducción"); jbPickDeduction.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel9.add(jbPickDeduction); moTextDeductionName.setEditable(false); moTextDeductionName.setText("TEXT"); moTextDeductionName.setToolTipText("Nombre deducción"); moTextDeductionName.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel9.add(moTextDeductionName); jPanel7.add(jPanel9); jPanel30.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jPanel7.add(jPanel30); jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0)); jlDeductionLoan_n.setText("Crédito/préstamo:*"); jlDeductionLoan_n.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel3.add(jlDeductionLoan_n); moKeyDeductionLoan_n.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel3.add(moKeyDeductionLoan_n); jPanel7.add(jPanel3); jPanel26.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 5, 0)); jlDeductionValue.setText("Cantidad/monto:"); jlDeductionValue.setToolTipText(""); jlDeductionValue.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel26.add(jlDeductionValue); moCompDeductionValue.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel26.add(moCompDeductionValue); jPanel7.add(jPanel26); jPanel11.setLayout(new java.awt.BorderLayout()); jbAddDeduction.setText("Agregar"); jbAddDeduction.setMargin(new java.awt.Insets(2, 0, 2, 0)); jbAddDeduction.setPreferredSize(new java.awt.Dimension(65, 23)); jPanel11.add(jbAddDeduction, java.awt.BorderLayout.EAST); jPanel21.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jPanel11.add(jPanel21, java.awt.BorderLayout.CENTER); jPanel7.add(jPanel11); jpDeductions.add(jPanel7, java.awt.BorderLayout.NORTH); jPanel4.add(jpDeductions, java.awt.BorderLayout.EAST); jPanel14.add(jPanel4, java.awt.BorderLayout.NORTH); jPanel20.setLayout(new java.awt.BorderLayout()); jpAbsenceConsumption.setBorder(javax.swing.BorderFactory.createTitledBorder("Consumo incidencias:")); jpAbsenceConsumption.setLayout(new java.awt.BorderLayout()); jPanel20.add(jpAbsenceConsumption, java.awt.BorderLayout.CENTER); jPanel13.setBorder(javax.swing.BorderFactory.createTitledBorder("Totales:")); jPanel13.setLayout(new java.awt.BorderLayout()); jPanel22.setLayout(new java.awt.GridLayout(3, 1, 0, 5)); jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.TRAILING, 5, 0)); jlEarningsTotal.setText("Total percepciones:"); jlEarningsTotal.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel5.add(jlEarningsTotal); moCurEarningsTotal.setEditable(false); jPanel5.add(moCurEarningsTotal); jPanel22.add(jPanel5); jPanel23.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.TRAILING, 5, 0)); jlDeductionsTotal.setText("Total deducciones:"); jlDeductionsTotal.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel23.add(jlDeductionsTotal); moCurDeductionsTotal.setEditable(false); jPanel23.add(moCurDeductionsTotal); jPanel22.add(jPanel23); jPanel24.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.TRAILING, 5, 0)); jlNetTotal.setText("Total neto:"); jlNetTotal.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel24.add(jlNetTotal); moCurNetTotal.setEditable(false); jPanel24.add(moCurNetTotal); jPanel22.add(jPanel24); jPanel13.add(jPanel22, java.awt.BorderLayout.SOUTH); jPanel20.add(jPanel13, java.awt.BorderLayout.EAST); jPanel14.add(jPanel20, java.awt.BorderLayout.CENTER); jPanel1.add(jPanel14, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel11; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel13; private javax.swing.JPanel jPanel14; private javax.swing.JPanel jPanel15; private javax.swing.JPanel jPanel16; private javax.swing.JPanel jPanel17; private javax.swing.JPanel jPanel18; private javax.swing.JPanel jPanel19; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel20; private javax.swing.JPanel jPanel21; private javax.swing.JPanel jPanel22; private javax.swing.JPanel jPanel23; private javax.swing.JPanel jPanel24; private javax.swing.JPanel jPanel25; private javax.swing.JPanel jPanel26; private javax.swing.JPanel jPanel27; private javax.swing.JPanel jPanel28; private javax.swing.JPanel jPanel29; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel30; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JButton jbAddDeduction; private javax.swing.JButton jbAddEarning; private javax.swing.JButton jbPickDeduction; private javax.swing.JButton jbPickEarning; private javax.swing.JLabel jlAlternativeId; private javax.swing.JLabel jlBonus; private javax.swing.JLabel jlDateBenefits; private javax.swing.JLabel jlDateBirth; private javax.swing.JLabel jlDateLastDismissal_n; private javax.swing.JLabel jlDateLastHire; private javax.swing.JLabel jlDeductionLoan_n; private javax.swing.JLabel jlDeductionValue; private javax.swing.JLabel jlDeductionsTotal; private javax.swing.JLabel jlDepartament; private javax.swing.JLabel jlEarningAuxAmount1; private javax.swing.JLabel jlEarningAuxAmount1Hint; private javax.swing.JLabel jlEarningAuxAmount2; private javax.swing.JLabel jlEarningAuxAmount2Hint; private javax.swing.JLabel jlEarningAuxValue; private javax.swing.JLabel jlEarningAuxValueHint; private javax.swing.JLabel jlEarningLoan_n; private javax.swing.JLabel jlEarningLoan_n1; private javax.swing.JLabel jlEarningValue; private javax.swing.JLabel jlEarningsTotal; private javax.swing.JLabel jlEmployeeType; private javax.swing.JLabel jlFiscalId; private javax.swing.JLabel jlName; private javax.swing.JLabel jlNetTotal; private javax.swing.JLabel jlPaymentType; private javax.swing.JLabel jlPosition; private javax.swing.JLabel jlRecruitmentSchemeType; private javax.swing.JLabel jlSalary; private javax.swing.JLabel jlSalarySscBase; private javax.swing.JLabel jlSalaryType; private javax.swing.JLabel jlShift; private javax.swing.JLabel jlSocialSecurityNumber; private javax.swing.JLabel jlWage; private javax.swing.JLabel jlWorkerType; private javax.swing.JLabel jlWorkingHoursDay; private javax.swing.JPanel jpAbsenceConsumption; private javax.swing.JPanel jpDeductions; private javax.swing.JPanel jpEarnings; private sa.lib.gui.bean.SBeanCompoundField moCompDeductionValue; private sa.lib.gui.bean.SBeanCompoundField moCompEarningAuxValue; private sa.lib.gui.bean.SBeanCompoundField moCompEarningValue; private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurDeductionsTotal; private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurEarningAuxAmount1; private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurEarningAuxAmount2; private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurEarningsTotal; private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurNetTotal; private sa.lib.gui.bean.SBeanFieldDecimal moDecSalary; private sa.lib.gui.bean.SBeanFieldDecimal moDecSalarySscBase; private sa.lib.gui.bean.SBeanFieldDecimal moDecWage; private sa.lib.gui.bean.SBeanFieldInteger moIntWorkingHoursDay; private sa.lib.gui.bean.SBeanFieldKey moKeyBonusType; private sa.lib.gui.bean.SBeanFieldKey moKeyDeductionLoan_n; private sa.lib.gui.bean.SBeanFieldKey moKeyEarningLoan_n; private sa.lib.gui.bean.SBeanFieldKey moKeyEarningOtherPaymentType; private sa.lib.gui.bean.SBeanFieldText moTextAlternativeId; private sa.lib.gui.bean.SBeanFieldText moTextDateBenefits; private sa.lib.gui.bean.SBeanFieldText moTextDateBirth; private sa.lib.gui.bean.SBeanFieldText moTextDateLastDismissal_n; private sa.lib.gui.bean.SBeanFieldText moTextDateLastHire; private sa.lib.gui.bean.SBeanFieldText moTextDeductionCode; private sa.lib.gui.bean.SBeanFieldText moTextDeductionName; private sa.lib.gui.bean.SBeanFieldText moTextDepartament; private sa.lib.gui.bean.SBeanFieldText moTextEarningCode; private sa.lib.gui.bean.SBeanFieldText moTextEarningName; private sa.lib.gui.bean.SBeanFieldText moTextEmployeeType; private sa.lib.gui.bean.SBeanFieldText moTextFiscalId; private sa.lib.gui.bean.SBeanFieldText moTextId; private sa.lib.gui.bean.SBeanFieldText moTextName; private sa.lib.gui.bean.SBeanFieldText moTextNumber; private sa.lib.gui.bean.SBeanFieldText moTextPaymentType; private sa.lib.gui.bean.SBeanFieldText moTextPosition; private sa.lib.gui.bean.SBeanFieldText moTextRecruitmentSchemeType; private sa.lib.gui.bean.SBeanFieldText moTextSalaryType; private sa.lib.gui.bean.SBeanFieldText moTextShift; private sa.lib.gui.bean.SBeanFieldText moTextSocialSecurityNumber; private sa.lib.gui.bean.SBeanFieldText moTextWorkerType; // End of variables declaration//GEN-END:variables private void initComponentsCustom() { SGuiUtils.setWindowBounds(this, 1024, 672); // aspect ratio: 0.65625 instead of standard 0.625 jbSave.setText("Aceptar"); moTextName.setTextSettings(SGuiUtils.getLabelName(jlName), 202); moTextNumber.setTextSettings(SGuiUtils.getLabelName(jlName), 10); moTextId.setTextSettings(SGuiUtils.getLabelName(jlName), 10); moTextPaymentType.setTextSettings(SGuiUtils.getLabelName(jlName), 50); moDecSalary.setDecimalSettings(SGuiUtils.getLabelName(jlSalary), SGuiConsts.GUI_TYPE_DEC_AMT, false); moDecWage.setDecimalSettings(SGuiUtils.getLabelName(jlWage), SGuiConsts.GUI_TYPE_DEC_AMT, false); moDecSalarySscBase.setDecimalSettings(SGuiUtils.getLabelName(jlSalarySscBase), SGuiConsts.GUI_TYPE_DEC_AMT, false); moTextDateBirth.setTextSettings(SGuiUtils.getLabelName(jlName), 50); moTextDateBenefits.setTextSettings(SGuiUtils.getLabelName(jlName), 50); moTextDateLastHire.setTextSettings(SGuiUtils.getLabelName(jlName), 50); moTextDateLastDismissal_n.setTextSettings(SGuiUtils.getLabelName(jlName), 50); moTextDepartament.setTextSettings(SGuiUtils.getLabelName(jlName), 50); moTextPosition.setTextSettings(SGuiUtils.getLabelName(jlName), 50); moTextShift.setTextSettings(SGuiUtils.getLabelName(jlName), 50); moIntWorkingHoursDay.setIntegerSettings(SGuiUtils.getLabelName(jlName), SGuiConsts.GUI_TYPE_INT, false); moTextSalaryType.setTextSettings(SGuiUtils.getLabelName(jlName), 100); moTextEmployeeType.setTextSettings(SGuiUtils.getLabelName(jlName), 100); moTextWorkerType.setTextSettings(SGuiUtils.getLabelName(jlName), 100); moTextRecruitmentSchemeType.setTextSettings(SGuiUtils.getLabelName(jlName), 100); moTextFiscalId.setTextSettings(SGuiUtils.getLabelName(jlName), 25); moTextAlternativeId.setTextSettings(SGuiUtils.getLabelName(jlName), 25); moTextSocialSecurityNumber.setTextSettings(SGuiUtils.getLabelName(jlName), 25); moTextEarningCode.setTextSettings(SGuiUtils.getLabelName(moTextEarningCode.getToolTipText()), 10, 0); moTextEarningCode.setFieldButton(jbPickEarning); moTextEarningName.setTextSettings(SGuiUtils.getLabelName(moTextEarningName.getToolTipText()), 100, 0); moKeyEarningOtherPaymentType.setKeySettings(miClient, SGuiUtils.getLabelName(moKeyEarningOtherPaymentType.getToolTipText()), true); moKeyBonusType.setKeySettings(miClient, SGuiUtils.getLabelName(moKeyBonusType.getToolTipText()), true); moKeyEarningLoan_n.setKeySettings(miClient, SGuiUtils.getLabelName(jlEarningLoan_n), true); moCompEarningValue.setCompoundFieldSettings(miClient); moCompEarningValue.getField().setDecimalSettings(SGuiUtils.getLabelName(jlEarningValue), SGuiConsts.GUI_TYPE_DEC_QTY, false); // yes!, is NOT mandatory! moCompEarningAuxValue.setCompoundFieldSettings(miClient); moCompEarningAuxValue.getField().setDecimalSettings(SGuiUtils.getLabelName(jlEarningAuxValue), SGuiConsts.GUI_TYPE_DEC_AMT, false); moCurEarningAuxAmount1.setCompoundFieldSettings(miClient); moCurEarningAuxAmount1.getField().setDecimalSettings(SGuiUtils.getLabelName(jlEarningAuxAmount1), SGuiConsts.GUI_TYPE_DEC_AMT, false); moCurEarningAuxAmount2.setCompoundFieldSettings(miClient); moCurEarningAuxAmount2.getField().setDecimalSettings(SGuiUtils.getLabelName(jlEarningAuxAmount2), SGuiConsts.GUI_TYPE_DEC_AMT, false); moTextDeductionCode.setTextSettings(SGuiUtils.getLabelName(moTextDeductionCode.getToolTipText()), 10, 0); moTextDeductionCode.setFieldButton(jbPickDeduction); moTextDeductionName.setTextSettings(SGuiUtils.getLabelName(moTextDeductionName.getToolTipText()), 100, 0); moKeyDeductionLoan_n.setKeySettings(miClient, SGuiUtils.getLabelName(jlDeductionLoan_n), true); moCompDeductionValue.setCompoundFieldSettings(miClient); moCompDeductionValue.getField().setDecimalSettings(SGuiUtils.getLabelName(jlDeductionValue), SGuiConsts.GUI_TYPE_DEC_QTY, false); // yes!, is NOT mandatory! moCurEarningsTotal.setCompoundFieldSettings(miClient); moCurEarningsTotal.getField().setDecimalSettings(SGuiUtils.getLabelName(jlEarningsTotal), SGuiConsts.GUI_TYPE_DEC_AMT, false); moCurDeductionsTotal.setCompoundFieldSettings(miClient); moCurDeductionsTotal.getField().setDecimalSettings(SGuiUtils.getLabelName(jlDeductionsTotal), SGuiConsts.GUI_TYPE_DEC_AMT, false); moCurNetTotal.setCompoundFieldSettings(miClient); moCurNetTotal.getField().setDecimalSettings(SGuiUtils.getLabelName(jlNetTotal), SGuiConsts.GUI_TYPE_DEC_AMT, false); moFields.addField(moTextEarningCode); moFields.addField(moTextEarningName); moFields.addField(moKeyEarningOtherPaymentType); moFields.addField(moKeyBonusType); moFields.addField(moKeyEarningLoan_n); moFields.addField(moCompEarningValue.getField()); moFields.addField(moCompEarningAuxValue.getField()); moFields.addField(moCurEarningAuxAmount1.getField()); moFields.addField(moCurEarningAuxAmount2.getField()); moFields.addField(moTextDeductionCode); moFields.addField(moTextDeductionName); moFields.addField(moKeyDeductionLoan_n); moFields.addField(moCompDeductionValue.getField()); moFields.setFormButton(jbSave); // prevent from sending focus to next field when key 'enter' pressed: moTextEarningCode.setNextField(null); moTextDeductionCode.setNextField(null); resetFieldsEarning(); resetFieldsDeduction(); mbEditable = true; setEnableFields(mbEditable); moGridReceiptEarnings = new SGridPaneForm(miClient, SModConsts.HRSX_PAY_REC_EAR, SLibConsts.UNDEFINED, "Percepciones") { @Override public void initGrid() { setRowButtonsEnabled(false, true, true); } @Override public ArrayList<SGridColumnForm> createGridColumns() { SGridColumnForm columnForm; ArrayList<SGridColumnForm> gridColumnsForm = new ArrayList<>(); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_INT_1B, " gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_NAME_CAT_S, "Percepción", 125)); columnForm = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_QTY, "Cantidad", 55); columnForm.setEditable(mbEditable); gridColumnsForm.add(columnForm); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_UNT, "Unidad", 45)); columnForm = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Monto unitario $", 80); columnForm.setEditable(mbEditable); gridColumnsForm.add(columnForm); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Monto $", 80)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_QTY, "Cantidad ajustada", 55)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_UNT, "Unidad", 45)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Parte exenta $", 80)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Parte gravada $", 80)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_NAME_CAT_M, "Crédito/préstamo")); return gridColumnsForm; } @Override public void actionRowEdit() { if (jbRowEdit.isEnabled()) { try { SHrsReceiptEarning hrsReceiptEarning = (SHrsReceiptEarning) moGridReceiptEarnings.getSelectedGridRow(); SDialogPayrollEarning dlgPayrollEarning = new SDialogPayrollEarning(miClient, hrsReceiptEarning.clone(), "Percepción"); dlgPayrollEarning.setVisible(true); if (dlgPayrollEarning.getFormResult() == SGuiConsts.FORM_RESULT_OK) { refreshReceiptMovements(); } } catch (Exception e) { SLibUtils.printException(this, e); } } } @Override public void actionRowDelete() { if (jbRowDelete.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { int moveId = 0; boolean remove = false; SHrsReceiptEarning hrsReceiptEarning = (SHrsReceiptEarning) moGridReceiptEarnings.getSelectedGridRow(); if (hrsReceiptEarning.getPayrollReceiptEarning().isSystem()) { miClient.showMsgBoxInformation(SDbConsts.MSG_REG_ + hrsReceiptEarning.getEarning().getName() + SDbConsts.MSG_REG_IS_SYSTEM + "\n" + "Se debe eliminar mediante la eliminación del consumo de incidencia respectivo."); } else { for (SHrsReceiptEarning hrsReceiptEarningToRemove : moHrsReceipt.getHrsReceiptEarnings()) { if (SLibUtils.compareKeys(hrsReceiptEarningToRemove.getRowPrimaryKey(), hrsReceiptEarning.getRowPrimaryKey())) { remove = true; moveId = hrsReceiptEarningToRemove.getPayrollReceiptEarning().getPkMoveId(); break; } } if (remove) { moHrsReceipt.removeHrsReceiptEarning(moveId); refreshReceiptMovements(); } } } } } }; moGridReceiptEarnings.setForm(null); moGridReceiptEarnings.setPaneFormOwner(this); jpEarnings.add(moGridReceiptEarnings, BorderLayout.CENTER); moGridReceiptDeductions = new SGridPaneForm(miClient, SModConsts.HRSX_PAY_REC_DED, SLibConsts.UNDEFINED, "Deducciones") { @Override public void initGrid() { setRowButtonsEnabled(false, false, true); } @Override public ArrayList<SGridColumnForm> createGridColumns() { SGridColumnForm columnForm; ArrayList<SGridColumnForm> gridColumnsForm = new ArrayList<>(); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_INT_1B, " gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_NAME_CAT_S, "Deducción", 125)); columnForm = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_QTY, "Cantidad", 55); columnForm.setEditable(mbEditable); gridColumnsForm.add(columnForm); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_UNT, "Unidad", 45)); columnForm = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Monto unitario $", 80); columnForm.setEditable(mbEditable); gridColumnsForm.add(columnForm); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_AMT, "Monto $", 80)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_NAME_CAT_M, "Crédito/préstamo")); moGridReceiptDeductions.getTable().getDefaultEditor(Double.class).addCellEditorListener(SDialogPayrollReceipt.this); return gridColumnsForm; } @Override public void actionRowDelete() { if (jbRowDelete.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { int moveId = 0; boolean remove = false; SHrsReceiptDeduction hrsReceiptDeduction = (SHrsReceiptDeduction) moGridReceiptDeductions.getSelectedGridRow(); for (SHrsReceiptDeduction hrsReceiptDeductionToRemove : moHrsReceipt.getHrsReceiptDeductions()) { if (SLibUtils.compareKeys(hrsReceiptDeductionToRemove.getRowPrimaryKey(), hrsReceiptDeduction.getRowPrimaryKey())) { remove = true; moveId = hrsReceiptDeductionToRemove.getPayrollReceiptDeduction().getPkMoveId(); break; } } if (remove) { moHrsReceipt.removeHrsReceiptDeduction(moveId); refreshReceiptMovements(); } } } } }; moGridReceiptDeductions.setForm(null); moGridReceiptDeductions.setPaneFormOwner(this); jpDeductions.add(moGridReceiptDeductions, BorderLayout.CENTER); moGridAbsenceConsumptions = new SGridPaneForm(miClient, SModConsts.HRS_ABS_CNS, SLibConsts.UNDEFINED, "Consumo incidencias") { @Override public void initGrid() { setRowButtonsEnabled(true, false, true); } @Override public ArrayList<SGridColumnForm> createGridColumns() { ArrayList<SGridColumnForm> gridColumnsForm = new ArrayList<>(); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Clase incidencia")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Tipo incidencia")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_CAT, "Folio")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Inicial incidencia")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Final incidencia")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_QTY, "Días efectivos incidencia")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Inicial consumo")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Final consumo")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_QTY, "Días efectivos consumo")); return gridColumnsForm; } @Override public void actionRowNew() { SDialogPayrollReceiptAbsence dlgAbsence = new SDialogPayrollReceiptAbsence(miClient, "Consumo de incidencias"); dlgAbsence.setValue(SModConsts.HRS_PAY_RCP, moHrsReceipt); dlgAbsence.setFormVisible(true); if (dlgAbsence.getFormResult() == SGuiConsts.FORM_RESULT_OK) { populateAbsenceConsumption(); refreshReceiptMovements(); } } @Override public void actionRowDelete() { if (jbRowDelete.isEnabled()) { try { if (jtTable.getSelectedRowCount() == 0) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROWS); } else if (miClient.showMsgBoxConfirm(SGridConsts.MSG_CONFIRM_REG_DEL) == JOptionPane.YES_OPTION) { SGridRow[] gridRows = getSelectedGridRows(); for (int i = 0; i < gridRows.length; i++) { SGridRow gridRow = gridRows[i]; SDbAbsenceConsumption absenceConsumption = (SDbAbsenceConsumption) gridRow; moHrsReceipt.updateHrsReceiptEarningAbsence(absenceConsumption, false); moModel.getGridRows().remove(moModel.getGridRows().indexOf(gridRow)); populateAbsenceConsumption(); refreshReceiptMovements(); } } } catch (Exception e) { SLibUtils.showException(this, e); } } } }; moGridAbsenceConsumptions.setForm(null); moGridAbsenceConsumptions.setPaneFormOwner(null); jpAbsenceConsumption.add(moGridAbsenceConsumptions, BorderLayout.CENTER); reloadCatalogues(); addAllListeners(); } private void renderEmployee() { SDbEmployee employee = moHrsReceipt.getHrsEmployee().getEmployee(); moTextName.setValue(employee.getXtaEmployeeName()); moTextNumber.setValue(employee.getNumber()); moTextId.setValue("" + employee.getPkEmployeeId()); moTextFiscalId.setValue(employee.getXtaEmployeeRfc()); moTextAlternativeId.setValue(employee.getXtaEmployeeCurp()); moTextSocialSecurityNumber.setValue(employee.getSocialSecurityNumber()); moTextPaymentType.setValue(miClient.getSession().readField(SModConsts.HRSS_TP_PAY, new int[] { employee.getFkPaymentTypeId() }, SDbRegistry.FIELD_NAME)); moDecSalary.setValue(employee.getSalary()); moDecWage.setValue(employee.getWage()); moDecSalarySscBase.setValue(employee.getSalarySscBase()); moTextDateBirth.setValue(SLibUtils.DateFormatDate.format(employee.getDateBirth())); moTextDateBenefits.setValue(SLibUtils.DateFormatDate.format(employee.getDateBenefits())); moTextDateLastHire.setValue(SLibUtils.DateFormatDate.format(employee.getDateLastHire())); moTextDateLastDismissal_n.setValue(employee.getDateLastDismissal_n() != null ? SLibUtils.DateFormatDate.format(employee.getDateLastDismissal_n()) : ""); moTextSalaryType.setValue(miClient.getSession().readField(SModConsts.HRSS_TP_SAL, new int[] { employee.getFkSalaryTypeId() }, SDbRegistry.FIELD_NAME)); moTextEmployeeType.setValue(miClient.getSession().readField(SModConsts.HRSU_TP_EMP, new int[] { employee.getFkEmployeeTypeId() }, SDbRegistry.FIELD_NAME)); moTextWorkerType.setValue(miClient.getSession().readField(SModConsts.HRSU_TP_WRK, new int[] { employee.getFkWorkerTypeId() }, SDbRegistry.FIELD_NAME)); moTextDepartament.setValue(miClient.getSession().readField(SModConsts.HRSU_DEP, new int[] { employee.getFkDepartmentId() }, SDbRegistry.FIELD_NAME)); moTextPosition.setValue(miClient.getSession().readField(SModConsts.HRSU_POS, new int[] { employee.getFkPositionId() }, SDbRegistry.FIELD_NAME)); moTextShift.setValue(miClient.getSession().readField(SModConsts.HRSU_SHT, new int[] { employee.getFkShiftId() }, SDbRegistry.FIELD_NAME)); moTextRecruitmentSchemeType.setValue(miClient.getSession().readField(SModConsts.HRSS_TP_REC_SCHE, new int[] { employee.getFkRecruitmentSchemeTypeId()}, SDbRegistry.FIELD_NAME)); moIntWorkingHoursDay.setValue(employee.getWorkingHoursDay()); } private SDbPayrollReceiptEarning createPayrollReceipEarning(SHrsReceipt hrsReceipt, SHrsEmployeeDays hrsEmployeeDays) { double unitsAlleged; double amountUnitAlleged; int[] loanKey = moKeyEarningLoan_n.getSelectedIndex() <= 0 ? new int[] { 0, 0 } : moKeyEarningLoan_n.getValue(); if (moHrsBenefit == null) { if (moEarning.isBasedOnUnits()) { unitsAlleged = moCompEarningValue.getField().getValue(); amountUnitAlleged = 0; } else { unitsAlleged = 1; amountUnitAlleged = moCompEarningValue.getField().getValue(); } } else { if (moEarning.isBasedOnUnits()) { unitsAlleged = moHrsBenefit.getValuePayedReceipt(); amountUnitAlleged = 0; } else { unitsAlleged = 1; amountUnitAlleged = moHrsBenefit.getAmountPayedReceipt(); } } SDbPayrollReceiptEarning earning = hrsReceipt.getHrsPayroll().createPayrollReceiptEarning( hrsReceipt, moEarning, hrsEmployeeDays, moHrsBenefit, unitsAlleged, amountUnitAlleged, false, loanKey[0], loanKey[1], moGridReceiptEarnings.getTable().getRowCount() + 1); // consider specialized inputs: earning.setFkOtherPaymentTypeId(moKeyEarningOtherPaymentType.getValue()[0]); earning.setFkBonusId(!moKeyBonusType.isEnabled() ? 1 : moKeyBonusType.getValue()[0]); earning.setAuxiliarValue(!moCompEarningAuxValue.isEnabled() ? 0 : moCompEarningAuxValue.getField().getValue()); earning.setAuxiliarAmount1(!moCurEarningAuxAmount1.isEnabled() ? 0 : moCurEarningAuxAmount1.getField().getValue()); earning.setAuxiliarAmount2(!moCurEarningAuxAmount2.isEnabled() ? 0 : moCurEarningAuxAmount2.getField().getValue()); return earning; } private SDbPayrollReceiptDeduction createPayrollReceipDeduction(SHrsReceipt hrsReceipt) { double unitsAlleged; double amountUnitAlleged; int[] loanKey = moKeyDeductionLoan_n.getSelectedIndex() <= 0 ? new int[] { 0, 0 } : moKeyDeductionLoan_n.getValue(); if (moDeduction.isBasedOnUnits()) { unitsAlleged = moCompDeductionValue.getField().getValue(); amountUnitAlleged = 0; } else { unitsAlleged = 1; amountUnitAlleged = moCompDeductionValue.getField().getValue(); } SDbPayrollReceiptDeduction deduction = hrsReceipt.getHrsPayroll().createPayrollReceiptDeduction( hrsReceipt, moDeduction, unitsAlleged, amountUnitAlleged, false, loanKey[0], loanKey[1], moGridReceiptDeductions.getTable().getRowCount() + 1); return deduction; } private void createBenefit(final SDbEarning earning) throws Exception { int benefitType = 0; Date dateCutOff = null; SDbBenefitTable benefitTable = null; SDbBenefitTable benefitTableAux = null; SHrsBenefitParams benefitParams = null; benefitTable = SHrsUtils.getBenefitTableByEarning(miClient.getSession(), earning.getPkEarningId(), moHrsReceipt.getHrsPayroll().getPayroll().getFkPaymentTypeId(), moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd()); benefitType = benefitTable.getFkBenefitTypeId(); if (benefitType == SLibConsts.UNDEFINED) { throw new Exception("No se encontró ninguna prestación para el tipo de prestación definido en la percepción '" + earning.getName() + "'."); } else if (earning.getFkBenefitTypeId() != benefitType) { throw new Exception("El tipo de prestación de la percepción '" + earning.getName() + "', es diferente al tipo de prestación de la prestación '" + benefitTable.getName() + "'."); } // check if benefit is vacation bonus: if (benefitType == SModSysConsts.HRSS_TP_BEN_VAC_BON) { int tableAuxId = SHrsUtils.getRecentBenefitTable(miClient.getSession(), SModSysConsts.HRSS_TP_BEN_VAC, moHrsReceipt.getHrsPayroll().getPayroll().getFkPaymentTypeId(), moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd()); benefitTableAux = moHrsReceipt.getHrsPayroll().getBenefitTable(tableAuxId); if (benefitTableAux == null) { throw new Exception("No se encontró ninguna tabla para la prestación 'Vacaciones' que es requerida para el pago de la prestación 'Prima Vacacional'."); } } if (!moHrsReceipt.getHrsEmployee().getEmployee().isActive()) { dateCutOff = moHrsReceipt.getHrsEmployee().getEmployee().getDateLastDismissal_n(); if (benefitType != SModSysConsts.HRSS_TP_BEN_ANN_BON && !SLibTimeUtils.isBelongingToPeriod(dateCutOff, moHrsReceipt.getHrsPayroll().getPayroll().getDateStart(), moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd())) { dateCutOff = moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd(); } } else if (benefitType == SModSysConsts.HRSS_TP_BEN_ANN_BON) { dateCutOff = SLibTimeUtils.getEndOfYear(moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd()); } else { dateCutOff = moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd(); } // Create benefit params: benefitParams = new SHrsBenefitParams(earning, benefitTable, benefitTableAux, moHrsReceipt, dateCutOff); SDialogPayrollBenefit dlgBenefit = new SDialogPayrollBenefit(miClient, benefitType, "Agregar prestación"); dlgBenefit.setValue(SGuiConsts.PARAM_ROWS, benefitParams); dlgBenefit.setVisible(true); if (dlgBenefit.getFormResult() == SGuiConsts.FORM_RESULT_OK) { moHrsBenefit = (SHrsBenefit) dlgBenefit.getValue(SGuiConsts.PARAM_ROWS); if (moEarning.isBasedOnUnits()) { moCompEarningValue.getField().setValue(moHrsBenefit.getValuePayedReceipt()); } else { moCompEarningValue.getField().setValue(moHrsBenefit.getAmountPayedReceipt()); } actionAddEarning(); } } private void computeTotal() { double earningTotal = 0; double deductionTotal = 0; for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) { earningTotal += hrsReceiptEarning.getPayrollReceiptEarning().getAmount_r(); } for (SHrsReceiptDeduction hrsReceiptDeduction : moHrsReceipt.getHrsReceiptDeductions()) { deductionTotal += hrsReceiptDeduction.getPayrollReceiptDeduction().getAmount_r(); } moCurEarningsTotal.getField().setValue(earningTotal); moCurDeductionsTotal.getField().setValue(deductionTotal); moCurNetTotal.getField().setValue(earningTotal - deductionTotal); } private void setEnableFields(boolean enable) { moTextEarningCode.setEnabled(enable); jbPickEarning.setEnabled(enable); moCompEarningValue.setEditable(enable); jbAddEarning.setEnabled(enable); moKeyEarningLoan_n.setEnabled(enable && moKeyEarningLoan_n.getItemCount() > 0); if (!enable) { moKeyEarningOtherPaymentType.setEnabled(false); moKeyBonusType.setEnabled(false); jlEarningAuxValue.setEnabled(false); moCompEarningAuxValue.setEnabled(false); jlEarningAuxAmount1.setEnabled(false); jlEarningAuxAmount1Hint.setEnabled(false); moCurEarningAuxAmount1.setEnabled(false); jlEarningAuxAmount2.setEnabled(false); jlEarningAuxAmount2Hint.setEnabled(false); moCurEarningAuxAmount2.setEnabled(false); } moTextDeductionCode.setEnabled(enable); jbPickDeduction.setEnabled(enable); moCompDeductionValue.setEditable(enable); jbAddDeduction.setEnabled(enable); moKeyDeductionLoan_n.setEnabled(enable && moKeyDeductionLoan_n.getItemCount() > 0); jbSave.setEnabled(enable); } private void resetFieldsEarningAux() { jlEarningAuxValue.setText(LABEL_AUX_VAL + ":"); jlEarningAuxValue.setEnabled(false); jlEarningAuxValueHint.setToolTipText(null); jlEarningAuxValueHint.setEnabled(false); moCompEarningAuxValue.setEnabled(false); moCompEarningAuxValue.getField().setMandatory(false); moCompEarningAuxValue.setCompoundText(""); moCompEarningAuxValue.getField().setDecimalFormat(SLibUtils.DecimalFormatInteger); moCompEarningAuxValue.getField().setMinDouble(0); moCompEarningAuxValue.getField().setMaxDouble(Double.MAX_VALUE); moCompEarningAuxValue.getField().resetField(); jlEarningAuxAmount1.setText(LABEL_AUX_AMT + ":"); jlEarningAuxAmount1.setEnabled(false); jlEarningAuxAmount1Hint.setToolTipText(null); jlEarningAuxAmount1Hint.setEnabled(false); moCurEarningAuxAmount1.setEnabled(false); moCurEarningAuxAmount1.getField().setMandatory(false); moCurEarningAuxAmount1.getField().resetField(); jlEarningAuxAmount2.setText(LABEL_AUX_AMT + ":"); jlEarningAuxAmount2.setEnabled(false); jlEarningAuxAmount2Hint.setToolTipText(null); jlEarningAuxAmount2Hint.setEnabled(false); moCurEarningAuxAmount2.setEnabled(false); moCurEarningAuxAmount2.getField().setMandatory(false); moCurEarningAuxAmount2.getField().resetField(); } private void resetFieldsEarning() { moEarning = null; msOriginalEarningCode = ""; moTextEarningCode.resetField(); moTextEarningName.resetField(); moCompEarningValue.getField().resetField(); moCompEarningValue.setCompoundText(""); moKeyEarningLoan_n.setEnabled(false); moKeyEarningLoan_n.removeAllItems(); // resetting of specialized fields related to other payments: moKeyEarningOtherPaymentType.setEnabled(false); moKeyEarningOtherPaymentType.removeItemListener(this); // prevent from triggering unwished item-state-changed event moKeyEarningOtherPaymentType.resetField(); // will not trigger an item-state-changed event itemStateChangedKeyEarningOtherPayment(); // force triggering an item-state-changed event moKeyEarningOtherPaymentType.addItemListener(this); // resetting of specialized fields related to other payments: moKeyBonusType.setEnabled(false); moKeyBonusType.removeItemListener(this); // prevent from triggering unwished item-state-changed event moKeyBonusType.resetField(); // will not trigger an item-state-changed event moKeyBonusType.addItemListener(this); } private void resetFieldsDeduction() { moDeduction = null; msOriginalDeductionCode = ""; moTextDeductionCode.resetField(); moTextDeductionName.resetField(); moCompDeductionValue.getField().resetField(); moCompDeductionValue.setCompoundText(""); moKeyDeductionLoan_n.setEnabled(false); moKeyDeductionLoan_n.removeAllItems(); } private void prepareFocusFieldsEarning() { moCompEarningValue.getField().setNextButton(null); moCompEarningAuxValue.getField().setNextButton(null); moCurEarningAuxAmount1.getField().setNextButton(null); moCurEarningAuxAmount2.getField().setNextButton(null); if (moCurEarningAuxAmount2.isEnabled()) { // field rarely used; preferable disabling it when not used moCurEarningAuxAmount2.getField().setNextButton(jbAddEarning); } else if (moCurEarningAuxAmount1.isEnabled()) { // field rarely used; preferable disabling it when not used moCurEarningAuxAmount1.getField().setNextButton(jbAddEarning); } else if (moCompEarningAuxValue.isEnabled()) { // field rarely used; preferable disabling it when not used moCompEarningAuxValue.getField().setNextButton(jbAddEarning); } else { moCompEarningValue.getField().setNextButton(jbAddEarning); } } private void prepareFocusFieldsDeduction() { moCompDeductionValue.getField().setNextButton(jbAddDeduction); } private void addHrsReceiptEarning() { if (moEarning != null) { SHrsEmployeeDays hrsEmployeeDays = moHrsReceipt.getHrsEmployee().createEmployeeDays(); SHrsReceiptEarning hrsReceiptEarning = new SHrsReceiptEarning(); hrsReceiptEarning.setHrsReceipt(moHrsReceipt); hrsReceiptEarning.setEarning(moEarning); hrsReceiptEarning.setPayrollReceiptEarning(createPayrollReceipEarning(moHrsReceipt, hrsEmployeeDays)); try { if (moKeyEarningLoan_n.isEnabled() && moKeyEarningLoan_n.getSelectedIndex() > 0) { SDbLoan loan = moHrsReceipt.getHrsEmployee().getLoan(moKeyEarningLoan_n.getValue()[1]); hrsReceiptEarning.getPayrollReceiptEarning().setUserEdited(true); hrsReceiptEarning.getPayrollReceiptEarning().setFkLoanEmployeeId_n(moKeyEarningLoan_n.getValue()[0]); hrsReceiptEarning.getPayrollReceiptEarning().setFkLoanLoanId_n(moKeyEarningLoan_n.getValue()[1]); hrsReceiptEarning.getPayrollReceiptEarning().setFkLoanTypeId_n(loan.getFkLoanTypeId()); } moHrsReceipt.addHrsReceiptEarning(hrsReceiptEarning); populateEarnings(); populateDeductions(); } catch (Exception e) { SLibUtils.printException(this, e); } } } private void addHrsReceiptDeduction() { if (moDeduction != null) { SHrsReceiptDeduction hrsReceiptDeduction = new SHrsReceiptDeduction(); hrsReceiptDeduction.setHrsReceipt(moHrsReceipt); hrsReceiptDeduction.setDeduction(moDeduction); hrsReceiptDeduction.setPayrollReceiptDeduction(createPayrollReceipDeduction(moHrsReceipt)); try { if (moKeyDeductionLoan_n.isEnabled() && moKeyDeductionLoan_n.getSelectedIndex() > 0) { SDbLoan loan = moHrsReceipt.getHrsEmployee().getLoan(moKeyDeductionLoan_n.getValue()[1]); hrsReceiptDeduction.getPayrollReceiptDeduction().setUserEdited(true); hrsReceiptDeduction.getPayrollReceiptDeduction().setFkLoanEmployeeId_n(moKeyDeductionLoan_n.getValue()[0]); hrsReceiptDeduction.getPayrollReceiptDeduction().setFkLoanLoanId_n(moKeyDeductionLoan_n.getValue()[1]); hrsReceiptDeduction.getPayrollReceiptDeduction().setFkLoanTypeId_n(loan.getFkLoanTypeId()); } moHrsReceipt.addHrsReceiptDeduction(hrsReceiptDeduction); populateDeductions(); } catch (Exception e) { SLibUtils.printException(this, e); } } } private void refreshReceiptMovements() { populateEarnings(); populateDeductions(); } private void populateEarnings() { Vector<SGridRow> rows = new Vector<>(); moGridReceiptEarnings.setRowButtonsEnabled(false, mbEditable, mbEditable); for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) { SHrsReceiptEarning hrsReceiptEarningNew = new SHrsReceiptEarning(); hrsReceiptEarningNew.setHrsReceipt(moHrsReceipt); hrsReceiptEarningNew.setEarning(hrsReceiptEarning.getEarning()); hrsReceiptEarningNew.setPayrollReceiptEarning(hrsReceiptEarning.getPayrollReceiptEarning()); rows.add(hrsReceiptEarningNew); } moGridReceiptEarnings.populateGrid(rows); moGridReceiptEarnings.getTable().getDefaultEditor(Double.class).addCellEditorListener(this); computeTotal(); } private void populateDeductions() { Vector<SGridRow> rows = new Vector<>(); moGridReceiptDeductions.setRowButtonsEnabled(false, false, mbEditable); for (SHrsReceiptDeduction hrsReceiptDeduction : moHrsReceipt.getHrsReceiptDeductions()) { SHrsReceiptDeduction hrsReceiptDeductionNew = new SHrsReceiptDeduction(); hrsReceiptDeductionNew.setHrsReceipt(moHrsReceipt); hrsReceiptDeductionNew.setDeduction(hrsReceiptDeduction.getDeduction()); hrsReceiptDeductionNew.setPayrollReceiptDeduction(hrsReceiptDeduction.getPayrollReceiptDeduction()); rows.add(hrsReceiptDeductionNew); } moGridReceiptDeductions.populateGrid(rows); moGridReceiptDeductions.getTable().getDefaultEditor(Double.class).addCellEditorListener(this); computeTotal(); } private void populateAbsenceConsumption() { Vector<SGridRow> rows = new Vector<>(); moGridAbsenceConsumptions.setRowButtonsEnabled(mbEditable, false, mbEditable); for (SDbAbsenceConsumption absenceConsumption : moHrsReceipt.getAbsenceConsumptions()) { SDbAbsence absence = (SDbAbsence) miClient.getSession().readRegistry(SModConsts.HRS_ABS, new int[] { absenceConsumption.getPkEmployeeId(), absenceConsumption.getPkAbsenceId() }); absenceConsumption.setAuxNumber(absence.getNumber()); absenceConsumption.setAuxDateStart(absence.getDateStart()); absenceConsumption.setAuxDateEnd(absence.getDateEnd()); absenceConsumption.setAuxEffectiveDays(absence.getEffectiveDays()); rows.add(absenceConsumption); } moGridAbsenceConsumptions.populateGrid(rows); moGridAbsenceConsumptions.setSelectedGridRow(0); } private void updateReceipt() { for (SGridRow row : moGridReceiptEarnings.getModel().getGridRows()) { SHrsReceiptEarning hrsReceiptEarningRow = (SHrsReceiptEarning) row; for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) { if (SLibUtils.compareKeys(hrsReceiptEarning.getRowPrimaryKey(), hrsReceiptEarningRow.getRowPrimaryKey())) { if (!hrsReceiptEarning.getPayrollReceiptEarning().isAutomatic() && hrsReceiptEarningRow.getPayrollReceiptEarning().getUnits() == 0) { moHrsReceipt.removeHrsReceiptEarning(hrsReceiptEarning.getPayrollReceiptEarning().getPkMoveId()); break; } } } } for (SGridRow row : moGridReceiptDeductions.getModel().getGridRows()) { SHrsReceiptDeduction hrsReceiptDeductionRow = (SHrsReceiptDeduction) row; for (SHrsReceiptDeduction hrsReceiptDeduction : moHrsReceipt.getHrsReceiptDeductions()) { if (SLibUtils.compareKeys(hrsReceiptDeduction.getRowPrimaryKey(), hrsReceiptDeductionRow.getRowPrimaryKey())) { if (!hrsReceiptDeduction.getPayrollReceiptDeduction().isAutomatic() && hrsReceiptDeductionRow.getPayrollReceiptDeduction().getAmountUnitary() == 0) { moHrsReceipt.removeHrsReceiptDeduction(hrsReceiptDeduction.getPayrollReceiptDeduction().getPkMoveId()); break; } } } } } private void actionLoadEarning(final boolean focusEventRaised, final boolean actionEventRaised) { try { if (moTextEarningCode.getValue().isEmpty()) { if (focusEventRaised || actionEventRaised) { resetFieldsEarning(); } if (actionEventRaised) { moCompEarningValue.getField().getComponent().requestFocusInWindow(); } } else if (moEarning == null || !moEarning.getCode().equals(moTextEarningCode.getValue())) { // identify earning: moEarning = null; msOriginalEarningCode = moTextEarningCode.getValue(); for (SDbEarning earning : moEarnigsMap.values()) { if (earning.getCode().equals(moTextEarningCode.getValue())) { moEarning = earning; break; } } // process earning, if any: if (moEarning == null) { String code = moTextEarningCode.getValue(); miClient.showMsgBoxWarning("No se encontró ninguna percepción con el código '" + code + "'."); resetFieldsEarning(); moTextEarningCode.setValue(code); moTextEarningCode.requestFocusInWindow(); } else if (moEarning.isAbsence()) { miClient.showMsgBoxWarning("No se puede agregar la percepción '" + moEarning.getName() + " (" + moEarning.getCode() + ")' de forma directa, se debe agregar mediante una incidencia."); moTextEarningCode.requestFocusInWindow(); } else { moTextEarningName.setValue(moEarning.getName()); moCompEarningValue.setCompoundText(moHrsReceipt.getHrsPayroll().getEarningComputationTypesMap().get(moEarning.getFkEarningComputationTypeId())); moCompEarningValue.getField().setEditable(moEarning.areUnitsModifiable() || !moEarning.isBasedOnUnits()); // enable/disable specialized fields: if (moEarning.isLoan()) { miClient.getSession().populateCatalogue(moKeyEarningLoan_n, SModConsts.HRS_LOAN, SLibConsts.UNDEFINED, new SGuiParams(new int[] { moHrsReceipt.getHrsEmployee().getEmployee().getPkEmployeeId(), moEarning.getFkLoanTypeId()})); moKeyEarningLoan_n.setEnabled(true); } else { moKeyEarningLoan_n.setEnabled(false); moKeyEarningLoan_n.removeAllItems(); } // resetting of specialized fields related to other payments: moKeyEarningOtherPaymentType.setEnabled(moEarning.getFkOtherPaymentTypeId() == SModSysConsts.HRSS_TP_OTH_PAY_OTH); moKeyEarningOtherPaymentType.removeItemListener(this); // prevent from triggering unwished item-state-changed event moKeyEarningOtherPaymentType.setValue(new int[] { moEarning.getFkOtherPaymentTypeId() }); // will not trigger an item-state-changed event itemStateChangedKeyEarningOtherPayment(); // force triggering an item-state-changed event moKeyEarningOtherPaymentType.addItemListener(this); // resetting of specialized fields related bonus payments: moKeyBonusType.setEnabled(moEarning.isPayBonus()); moKeyBonusType.removeItemListener(this); // prevent from triggering unwished item-state-changed event if (moEarning.isPayBonus()) { moKeyBonusType.setValue(new int[] { SPayrollBonusUtils.BONUS }); // will not trigger an item-state-changed event } else { moKeyBonusType.setValue(new int[] { moEarning.getFkBonusId_n() }); } // itemStateChangedKeyEarningOtherPayment(); // force triggering an item-state-changed event moKeyBonusType.addItemListener(this); prepareFocusFieldsEarning(); // set focus on next editable field: if (moKeyEarningOtherPaymentType.isEnabled()) { moKeyEarningOtherPaymentType.requestFocusInWindow(); } else if (moKeyEarningLoan_n.isEnabled()) { moKeyEarningLoan_n.requestFocusInWindow(); } else if (moCompEarningValue.getField().isEditable()) { moCompEarningValue.getField().getComponent().requestFocusInWindow(); } else { jbAddEarning.requestFocusInWindow(); } // create benefit, if it is necessary: moHrsBenefit = null; if (moEarning.isBenefit()) { createBenefit(moEarning); } } } } catch (Exception e) { SLibUtils.showException(this, e); } } private void actionLoadDeduction(boolean focusEventRaised, final boolean actionEventRaised) { try { if (moTextDeductionCode.getValue().isEmpty()) { if (focusEventRaised || actionEventRaised) { resetFieldsDeduction(); } if (actionEventRaised) { moCompDeductionValue.getField().getComponent().requestFocusInWindow(); } } else if (moDeduction == null || !moDeduction.getCode().equals(moTextDeductionCode.getValue())) { // identify deduction: moDeduction = null; msOriginalDeductionCode = moTextDeductionCode.getValue(); for (SDbDeduction deduction : moDeductionsMap.values()) { if (deduction.getCode().equals(moTextDeductionCode.getValue())) { moDeduction = deduction; break; } } // process deduction, if any: if (moDeduction == null) { String code = moTextDeductionCode.getValue(); miClient.showMsgBoxWarning("No se encontró ninguna deducción con el código '" + code + "'."); resetFieldsDeduction(); moTextDeductionCode.setValue(code); moTextDeductionCode.requestFocusInWindow(); } else if (moDeduction.isAbsence()) { miClient.showMsgBoxWarning("No se puede agregar la deducción '" + moDeduction.getName() + " (" + moDeduction.getCode() + ")' de forma directa, se debe agregar mediante una incidencia."); moTextDeductionCode.requestFocusInWindow(); } else { moTextDeductionName.setValue(moDeduction.getName()); moCompDeductionValue.setCompoundText(moHrsReceipt.getHrsPayroll().getDeductionComputationTypesMap().get(moDeduction.getFkDeductionComputationTypeId())); moCompDeductionValue.getField().setEditable(moDeduction.areUnitsModifiable() || !moDeduction.isBasedOnUnits()); // enable/disable specialized fields: if (moDeduction.isLoan()) { miClient.getSession().populateCatalogue(moKeyDeductionLoan_n, SModConsts.HRS_LOAN, SLibConsts.UNDEFINED, new SGuiParams(new int[] { moHrsReceipt.getHrsEmployee().getEmployee().getPkEmployeeId(), moDeduction.getFkLoanTypeId()})); moKeyDeductionLoan_n.setEnabled(true); } else { moKeyDeductionLoan_n.setEnabled(false); moKeyDeductionLoan_n.removeAllItems(); } prepareFocusFieldsDeduction(); // set focus on next editable field: if (moKeyDeductionLoan_n.isEnabled()) { moKeyDeductionLoan_n.requestFocusInWindow(); } else if (moCompDeductionValue.getField().isEditable()) { moCompDeductionValue.getField().getComponent().requestFocusInWindow(); } else { jbAddEarning.requestFocusInWindow(); } } } } catch (Exception e) { SLibUtils.printException(this, e); } } private void actionPickEarning() { miClient.getSession().showOptionPicker(SModConsts.HRS_EAR, SLibConsts.UNDEFINED, null, moTextEarningCode); if (!moTextEarningCode.getValue().isEmpty()) { actionLoadEarning(false, false); } } private void actionPickDeduction() { miClient.getSession().showOptionPicker(SModConsts.HRS_DED, SLibConsts.UNDEFINED, null, moTextDeductionCode); if (!moTextDeductionCode.getValue().isEmpty()) { actionLoadDeduction(false, false); } } private void actionAddEarning() { try { if (moEarning == null) { miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + SGuiUtils.getLabelName(moTextEarningCode.getToolTipText()) + "'."); moTextEarningCode.requestFocusInWindow(); } else { SGuiValidation validation = moFields.validateFields(); if (SGuiUtils.computeValidation(miClient, validation)) { // special-case validations: if (moCompEarningValue.getField().getValue() == 0 && miClient.showMsgBoxConfirm(SGuiConsts.MSG_CNF_FIELD_VAL_ + "'" + moCompEarningValue.getField().getFieldName() + "'" + SGuiConsts.MSG_CNF_FIELD_VAL_UNDEF) != JOptionPane.YES_OPTION) { miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + moCompEarningValue.getField().getFieldName() + "'. "); moCompEarningValue.getField().getComponent().requestFocusInWindow(); return; } if (moKeyEarningOtherPaymentType.isEnabled() && moKeyEarningOtherPaymentType.getValue()[0] == SModSysConsts.HRSS_TP_OTH_PAY_NON) { miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_DIF + "'" + SGuiUtils.getLabelName(moKeyEarningOtherPaymentType.getToolTipText()) + "'. "); moKeyEarningOtherPaymentType.requestFocusInWindow(); return; } if (moEarning.isLoan()) { if (moKeyEarningLoan_n.getSelectedIndex() <= 0) { miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + SGuiUtils.getLabelName(jlEarningLoan_n.getText()) + "'. "); moKeyEarningLoan_n.requestFocusInWindow(); return; } } if (moEarning.isBenefit() && moHrsBenefit == null) { miClient.showMsgBoxWarning("Se debe capturar la cantidad o monto de la prestación '" + moEarning.getName() + "'."); moTextEarningCode.requestFocusInWindow(); return; } // validate assimilated employees: SDbEmployee employee = moHrsReceipt.getHrsEmployee().getEmployee(); // convenience variable if (employee.isAssimilable() && moEarning.getFkEarningTypeId() != SModSysConsts.HRSS_TP_EAR_ASS_INC) { // this message is duplicated as is in method validateForm(), please synchronize any change! miClient.showMsgBoxWarning(employee.getXtaEmployeeName() + ", " + "cuyo tipo de régimen de contratación es '" + miClient.getSession().readField(SModConsts.HRSS_TP_REC_SCHE, new int[] { employee.getFkRecruitmentSchemeTypeId() }, SDbRegistry.FIELD_NAME) + "',\n" + "no puede tener percepciones distintas a '" + miClient.getSession().readField(SModConsts.HRSS_TP_EAR, new int[] { SModSysConsts.HRSS_TP_EAR_ASS_INC }, SDbRegistry.FIELD_NAME) + "'."); moTextEarningCode.requestFocusInWindow(); return; } // confirm multiple earnings of the same type: for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) { if (hrsReceiptEarning.getEarning().getPkEarningId() == moEarning.getPkEarningId() && !moEarning.isLoan() && miClient.showMsgBoxConfirm("La percepción '" + moEarning.getName() + "' ya existe en el recibo.\n" + "¿Está seguro que desea agregarla otra vez?") != JOptionPane.YES_OPTION) { moTextEarningCode.requestFocusInWindow(); return; } } // add earning: addHrsReceiptEarning(); resetFieldsEarning(); moTextEarningCode.requestFocusInWindow(); } } } catch (Exception e) { SLibUtils.showException(this, e); } } private void actionAddDeduction() { try { if (moDeduction == null) { miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + SGuiUtils.getLabelName(moTextDeductionCode.getToolTipText()) + "'."); moTextDeductionCode.requestFocusInWindow(); } else { SGuiValidation validation = moFields.validateFields(); if (SGuiUtils.computeValidation(miClient, validation)) { // special-case validations: if (moCompDeductionValue.getField().getValue() == 0 && miClient.showMsgBoxConfirm(SGuiConsts.MSG_CNF_FIELD_VAL_ + "'" + moCompDeductionValue.getField().getFieldName() + "'" + SGuiConsts.MSG_CNF_FIELD_VAL_UNDEF) != JOptionPane.YES_OPTION) { miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + moCompDeductionValue.getField().getFieldName() + "'. "); moCompDeductionValue.getField().getComponent().requestFocusInWindow(); return; } if (moDeduction.isLoan()) { if (moKeyDeductionLoan_n.getSelectedIndex() <= 0) { miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + SGuiUtils.getLabelName(jlDeductionLoan_n.getText()) + "'. "); moKeyDeductionLoan_n.requestFocusInWindow(); return; } else { SDbLoan loan = moHrsReceipt.getHrsEmployee().getLoan(moKeyDeductionLoan_n.getValue()[1]); if (loan.isPlainLoan()) { double loanBalance = SHrsUtils.getLoanBalance(loan, moHrsReceipt, null, null); if (loanBalance <= 0) { miClient.showMsgBoxWarning("El préstamo '" + loan.composeLoanDescription() + "' " + (loanBalance == 0 ? "está saldado" : "tiene un saldo negativo de $" + SLibUtils.getDecimalFormatAmount().format(loanBalance)) + "."); moCompDeductionValue.getField().getComponent().requestFocusInWindow(); return; } else if (moCompDeductionValue.getField().getValue() > loanBalance) { miClient.showMsgBoxWarning(SGuiConsts.ERR_MSG_FIELD_VAL_ + "'" + SGuiUtils.getLabelName(jlDeductionValue.getText()) + "'" + SGuiConsts.ERR_MSG_FIELD_VAL_LESS_EQUAL + "$" + SLibUtils.getDecimalFormatAmount().format(loanBalance) + "."); moCompDeductionValue.getField().getComponent().requestFocusInWindow(); return; } } } } // validate assimilated employees: SDbEmployee employee = moHrsReceipt.getHrsEmployee().getEmployee(); // convenience variable if (employee.isAssimilable() && moDeduction.getFkDeductionTypeId() != SModSysConsts.HRSS_TP_DED_TAX) { // this message is duplicated as is in method validateForm(), please synchronize any change! miClient.showMsgBoxWarning(employee.getXtaEmployeeName() + ", " + "cuyo tipo de régimen de contratación es '" + miClient.getSession().readField(SModConsts.HRSS_TP_REC_SCHE, new int[] { employee.getFkRecruitmentSchemeTypeId() }, SDbRegistry.FIELD_NAME) + "',\n" + "no puede tener deducciones distintas a '" + miClient.getSession().readField(SModConsts.HRSS_TP_DED, new int[] { SModSysConsts.HRSS_TP_DED_TAX }, SDbRegistry.FIELD_NAME) + "'."); moTextDeductionCode.requestFocusInWindow(); return; } // confirm multiple deductions of the same type: for (SHrsReceiptDeduction hrsReceiptDeduction : moHrsReceipt.getHrsReceiptDeductions()) { if (hrsReceiptDeduction.getDeduction().getPkDeductionId() == moDeduction.getPkDeductionId() && !moDeduction.isLoan() && miClient.showMsgBoxConfirm("La deducción '" + moDeduction.getName() + "' ya existe en el recibo.\n" + "¿Está seguro que desea agregarla otra vez?") != JOptionPane.YES_OPTION) { moTextDeductionCode.requestFocusInWindow(); return; } } // add deduction: addHrsReceiptDeduction(); resetFieldsDeduction(); moTextDeductionCode.requestFocusInWindow(); } } } catch (Exception e) { SLibUtils.showException(this, e); } } private void itemStateChangedEarningLoan_n() { if (moKeyEarningLoan_n.getSelectedIndex() <= 0) { moCompEarningValue.getField().resetField(); } } private void itemStateChangedDeductionLoan_n() { if (moKeyDeductionLoan_n.getSelectedIndex() <= 0) { moCompDeductionValue.getField().resetField(); } else { try { SDbLoan loan = moHrsReceipt.getHrsEmployee().getLoan(moKeyDeductionLoan_n.getValue()[1]); moCompDeductionValue.getField().setValue(SHrsUtils.computeLoanAmount(loan, moHrsReceipt, null, null)); } catch (Exception e) { SLibUtils.printException(this, e); } } } private void itemStateChangedKeyEarningOtherPayment() { resetFieldsEarningAux(); if (moKeyEarningOtherPaymentType.getSelectedIndex() > 0) { switch (moKeyEarningOtherPaymentType.getValue()[0]) { case SModSysConsts.HRSS_TP_OTH_PAY_TAX_SUB: jlEarningAuxAmount1.setText(SDbEarning.TAX_SUB_LABEL + ":"); jlEarningAuxAmount1.setEnabled(true); jlEarningAuxAmount1Hint.setToolTipText(SDbEarning.TAX_SUB_HINT); jlEarningAuxAmount1Hint.setEnabled(true); moCurEarningAuxAmount1.setEnabled(true); moCurEarningAuxAmount1.getField().setMandatory(false); // non-mandatory! break; case SModSysConsts.HRSS_TP_OTH_PAY_TAX_BAL: int year = SLibTimeUtils.digestYear(moHrsReceipt.getHrsPayroll().getPayroll().getDateEnd())[0]; jlEarningAuxValue.setText(SDbEarning.OTH_TAX_BAL_LABEL_YEAR + ":*"); jlEarningAuxValue.setEnabled(true); jlEarningAuxValueHint.setToolTipText(SDbEarning.OTH_TAX_BAL_HINT_YEAR); jlEarningAuxValueHint.setEnabled(true); moCompEarningAuxValue.setEnabled(true); moCompEarningAuxValue.getField().setMandatory(true); // mandatory! moCompEarningAuxValue.setCompoundText(""); moCompEarningAuxValue.getField().setDecimalFormat(SLibUtils.DecimalFormatCalendarYear); moCompEarningAuxValue.getField().setMinDouble(year - 1); moCompEarningAuxValue.getField().setMaxDouble(year); moCompEarningAuxValue.getField().setValue((double) year); jlEarningAuxAmount1.setText(SDbEarning.OTH_TAX_BAL_LABEL_BAL + ":*"); jlEarningAuxAmount1.setEnabled(true); jlEarningAuxAmount1Hint.setToolTipText(SDbEarning.OTH_TAX_BAL_HINT_BAL); jlEarningAuxAmount1Hint.setEnabled(true); moCurEarningAuxAmount1.setEnabled(true); moCurEarningAuxAmount1.getField().setMandatory(true); // mandatory! jlEarningAuxAmount2.setText(SDbEarning.OTH_TAX_BAL_LABEL_REM_BAL + ":"); jlEarningAuxAmount2.setEnabled(true); jlEarningAuxAmount2Hint.setToolTipText(SDbEarning.OTH_TAX_BAL_HINT_REM_BAL); jlEarningAuxAmount2Hint.setEnabled(true); moCurEarningAuxAmount2.setEnabled(true); moCurEarningAuxAmount2.getField().setMandatory(false); // non-mandatory! break; default: } } prepareFocusFieldsEarning(); } private void processCellEditionEarning() { boolean refresh = false; SHrsReceiptEarning hrsReceiptEarning = (SHrsReceiptEarning) moGridReceiptEarnings.getSelectedGridRow(); if (hrsReceiptEarning != null) { switch (moGridReceiptEarnings.getTable().getSelectedColumn()) { case COL_VAL: if (hrsReceiptEarning.isEditableValueAlleged()) { refresh = true; } else { miClient.showMsgBoxWarning("No se puede modificar la 'Cantidad' de la percepción '" + hrsReceiptEarning.getEarning().getName() + "'."); } break; case COL_AMT_UNT: if (hrsReceiptEarning.isEditableAmountUnitary(hrsReceiptEarning.getAmountBeingEdited())) { refresh = true; } else { miClient.showMsgBoxWarning("No se puede modificar el 'Monto unitario' de la percepción '" + hrsReceiptEarning.getEarning().getName() + "'." + (!hrsReceiptEarning.getEarning().isBenefit() ? "" : "El monto capturado no puede ser menor que " + SLibUtils.getDecimalFormatAmount().format(hrsReceiptEarning.getAmountOriginal()) + ".")); } break; default: } } if (refresh) { try { moHrsReceipt.computeReceipt(); } catch (Exception e) { SLibUtils.showException(this, e); } int row = moGridReceiptEarnings.getTable().getSelectedRow(); refreshReceiptMovements(); moGridReceiptEarnings.setSelectedGridRow(row); } } private void processCellEditionDeduction() { boolean refresh = false; SHrsReceiptDeduction hrsReceiptDeduction = (SHrsReceiptDeduction) moGridReceiptDeductions.getSelectedGridRow(); if (hrsReceiptDeduction != null) { switch (moGridReceiptDeductions.getTable().getSelectedColumn()) { case COL_VAL: if (hrsReceiptDeduction.isEditableValueAlleged()) { refresh = true; } else { miClient.showMsgBoxWarning("No se puede modificar la 'Cantidad' de la deducción '" + hrsReceiptDeduction.getDeduction().getName() + "'."); } break; case COL_AMT_UNT: if (hrsReceiptDeduction.isEditableAmountUnitary(hrsReceiptDeduction.getAmountBeingEdited())) { refresh = true; } else { miClient.showMsgBoxWarning("No se puede modificar el 'Monto unitario' de la deducción '" + hrsReceiptDeduction.getDeduction().getName() + "'." + (!hrsReceiptDeduction.getDeduction().isBenefit() ? "" : "El monto capturado no puede ser menor que " + SLibUtils.getDecimalFormatAmount().format(hrsReceiptDeduction.getAmountOriginal()) + ".")); } break; default: } } if (refresh) { try { moHrsReceipt.computeReceipt(); } catch (Exception e) { SLibUtils.showException(this, e); } int row = moGridReceiptDeductions.getTable().getSelectedRow(); refreshReceiptMovements(); moGridReceiptDeductions.setSelectedGridRow(row); } } @Override public void addAllListeners() { jbPickEarning.addActionListener(this); jbAddEarning.addActionListener(this); jbPickDeduction.addActionListener(this); jbAddDeduction.addActionListener(this); moTextEarningCode.addActionListener(this); moTextDeductionCode.addActionListener(this); moKeyEarningLoan_n.addItemListener(this); moKeyDeductionLoan_n.addItemListener(this); moKeyEarningOtherPaymentType.addItemListener(this); moKeyBonusType.addItemListener(this); moTextEarningCode.addFocusListener(this); moTextDeductionCode.addFocusListener(this); } @Override public void removeAllListeners() { jbPickEarning.removeActionListener(this); jbAddEarning.removeActionListener(this); jbPickDeduction.removeActionListener(this); jbAddDeduction.removeActionListener(this); moTextEarningCode.removeActionListener(this); moTextDeductionCode.removeActionListener(this); moKeyEarningLoan_n.removeItemListener(this); moKeyDeductionLoan_n.removeItemListener(this); moKeyEarningOtherPaymentType.removeItemListener(this); moKeyBonusType.removeItemListener(this); moTextEarningCode.removeFocusListener(this); moTextDeductionCode.removeFocusListener(this); } @Override public void reloadCatalogues() { miClient.getSession().populateCatalogue(moKeyEarningOtherPaymentType, SModConsts.HRSS_TP_OTH_PAY, 0, null); miClient.getSession().populateCatalogue(moKeyBonusType, SModConsts.HRSS_BONUS, 0, null); } @Override public void setRegistry(SDbRegistry registry) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public SDbRegistry getRegistry() throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public SGuiValidation validateForm() { SGuiValidation validation = moFields.validateFields(); if (moHrsReceipt.getHrsPayroll().getPayroll().isPayrollNormal()) { double daysWorked = 0; for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) { if (hrsReceiptEarning.getEarning().isDaysWorked() && !hrsReceiptEarning.getEarning().isAbsence()) { daysWorked += hrsReceiptEarning.getPayrollReceiptEarning().getUnitsAlleged(); } } double daysAbsence = 0; for (SDbAbsenceConsumption absenceConsumption : moHrsReceipt.getAbsenceConsumptions()) { daysAbsence += absenceConsumption.getEffectiveDays(); } SHrsEmployeeDays hrsEmployeeDays = moHrsReceipt.getHrsEmployee().createEmployeeDays(); double maxWorkingDays = hrsEmployeeDays.getWorkingDays(); double daysCovered = daysWorked + daysAbsence; double daysDiff = maxWorkingDays - daysCovered; if (Math.abs(daysDiff) > 0.0001) { String msg = "¡ADVERTENCIA!\n" + "Los días laborables del empleado (" + maxWorkingDays + " " + (maxWorkingDays == 1 ? "día" : "días") + ") no son consistentes con\n" + "los días a pagar (" + daysWorked + " " + (daysWorked == 1 ? "día" : "días") + ")" + (daysAbsence == 0 ? "" : " más los días de incidencias (" + daysAbsence + " " + (daysAbsence == 1 ? "día" : "días") + ")" + "; esto es: " + maxWorkingDays + " " + (maxWorkingDays == 1 ? "día" : "días") + " vs. " + daysCovered + " " + (daysCovered == 1 ? "día" : "días")) + ".\n" + "¡SE PAGARÁ " + Math.abs(daysDiff) + " " + (Math.abs(daysDiff) == 1 ? "DÍA" : "DÍAS") + " DE " + (daysDiff > 0 ? "MENOS" : "MÁS") + " AL EMPLEADO!"; if (miClient.showMsgBoxConfirm(msg + "\n" + SGuiConsts.MSG_CNF_CONT) == JOptionPane.NO_OPTION) { validation.setMessage("Ajustarse a los días laborables del empleado (" + maxWorkingDays + " " + (maxWorkingDays == 1 ? "día" : "días") + ")."); validation.setComponent(moTextEarningCode); } } } SDbEmployee employee = moHrsReceipt.getHrsEmployee().getEmployee(); // convenience variable if (employee.isAssimilable()) { for (SHrsReceiptEarning hrsReceiptEarning : moHrsReceipt.getHrsReceiptEarnings()) { if (hrsReceiptEarning.getEarning().getFkEarningTypeId() != SModSysConsts.HRSS_TP_EAR_ASS_INC) { // this message is duplicated as is in method actionAddEarning(), please synchronize any change! validation.setMessage(employee.getXtaEmployeeName() + ", " + "cuyo tipo de régimen de contratación es '" + miClient.getSession().readField(SModConsts.HRSS_TP_REC_SCHE, new int[] { employee.getFkRecruitmentSchemeTypeId() }, SDbRegistry.FIELD_NAME) + "',\n" + "no puede tener percepciones distintas a '" + miClient.getSession().readField(SModConsts.HRSS_TP_EAR, new int[] { SModSysConsts.HRSS_TP_EAR_ASS_INC }, SDbRegistry.FIELD_NAME) + "'."); validation.setComponent(moTextEarningCode); break; } } if (validation.isValid()) { for (SHrsReceiptDeduction hrsReceiptDeduction : moHrsReceipt.getHrsReceiptDeductions()) { if (hrsReceiptDeduction.getDeduction().getFkDeductionTypeId() != SModSysConsts.HRSS_TP_DED_TAX) { // this message is duplicated as is in method actionAddDeduction(), please synchronize any change! validation.setMessage(employee.getXtaEmployeeName() + ", " + "cuyo tipo de régimen de contratación es '" + miClient.getSession().readField(SModConsts.HRSS_TP_REC_SCHE, new int[] { employee.getFkRecruitmentSchemeTypeId() }, SDbRegistry.FIELD_NAME) + "',\n" + "no puede tener deducciones distintas a '" + miClient.getSession().readField(SModConsts.HRSS_TP_DED, new int[] { SModSysConsts.HRSS_TP_DED_TAX }, SDbRegistry.FIELD_NAME) + "'."); validation.setComponent(moTextEarningCode); break; } } } } return validation; } @Override @SuppressWarnings("unchecked") public void setValue(final int type, final Object value) { switch (type) { case SGuiConsts.PARAM_REQ_PAY: mbEditable = (boolean) value; setEnableFields(mbEditable); break; case SModConsts.HRS_PAY_RCP: moHrsReceipt = (SHrsReceipt) value; renderEmployee(); refreshReceiptMovements(); populateAbsenceConsumption(); break; case SModConsts.HRS_EAR: moEarnigsMap = new HashMap<>(); for (SDbEarning earning : (ArrayList<SDbEarning>) value) { moEarnigsMap.put(earning.getPkEarningId(), earning); } break; case SModConsts.HRS_DED: moDeductionsMap = new HashMap<>(); for (SDbDeduction deduction : (ArrayList<SDbDeduction>) value) { moDeductionsMap.put(deduction.getPkDeductionId(), deduction); } break; default: } } @Override public Object getValue(final int type) { Object value = null; switch (type) { case SModConsts.HRS_PAY_RCP: updateReceipt(); value = moHrsReceipt; break; default: break; } return value; } @Override public void actionSave() { try { if (!mbEditable) { mnFormResult = SGuiConsts.FORM_RESULT_CANCEL; dispose(); } else { updateReceipt(); super.actionSave(); } } catch (Exception e) { SLibUtils.showException(this, e); } } @Override public void notifyRowNew(int gridType, int gridSubtype, int row, SGridRow gridRow) { computeTotal(); } @Override public void notifyRowEdit(int gridType, int gridSubtype, int row, SGridRow gridRow) { computeTotal(); } @Override public void notifyRowDelete(int gridType, int gridSubtype, int row, SGridRow gridRow) { } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) { JButton button = (JButton) e.getSource(); if (button == jbPickEarning) { actionPickEarning(); } else if (button == jbAddEarning) { actionAddEarning(); } else if (button == jbPickDeduction) { actionPickDeduction(); } else if (button == jbAddDeduction) { actionAddDeduction(); } } else if (e.getSource() instanceof SBeanFieldText) { SBeanFieldText field = (SBeanFieldText) e.getSource(); if (field == moTextEarningCode) { actionLoadEarning(false, true); } else if (field == moTextDeductionCode) { actionLoadDeduction(false, true); } } } @Override public void focusGained(FocusEvent e) { if (e.getSource() instanceof SBeanFieldText) { SBeanFieldText field = (SBeanFieldText) e.getSource(); if (field == moTextEarningCode) { msOriginalEarningCode = moTextEarningCode.getValue(); } else if (field == moTextDeductionCode) { msOriginalDeductionCode = moTextDeductionCode.getValue(); } } } @Override public void focusLost(FocusEvent e) { if (e.getSource() instanceof SBeanFieldText) { SBeanFieldText field = (SBeanFieldText) e.getSource(); if (field == moTextEarningCode) { if (!msOriginalEarningCode.equals(moTextEarningCode.getValue())) { actionLoadEarning(true, false); } } else if (field == moTextDeductionCode) { if (!msOriginalDeductionCode.equals(moTextDeductionCode.getValue())) { actionLoadDeduction(true, false); } } } } @Override public void itemStateChanged(ItemEvent e) { if (e.getSource() instanceof SBeanFieldKey && e.getStateChange() == ItemEvent.SELECTED) { SBeanFieldKey field = (SBeanFieldKey) e.getSource(); if (field == moKeyEarningLoan_n) { itemStateChangedEarningLoan_n(); } else if (field == moKeyDeductionLoan_n) { itemStateChangedDeductionLoan_n(); } else if (field == moKeyEarningOtherPaymentType) { itemStateChangedKeyEarningOtherPayment(); } } } @Override public void editingStopped(ChangeEvent e) { if (moGridReceiptEarnings.getTable().getDefaultEditor(Double.class).equals(e.getSource())) { processCellEditionEarning(); } else if (moGridReceiptDeductions.getTable().getDefaultEditor(Double.class).equals(e.getSource())) { processCellEditionDeduction(); } } @Override public void editingCanceled(ChangeEvent e) { } }
package org.openlmis.fulfillment.web; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.openlmis.fulfillment.i18n.MessageKeys.MUST_CONTAIN_VALUE; import static org.openlmis.fulfillment.i18n.MessageKeys.PERMISSIONS_MISSING; import static org.openlmis.fulfillment.i18n.MessageKeys.PERMISSION_MISSING; import static org.openlmis.fulfillment.i18n.MessageKeys.PROOF_OF_DELIVERY_ALREADY_CONFIRMED; import static org.openlmis.fulfillment.service.PermissionService.PODS_MANAGE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRParameter; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperReport; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.openlmis.fulfillment.ProofOfDeliveryDataBuilder; import org.openlmis.fulfillment.domain.Order; import org.openlmis.fulfillment.domain.OrderStatus; import org.openlmis.fulfillment.domain.ProofOfDelivery; import org.openlmis.fulfillment.domain.ProofOfDeliveryStatus; import org.openlmis.fulfillment.domain.Template; import org.openlmis.fulfillment.domain.TemplateParameter; import org.openlmis.fulfillment.repository.OrderRepository; import org.openlmis.fulfillment.repository.ProofOfDeliveryRepository; import org.openlmis.fulfillment.repository.ShipmentRepository; import org.openlmis.fulfillment.repository.TemplateRepository; import org.openlmis.fulfillment.service.PermissionService; import org.openlmis.fulfillment.service.referencedata.PermissionStringDto; import org.openlmis.fulfillment.service.referencedata.PermissionStrings; import org.openlmis.fulfillment.service.stockmanagement.StockEventStockManagementService; import org.openlmis.fulfillment.util.PageImplRepresentation; import org.openlmis.fulfillment.web.stockmanagement.StockEventDto; import org.openlmis.fulfillment.web.util.ProofOfDeliveryDto; import org.openlmis.fulfillment.web.util.StockEventBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import guru.nidi.ramltester.junit.RamlMatchers; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.stream.Collectors; @SuppressWarnings("PMD.TooManyMethods") public class ProofOfDeliveryControllerIntegrationTest extends BaseWebIntegrationTest { private static final String RESOURCE_URL = "/api/proofsOfDelivery"; private static final String ID_URL = RESOURCE_URL + "/{id}"; private static final String PRINT_URL = ID_URL + "/print"; private static final String PRINT_POD = "Print POD"; private static final String CONSISTENCY_REPORT = "Consistency Report"; @MockBean private TemplateRepository templateRepository; @MockBean private ProofOfDeliveryRepository proofOfDeliveryRepository; @MockBean private ShipmentRepository shipmentRepository; @MockBean private OrderRepository orderRepository; @MockBean private StockEventBuilder stockEventBuilder; @MockBean private StockEventStockManagementService stockEventStockManagementService; @SpyBean private PermissionService permissionService; @MockBean private PermissionStrings.Handler permissionStringsHandler; @Value("${service.url}") private String serviceUrl; private ProofOfDelivery proofOfDelivery = new ProofOfDeliveryDataBuilder().build(); @Before public void setUp() { given(proofOfDeliveryRepository.findOne(proofOfDelivery.getId())).willReturn(proofOfDelivery); given(proofOfDeliveryRepository.exists(proofOfDelivery.getId())).willReturn(true); given(proofOfDeliveryRepository.save(any(ProofOfDelivery.class))) .willAnswer(new SaveAnswer<>()); given(proofOfDeliveryRepository.findAll()).willReturn(Lists.newArrayList(proofOfDelivery)); given(proofOfDeliveryRepository.findByShipment(eq(proofOfDelivery.getShipment()))) .willReturn(Lists.newArrayList(proofOfDelivery)); given(shipmentRepository.findOne(proofOfDelivery.getShipment().getId())) .willReturn(proofOfDelivery.getShipment()); given(permissionService.getPermissionStrings(INITIAL_USER_ID)) .willReturn(permissionStringsHandler); given(permissionStringsHandler.get()) .willReturn(ImmutableSet.of(PermissionStringDto.create( PODS_MANAGE, proofOfDelivery.getReceivingFacilityId(), proofOfDelivery.getProgramId() ))); } @Test public void shouldGetAllProofsOfDelivery() { PageImplRepresentation response = restAssured.given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .when() .get(RESOURCE_URL) .then() .statusCode(200) .extract() .as(PageImplRepresentation.class); assertTrue(response.getContent().iterator().hasNext()); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldReturnEmptyListForGetAllProofsOfDeliveryIfUserHasNoRight() { given(permissionStringsHandler.get()).willReturn(Collections.emptySet()); PageImplRepresentation response = restAssured .given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .when() .get(RESOURCE_URL) .then() .statusCode(200) .extract() .as(PageImplRepresentation.class); assertThat(response.getContent().isEmpty(), is(true)); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldFindProofOfDeliveryBasedOnShipment() { PageImplRepresentation response = restAssured.given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(APPLICATION_JSON_VALUE) .queryParam("shipmentId", proofOfDelivery.getShipment().getId()) .when() .get(RESOURCE_URL) .then() .statusCode(200) .extract() .as(PageImplRepresentation.class); assertEquals(2000, response.getSize()); // default size assertEquals(0, response.getNumber()); assertEquals(1, response.getContent().size()); assertEquals(1, response.getNumberOfElements()); assertEquals(1, response.getTotalElements()); assertEquals(1, response.getTotalPages()); assertEquals(createDto(), getPageContent(response, ProofOfDeliveryDto.class).get(0)); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldUpdateProofOfDelivery() { String somebody = "Somebody"; ProofOfDeliveryDto dto = createDto(); dto.setDeliveredBy(somebody); ProofOfDeliveryDto response = restAssured.given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .pathParam("id", proofOfDelivery.getId()) .body(dto) .when() .put(ID_URL) .then() .statusCode(200) .extract() .as(ProofOfDeliveryDto.class); assertThat(response.getDeliveredBy(), is(somebody)); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldNotUpdateProofOfDeliveryIfDoesNotExist() { given(proofOfDeliveryRepository.findOne(proofOfDelivery.getId())).willReturn(null); given(proofOfDeliveryRepository.exists(proofOfDelivery.getId())).willReturn(false); restAssured.given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .pathParam("id", proofOfDelivery.getId()) .body(createDto()) .when() .put(ID_URL) .then() .statusCode(404); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldNotUpdateProofOfDeliveryWhenIsSubmitted() { proofOfDelivery = new ProofOfDeliveryDataBuilder().buildAsConfirmed(); setUp(); String response = restAssured.given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .pathParam("id", proofOfDelivery.getId()) .body(createDto()) .when() .put(ID_URL) .then() .statusCode(400) .extract() .path("messageKey"); assertThat(response, is(PROOF_OF_DELIVERY_ALREADY_CONFIRMED)); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldRejectUpdateRequestIfUserHasNoRight() { denyUserAllRights(); String response = restAssured .given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .pathParam("id", proofOfDelivery.getId()) .body(createDto()) .when() .put(ID_URL) .then() .statusCode(403) .extract().path(MESSAGE_KEY); assertThat(response, is(PERMISSION_MISSING)); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldSubmitValidObject() { ProofOfDeliveryDto dto = createDto(); dto.setStatus(ProofOfDeliveryStatus.CONFIRMED); ProofOfDeliveryDto response = restAssured.given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .pathParam("id", proofOfDelivery.getId()) .body(dto) .when() .put(ID_URL) .then() .statusCode(200) .extract() .as(ProofOfDeliveryDto.class); assertThat(response.getStatus(), is(ProofOfDeliveryStatus.CONFIRMED)); ArgumentCaptor<Order> captor = ArgumentCaptor.forClass(Order.class); verify(orderRepository).save(captor.capture()); verify(stockEventBuilder).fromProofOfDelivery(any(ProofOfDelivery.class)); verify(stockEventStockManagementService).submit(any(StockEventDto.class)); assertThat(captor.getValue().getStatus(), is(OrderStatus.RECEIVED)); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldNotSubmitIfObjectIsNotValid() { proofOfDelivery = new ProofOfDeliveryDataBuilder().withoutDeliveredBy().build(); setUp(); ProofOfDeliveryDto dto = createDto(); dto.setStatus(ProofOfDeliveryStatus.CONFIRMED); String response = restAssured.given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .pathParam("id", proofOfDelivery.getId()) .body(dto) .when() .put(ID_URL) .then() .statusCode(400) .extract() .path("messageKey"); verifyZeroInteractions(orderRepository, stockEventBuilder, stockEventStockManagementService); assertThat(response, is(MUST_CONTAIN_VALUE)); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldGetChosenProofOfDelivery() { ProofOfDeliveryDto response = restAssured.given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .pathParam("id", proofOfDelivery.getId()) .when() .get(ID_URL) .then() .statusCode(200) .extract().as(ProofOfDeliveryDto.class); assertTrue(proofOfDeliveryRepository.exists(response.getId())); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldNotGetNonexistentProofOfDelivery() { given(proofOfDeliveryRepository.findOne(proofOfDelivery.getId())).willReturn(null); given(proofOfDeliveryRepository.exists(proofOfDelivery.getId())).willReturn(false); restAssured.given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .pathParam("id", proofOfDelivery.getId()) .when() .get(ID_URL) .then() .statusCode(404); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldRejectGetRequestIfUserHasNoRight() { denyUserAllRights(); String response = restAssured .given() .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(MediaType.APPLICATION_JSON_VALUE) .pathParam("id", proofOfDelivery.getId()) .when() .get(ID_URL) .then() .statusCode(403) .extract() .path(MESSAGE_KEY); assertThat(response, is(PERMISSIONS_MISSING)); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test @Ignore("Current version *.jrxml have relations to different modules (like reference-data)") public void shouldPrintProofOfDeliveryToPdf() throws IOException, JRException { ClassPathResource podReport = new ClassPathResource("reports/podPrint.jrxml"); Template template = new Template(PRINT_POD, null, null, CONSISTENCY_REPORT, ""); JasperReport report = JasperCompileManager.compileReport(podReport.getInputStream()); JRParameter[] jrParameters = report.getParameters(); if (jrParameters != null && jrParameters.length > 0) { template.setTemplateParameters( Arrays.stream(jrParameters) .filter(p -> !p.isSystemDefined()) .map(this::createParameter) .collect(Collectors.toList()) ); } given(templateRepository.findByName(PRINT_POD)).willReturn(template); restAssured.given() .pathParam("id", proofOfDelivery.getId()) .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .when() .get(PRINT_URL) .then() .statusCode(200); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldNotPrintProofOfDeliveryIfTemplateNonExistent() { // given given(templateRepository.findByName(any(String.class))).willReturn(null); // when restAssured.given() .pathParam("id", proofOfDelivery.getId()) .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .when() .get(PRINT_URL) .then() .statusCode(400); // then assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } @Test public void shouldRejectPrintRequestIfUserHasNoRight() { denyUserAllRights(); String response = restAssured .given() .pathParam("id", proofOfDelivery.getId()) .header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .when() .get(PRINT_URL) .then() .statusCode(403) .extract() .path(MESSAGE_KEY); assertThat(response, is(PERMISSIONS_MISSING)); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations()); } private TemplateParameter createParameter(JRParameter jrParameter) { TemplateParameter templateParameter = new TemplateParameter(); templateParameter.setName(jrParameter.getName()); templateParameter.setDisplayName(jrParameter.getPropertiesMap().getProperty("displayName")); templateParameter.setDescription(jrParameter.getDescription()); templateParameter.setDataType(jrParameter.getValueClassName()); String selectSql = jrParameter.getPropertiesMap().getProperty("selectSql"); if (isNotBlank(selectSql)) { templateParameter.setSelectSql(selectSql); } if (jrParameter.getDefaultValueExpression() != null) { templateParameter.setDefaultValue(jrParameter.getDefaultValueExpression() .getText().replace("\"", "").replace("\'", "")); } return templateParameter; } private ProofOfDeliveryDto createDto() { ProofOfDeliveryDto dto = new ProofOfDeliveryDto(); dto.setServiceUrl(serviceUrl); proofOfDelivery.export(dto); return dto; } }
package org.jdcp.worker; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.UUID; import java.util.concurrent.Executor; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.jdcp.job.TaskDescription; import org.jdcp.job.TaskWorker; import org.jdcp.remote.JobService; import org.selfip.bkimmel.jobs.Job; import org.selfip.bkimmel.progress.ProgressMonitor; import org.selfip.bkimmel.rmi.Serialized; /** * A job that processes tasks for a parallelizable job from a remote * <code>JobServiceMaster<code>. This class may potentially use multiple * threads to process tasks. * @author bkimmel */ public final class ThreadServiceWorkerJob implements Job { /** * Initializes the address of the master and the amount of time to idle * when no task is available. * @param masterHost The URL of the master. * @param idleTime The time (in milliseconds) to idle when no task is * available. * @param maxConcurrentWorkers The maximum number of concurrent worker * threads to allow. * @param executor The <code>Executor</code> to use to process tasks. */ public ThreadServiceWorkerJob(String masterHost, long idleTime, int maxConcurrentWorkers, Executor executor) { assert(maxConcurrentWorkers > 0); this.masterHost = masterHost; this.idleTime = idleTime; this.executor = executor; this.workerSlot = new Semaphore(maxConcurrentWorkers, true); } /* (non-Javadoc) * @see org.jmist.framework.Job#go(org.jmist.framework.ProgressMonitor) */ public boolean go(ProgressMonitor monitor) { try { int workerIndex = 0; monitor.notifyIndeterminantProgress(); monitor.notifyStatusChanged("Looking up master..."); this.registry = LocateRegistry.getRegistry(this.masterHost); this.initializeService(); while (!monitor.isCancelPending()) { this.workerSlot.acquire(); String workerTitle = String.format("Worker (%d)", ++workerIndex); monitor.notifyStatusChanged("Queueing worker process..."); this.executor.execute(new Worker(monitor.createChildProgressMonitor(workerTitle))); } monitor.notifyStatusChanged("Cancelled."); } catch (Exception e) { monitor.notifyStatusChanged("Exception: " + e.toString()); System.err.println("Client exception: " + e.toString()); e.printStackTrace(); } finally { monitor.notifyCancelled(); } return false; } /** * Attempt to initialize a connection to the master service. * @return A value indicating whether the operation succeeded. */ private boolean initializeService() { try { this.service = (JobService) this.registry.lookup("JobService"); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * An entry in the <code>TaskWorker</code> cache. * @author bkimmel */ private static class WorkerCacheEntry { /** * Initializes the cache entry. * @param jobId The <code>UUID</code> of the job that the * <code>TaskWorker</code> processes tasks for. */ public WorkerCacheEntry(UUID jobId) { this.jobId = jobId; this.workerGuard.writeLock().lock(); } /** * Returns a value indicating if this <code>WorkerCacheEntry</code> * is to be used for the job with the specified <code>UUID</code>. * @param jobId The job's <code>UUID</code> to test. * @return A value indicating if this <code>WorkerCacheEntry</code> * applies to the specified job. */ public boolean matches(UUID jobId) { return this.jobId.equals(jobId); } /** * Sets the <code>TaskWorker</code> to use. This method may only be * called once. * @param worker The <code>TaskWorker</code> to use for matching * jobs. */ public synchronized void setWorker(TaskWorker worker) { /* Set the worker. */ this.worker = worker; /* Release the lock. */ this.workerGuard.writeLock().unlock(); } /** * Gets the <code>TaskWorker</code> to use to process tasks for the * matching job. This method will wait for <code>setWorker</code> * to be called if it has not yet been called. * @return The <code>TaskWorker</code> to use to process tasks for * the matching job. * @see {@link #setWorker(TaskWorker)}. */ public TaskWorker getWorker() { this.workerGuard.readLock().lock(); TaskWorker worker = this.worker; this.workerGuard.readLock().unlock(); return worker; } /** * The <code>UUID</code> of the job that the <code>TaskWorker</code> * processes tasks for. */ private final UUID jobId; /** * The cached <code>TaskWorker</code>. */ private TaskWorker worker; /** * The <code>ReadWriteLock</code> to use before reading from or writing * to the <code>worker</code> field. */ private final ReadWriteLock workerGuard = new ReentrantReadWriteLock(); } /** * Searches for the <code>WorkerCacheEntry</code> matching the job with the * specified <code>UUID</code>. * @param jobId The <code>UUID</code> of the job whose * <code>WorkerCacheEntry</code> to search for. * @return The <code>WorkerCacheEntry</code> corresponding to the job with * the specified <code>UUID</code>, or <code>null</code> if the * no such entry exists. */ private WorkerCacheEntry getCacheEntry(UUID jobId) { assert(jobId != null); synchronized (this.workerCache) { Iterator<WorkerCacheEntry> i = this.workerCache.iterator(); /* Search for the worker for the specified job. */ while (i.hasNext()) { WorkerCacheEntry entry = i.next(); if (entry.matches(jobId)) { /* Remove the entry and re-insert it at the end of the list. * This will ensure that when an item is removed from the list, * the item that is removed will always be the least recently * used. */ i.remove(); this.workerCache.add(entry); return entry; } } /* cache miss */ return null; } } /** * Removes the specified entry from the task worker cache. * @param entry The <code>WorkerCacheEntry</code> to remove. */ private void removeCacheEntry(WorkerCacheEntry entry) { assert(entry != null); synchronized (this.workerCache) { this.workerCache.remove(entry); } } /** * Removes least recently used entries from the task worker cache until * there are at most <code>this.maxCachedWorkers</code> entries. */ private void removeOldCacheEntries() { synchronized (this.workerCache) { /* If the cache has exceeded capacity, then remove the least * recently used entry. */ assert(this.maxCachedWorkers > 0); while (this.workerCache.size() > this.maxCachedWorkers) { this.workerCache.remove(0); } } } /** * Obtains the task worker to process tasks for the job with the specified * <code>UUID</code>. * @param jobId The <code>UUID</code> of the job to obtain the task worker * for. * @return The <code>TaskWorker</code> to process tasks for the job with * the specified <code>UUID</code>, or <code>null</code> if the job * is invalid or has already been completed. * @throws RemoteException * @throws ClassNotFoundException */ private TaskWorker getTaskWorker(UUID jobId) throws RemoteException, ClassNotFoundException { WorkerCacheEntry entry = null; boolean hit; synchronized (this.workerCache) { /* First try to get the worker from the cache. */ entry = this.getCacheEntry(jobId); hit = (entry != null); /* If there was no matching cache entry, then add a new entry to * the cache. */ if (!hit) { entry = new WorkerCacheEntry(jobId); this.workerCache.add(entry); } } if (hit) { /* We found a cache entry, so get the worker from that entry. */ return entry.getWorker(); } else { /* cache miss */ /* The task worker was not in the cache, so use the service to * obtain the task worker. */ Serialized<TaskWorker> envelope = this.service.getTaskWorker(jobId); ClassLoader loader = JobServiceClassLoaderStrategy.createCachingClassLoader(service, jobId); TaskWorker worker = envelope.deserialize(loader); entry.setWorker(worker); /* If we couldn't get a worker from the service, then don't keep * the cache entry. */ if (worker == null) { this.removeCacheEntry(entry); } /* Clean up the cache. */ this.removeOldCacheEntries(); return worker; } } /** * Used to process tasks in threads. * @author bkimmel */ private class Worker implements Runnable { /** * Initializes the progress monitor to report to. * @param monitor The <code>ProgressMonitor</code> to report * the progress of the task to. */ public Worker(ProgressMonitor monitor) { this.monitor = monitor; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { try { this.monitor.notifyIndeterminantProgress(); this.monitor.notifyStatusChanged("Requesting task..."); if (service != null) { TaskDescription taskDesc = service.requestTask(); if (taskDesc != null) { this.monitor.notifyStatusChanged("Obtaining task worker..."); TaskWorker worker; try { worker = getTaskWorker(taskDesc.getJobId()); } catch (ClassNotFoundException e) { e.printStackTrace(); worker = null; } if (worker == null) { this.monitor.notifyStatusChanged("Could not obtain worker..."); this.monitor.notifyCancelled(); return; } this.monitor.notifyStatusChanged("Performing task..."); ClassLoader loader = worker.getClass().getClassLoader(); Object task = taskDesc.getTask().deserialize(loader); Object results = worker.performTask(task, monitor); this.monitor.notifyStatusChanged("Submitting task results..."); service.submitTaskResults(taskDesc.getJobId(), taskDesc.getTaskId(), new Serialized<Object>(results)); } else { this.monitor.notifyStatusChanged("Idling..."); this.idle(); } this.monitor.notifyComplete(); } else { this.monitor.notifyStatusChanged("No service at " + ThreadServiceWorkerJob.this.masterHost); this.waitForService(); this.monitor.notifyCancelled(); } } catch (RemoteException e) { System.err.println("Remote exception: " + e.toString()); e.printStackTrace(); this.monitor.notifyStatusChanged("Failed to communicate with master."); this.waitForService(); this.monitor.notifyCancelled(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { workerSlot.release(); } } /** * Blocks until a successful attempt is made to reconnect to the * service. This method will idle for some time between attempts. */ private void waitForService() { synchronized (registry) { while (!initializeService()) { this.idle(); } } } /** * Idles for a period of time before finishing the task. */ private void idle() { try { Thread.sleep(idleTime); } catch (InterruptedException e) { // continue. } } /** * The <code>ProgressMonitor</code> to report to. */ private final ProgressMonitor monitor; } /** The URL of the master. */ private final String masterHost; /** * The amount of time (in milliseconds) to idle when no task is available. */ private final long idleTime; /** The <code>Executor</code> to use to process tasks. */ private final Executor executor; /** * The <code>Semaphore</code> to use to throttle <code>Worker</code> * threads. */ private final Semaphore workerSlot; /** * The <code>Registry</code> to obtain the service from. */ private Registry registry = null; /** * The <code>JobService</code> to obtain tasks from and submit * results to. */ private JobService service = null; /** * A list of recently used <code>TaskWorker</code>s and their associated * job's <code>UUID</code>s, in order from least recently used to most * recently used. */ private final List<WorkerCacheEntry> workerCache = new LinkedList<WorkerCacheEntry>(); /** * The maximum number of <code>TaskWorker</code>s to retain in the cache. */ private final int maxCachedWorkers = 5; }
package com.gizwits.framework.activity.onboarding; import java.util.Timer; import java.util.TimerTask; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.gizwits.aircondition.R; import com.gizwits.framework.activity.BaseActivity; import com.gizwits.framework.activity.device.DeviceListActivity; import com.xpg.common.system.IntentUtils; import com.xpg.common.useful.StringUtils; import com.xtremeprog.xpgconnect.XPGWifiDevice; /** * ClassName: Class AirlinkActivity. <br/> * * <br/> * * @author Lien */ public class AirlinkActivity extends BaseActivity implements OnClickListener { /** * The btn config. */ private Button btnConfig; /** * The btn retry. */ private Button btnRetry; /** * The btn softap. */ private Button btnSoftap; /** * The iv back. */ private ImageView ivBack; /** * The ll start config. */ private LinearLayout llStartConfig; /** * The ll configing. */ private LinearLayout llConfiging; /** * The ll config failed. */ private LinearLayout llConfigFailed; /** The tv tick. */ private TextView tvTick; /** The secondleft. */ int secondleft = 60; /** The timer. */ private Timer timer; /** The str s sid. */ private String strSSid; /** The str psw. */ private String strPsw; /** The UI_STATE now. */ private UI_STATE UiStateNow; private enum handler_key { /** * The tick time. */ TICK_TIME, /** * The reg success. */ CONFIG_SUCCESS, /** * The toast. */ CONFIG_FAILED, } /** * The handler. */ Handler handler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); handler_key key = handler_key.values()[msg.what]; switch (key) { case TICK_TIME: secondleft if (secondleft <= 0) { timer.cancel(); sendEmptyMessage(handler_key.CONFIG_FAILED.ordinal()); } else { tvTick.setText(secondleft + ""); } break; case CONFIG_SUCCESS: IntentUtils.getInstance().startActivity(AirlinkActivity.this, DeviceListActivity.class); finish(); break; case CONFIG_FAILED: showLayout(UI_STATE.Result); break; } } }; /* * (non-Javadoc) * * @see com.gizwits.aircondition.activity.BaseActivity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_airlink); initViews(); initEvents(); initData(); } /** * Inits the events. */ private void initEvents() { btnConfig.setOnClickListener(this); btnRetry.setOnClickListener(this); btnSoftap.setOnClickListener(this); ivBack.setOnClickListener(this); } /** * Inits the views. */ private void initViews() { btnConfig = (Button) findViewById(R.id.btnConfig); btnRetry = (Button) findViewById(R.id.btnRetry); btnSoftap = (Button) findViewById(R.id.btnSoftap); tvTick = (TextView) findViewById(R.id.tvTick); ivBack=(ImageView) findViewById(R.id.ivBack); llStartConfig = (LinearLayout) findViewById(R.id.llStartConfig); llConfiging = (LinearLayout) findViewById(R.id.llConfiging); llConfigFailed = (LinearLayout) findViewById(R.id.llConfigFailed); showLayout(UI_STATE.Ready); } /** * Inits the data. */ private void initData() { if (getIntent() != null) { if (!StringUtils.isEmpty(getIntent().getStringExtra("ssid"))) { strSSid = getIntent().getStringExtra("ssid"); } if (!StringUtils.isEmpty(getIntent().getStringExtra("psw"))) { strPsw = getIntent().getStringExtra("psw"); } else { strPsw = ""; } } } private enum UI_STATE{ Ready,Setting,Result; } private void showLayout(UI_STATE ui){ UiStateNow=ui; switch(ui){ case Ready: llStartConfig.setVisibility(View.VISIBLE); llConfiging.setVisibility(View.GONE); llConfigFailed.setVisibility(View.GONE); ivBack.setVisibility(View.VISIBLE); break; case Setting: llStartConfig.setVisibility(View.GONE); llConfiging.setVisibility(View.VISIBLE); llConfigFailed.setVisibility(View.GONE); ivBack.setVisibility(View.GONE); break; case Result: llConfigFailed.setVisibility(View.VISIBLE); llConfiging.setVisibility(View.GONE); llStartConfig.setVisibility(View.GONE); ivBack.setVisibility(View.VISIBLE); break; } } /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnConfig: // airlink startAirlink(); break; case R.id.btnRetry: onBackPressed(); break; case R.id.btnSoftap: //spftap Intent intent = new Intent(AirlinkActivity.this, SoftApConfigActivity.class); intent.putExtra("ssid", strSSid); intent.putExtra("psw", strPsw); startActivity(intent); finish(); break; case R.id.ivBack: onBackPressed(); break; } } /** * Start airlink. */ private void startAirlink() { secondleft = 60; tvTick.setText(secondleft + ""); showLayout(UI_STATE.Setting); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { handler.sendEmptyMessage(handler_key.TICK_TIME.ordinal()); } }, 1000, 1000); mCenter.cSetAirLink(strSSid, strPsw); } @Override public void onBackPressed() { switch(UiStateNow){ case Ready: startActivity(new Intent(AirlinkActivity.this,AutoConfigActivity.class)); finish(); break; case Setting: break; case Result: startActivity(new Intent(AirlinkActivity.this,SearchDeviceActivity.class)); finish(); break; } } /* (non-Javadoc) * @see com.gizwits.framework.activity.BaseActivity#didSetDeviceWifi(int, com.xtremeprog.xpgconnect.XPGWifiDevice) */ @Override protected void didSetDeviceWifi(int error, XPGWifiDevice device) { if (error == 0) { handler.sendEmptyMessage(handler_key.CONFIG_SUCCESS.ordinal()); } else { handler.sendEmptyMessage(handler_key.CONFIG_FAILED.ordinal()); } } }
package com.github.randomcodeorg.ppplugin.ppdefaults.logging; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import com.github.randomcodeorg.ppplugin.ppdefaults.ByteCodeHelper; import javassist.CannotCompileException; import javassist.CtClass; import javassist.CtField; import javassist.CtMethod; public class InsertMethodCallLogProcessor extends AbstractLoggingProcessor { public InsertMethodCallLogProcessor() { } @Override protected void processClass(ByteCodeHelper helper, CtClass ctClass, Class<?> clazz) throws CannotCompileException { context.getLog().debug(String.format("Processing class %s...", clazz.getCanonicalName())); boolean classLevelLog = clazz.isAnnotationPresent(LogThis.class); LogThis annotation = null; if (classLevelLog) annotation = clazz.getAnnotation(LogThis.class); for (Method m : clazz.getDeclaredMethods()) { if (m.isAnnotationPresent(LogThis.class)) { processMethod(helper, ctClass, clazz, ByteCodeHelper.findMethod(ctClass, m), m, m.getAnnotation(LogThis.class)); } else if (classLevelLog) { processMethod(helper, ctClass, clazz, ByteCodeHelper.findMethod(ctClass, m), m, annotation); } } } protected void processMethod(ByteCodeHelper helper, CtClass ctClass, Class<?> clazz, CtMethod m, Method runtimeMethod, LogThis annotation) throws CannotCompileException { if (m == null) return; if (helper.edit(ctClass, clazz)) context.getLog().info(String.format("Inserting log calls into %s", m.getLongName())); CtField loggerField = injectLogger(helper, ctClass); context.getLog().debug(String.format("Using logger that is stored in field '%s' to log method calls of %s", loggerField.getName(), m.getLongName())); String loggerValue = getLoggerMessageString(m, runtimeMethod, annotation, getMethodVariableNames(m, runtimeMethod), loggerField); String toInsert = String.format("%s.%s(%s);", loggerField.getName(), getLogMethodName(annotation.value()), loggerValue); context.getLog().debug("Inserting: " + toInsert); m.insertBefore(toInsert); } protected String getLoggerMessageString(CtMethod m, Method runtimeMethod, LogThis annotation, String[] parameterNames, CtField loggerField) { StringBuilder sb = new StringBuilder(); sb.append("\"Called "); sb.append(m.getLongName()); if (parameterNames.length > 0) { sb.append(" with:"); for (int i = 0; i < parameterNames.length; i++) { String param = parameterNames[i]; if (param != null) { sb.append(String.format("\\n\\t%s: ", param)); sb.append(String.format("\" + $%d + \"", (i + 1))); } else { sb.append(String.format("\\n\\targ%d: ", i)); sb.append("@Stealth"); } } } if (annotation.logFields()) { Field[] fields = runtimeMethod.getDeclaringClass().getDeclaredFields(); if (fields.length > 0) { if (parameterNames.length == 0) sb.append(" with:"); else sb.append("\\n"); for (Field f : fields) { if (f.isAnnotationPresent(Stealth.class)) continue; if (annotation.ignoreStaticFinal()) { if (Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers())) continue; } sb.append(String.format("\\n\\t%s [field]: ", f.getName())); sb.append(String.format("\" + %s + \"", f.getName())); } } } sb.append("\""); return sb.toString(); } protected String[] getMethodVariableNames(CtMethod cm, Method method) { Parameter[] params = method.getParameters(); String[] result = new String[params.length]; Parameter p; for (int i = 0; i < params.length; i++) { p = params[i]; if (p.isAnnotationPresent(Stealth.class)) continue; result[i] = String.format("arg%d", i); } return result; } }
package org.litesoft.json.server; import org.litesoft.commonfoundation.base.*; import org.litesoft.server.dynamicload.*; import org.litesoft.server.util.*; import java8.util.function.*; public abstract class GsonPersister<T> implements Supplier<T>, TypePersister<T> { private final Class<T> mType; protected final String mFileName; public GsonPersister( Class<T> pType, String pFileNameWithoutJSON ) { mType = Confirm.isNotNull( "Type", pType ); mFileName = Confirm.significant( "FileName", pFileNameWithoutJSON ) + ".json"; } @Override public T get() { if ( !fileExists() ) { return ClassForName.newInstance( mType, mType.getName() ); } String zJSON = loadJson(); return GsonRoot.fromJson( zJSON, mType ); } @Override public void save( T pInstance ) { String zJSON = GsonRoot.toJson( Confirm.isNotNull( "Instance", pInstance ), mType ); saveJson( zJSON ); } protected T augment(T pNewInstance) { return pNewInstance; } protected abstract boolean fileExists(); protected abstract String loadJson(); protected abstract void saveJson( String pJSON ); }
package com.insightfullogic.honest_profiler.ports.javafx.controller; import static com.insightfullogic.honest_profiler.ports.javafx.ViewType.FLAME; import static com.insightfullogic.honest_profiler.ports.javafx.ViewType.FLAT; import static com.insightfullogic.honest_profiler.ports.javafx.ViewType.TREE; import static com.insightfullogic.honest_profiler.ports.javafx.model.ProfileContext.ProfileMode.LIVE; import static com.insightfullogic.honest_profiler.ports.javafx.util.BindUtil.CALLED_EXTRACTOR; import static com.insightfullogic.honest_profiler.ports.javafx.util.BindUtil.CALLING_EXTRACTOR; import static com.insightfullogic.honest_profiler.ports.javafx.util.BindUtil.DESCENDANT_FLAT_EXTRACTOR; import static com.insightfullogic.honest_profiler.ports.javafx.util.BindUtil.FLAME_EXTRACTOR; import static com.insightfullogic.honest_profiler.ports.javafx.util.BindUtil.FLAT_EXTRACTOR; import static com.insightfullogic.honest_profiler.ports.javafx.util.BindUtil.TREE_EXTRACTOR; import static com.insightfullogic.honest_profiler.ports.javafx.util.ConversionUtil.getStringConverterForType; import static com.insightfullogic.honest_profiler.ports.javafx.util.ResourceUtil.CONTENT_LABEL_PROFILESAMPLECOUNT; import static com.insightfullogic.honest_profiler.ports.javafx.util.ResourceUtil.INFO_BUTTON_COMPARE; import static com.insightfullogic.honest_profiler.ports.javafx.util.ResourceUtil.INFO_BUTTON_FREEZE_FROZEN; import static com.insightfullogic.honest_profiler.ports.javafx.util.ResourceUtil.INFO_BUTTON_FREEZE_UNFROZEN; import static com.insightfullogic.honest_profiler.ports.javafx.util.ResourceUtil.INFO_CHOICE_VIEWTYPE; import static com.insightfullogic.honest_profiler.ports.javafx.util.ResourceUtil.INFO_LABEL_PROFILESAMPLECOUNT; import static com.insightfullogic.honest_profiler.ports.javafx.util.ResourceUtil.TOOLTIP_BUTTON_FREEZE_FROZEN; import static com.insightfullogic.honest_profiler.ports.javafx.util.ResourceUtil.TOOLTIP_BUTTON_FREEZE_UNFROZEN; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.FREEZE_16; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.UNFREEZE_16; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.viewFor; import static java.util.Arrays.asList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.insightfullogic.honest_profiler.ports.javafx.ViewType; import com.insightfullogic.honest_profiler.ports.javafx.model.ApplicationContext; import com.insightfullogic.honest_profiler.ports.javafx.model.ProfileContext; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.Tooltip; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; public class ProfileRootController extends AbstractController { @FXML private ChoiceBox<ViewType> viewChoice; @FXML private Button freezeButton; @FXML private Tooltip freezeTooltip; @FXML private Button compareButton; @FXML private Label profileSampleCount; @FXML private AnchorPane content; @FXML private FlatViewController flatController; @FXML private TreeViewController callingController; @FXML private TreeViewController calledController; @FXML private TreeViewController treeController; @FXML private FlatViewController descendantsController; @FXML private FlameViewController flameController; private ProfileContext profileContext; private Map<ViewType, List<AbstractProfileViewController<?, ?>>> viewToControllerMap; @Override @FXML public void initialize() { super.initialize(); viewToControllerMap = new HashMap<>(); viewToControllerMap.put(FLAT, asList(flatController, callingController, calledController)); viewToControllerMap.put(TREE, asList(treeController, descendantsController)); viewToControllerMap.put(FLAME, asList(flameController)); } // Instance Accessors @Override public void setApplicationContext(ApplicationContext appCtx) { super.setApplicationContext(appCtx); flatController.setApplicationContext(appCtx); callingController.setApplicationContext(appCtx); calledController.setApplicationContext(appCtx); treeController.setApplicationContext(appCtx); descendantsController.setApplicationContext(appCtx); flameController.setApplicationContext(appCtx); } public void setProfileContext(ProfileContext prCtx) { this.profileContext = prCtx; flatController.setProfileContext(prCtx); flatController.bind(prCtx.profileProperty(), FLAT_EXTRACTOR); callingController.setProfileContext(prCtx); callingController.bind(flatController.selectedProperty(), CALLING_EXTRACTOR); calledController.setProfileContext(prCtx); calledController.bind(flatController.selectedProperty(), CALLED_EXTRACTOR); treeController.setProfileContext(prCtx); treeController.bind(prCtx.profileProperty(), TREE_EXTRACTOR); descendantsController.setProfileContext(prCtx); descendantsController.bind(treeController.selectedProperty(), DESCENDANT_FLAT_EXTRACTOR); flameController.setProfileContext(prCtx); flameController.bind(prCtx.flameGraphProperty(), FLAME_EXTRACTOR); prCtx.profileProperty().addListener( (property, oldValue, newValue) -> profileSampleCount.setText( newValue == null ? null : getText( CONTENT_LABEL_PROFILESAMPLECOUNT, newValue.getProfileData().getTotalCnt()))); if (prCtx.getProfile() != null) { profileSampleCount.setText( getText( CONTENT_LABEL_PROFILESAMPLECOUNT, prCtx.getProfile().getProfileData().getTotalCnt())); } viewChoice.setConverter(getStringConverterForType(ViewType.class)); viewChoice.getSelectionModel().selectedItemProperty() .addListener((property, oldValue, newValue) -> show(newValue)); viewChoice.getItems().addAll(ViewType.values()); viewChoice.getSelectionModel().select(FLAT); freezeButton.setDisable(prCtx.getMode() != LIVE); } // View Switch private void show(ViewType viewType) { for (int i = 0; i < viewChoice.getItems().size(); i++) { Node child = content.getChildren().get(i); child.setManaged(viewType.ordinal() == i); child.setVisible(viewType.ordinal() == i); } viewToControllerMap.forEach((type, controllerList) -> { if (viewType == type) { controllerList.forEach(AbstractProfileViewController::activate); } else { controllerList.forEach(AbstractProfileViewController::deactivate); } }); if (viewType == FLAME) { flameController.refreshFlameView(); } } // AbstractController Implementation @Override protected void initializeInfoText() { info(viewChoice, INFO_CHOICE_VIEWTYPE); info(compareButton, INFO_BUTTON_COMPARE); info(freezeButton, INFO_BUTTON_FREEZE_UNFROZEN); info(profileSampleCount, INFO_LABEL_PROFILESAMPLECOUNT); } @Override protected void initializeHandlers() { compareButton.setOnMousePressed(this::showCompareMenu); freezeButton.setOnAction(this::handleFreezeAction); } // Handler-related Helper Methods private void showCompareMenu(MouseEvent event) { ContextMenu ctxMenu = compareButton.getContextMenu(); if (ctxMenu == null) { ctxMenu = new ContextMenu(); compareButton.setContextMenu(ctxMenu); } refreshContextMenu(compareButton.getContextMenu()); compareButton.getContextMenu().show(compareButton, event.getScreenX(), event.getScreenY()); } private void refreshContextMenu(ContextMenu menu) { menu.getItems().clear(); List<String> profileNames = appCtx().getOpenProfileNames(); profileNames.forEach(name -> { if (!name.equals(profileContext.getName())) { MenuItem item = new MenuItem(name); item.setOnAction(event -> appCtx().createDiffView(profileContext.getName(), name)); menu.getItems().add(item); } }); } private void handleFreezeAction(ActionEvent event) { if (profileContext.isFrozen()) { unfreeze(); } else { freeze(); } } private void freeze() { profileContext.setFrozen(true); freezeButton.setGraphic(viewFor(UNFREEZE_16)); freezeTooltip.setText(appCtx().textFor(TOOLTIP_BUTTON_FREEZE_FROZEN)); info(freezeButton, INFO_BUTTON_FREEZE_FROZEN); } private void unfreeze() { profileContext.setFrozen(false); freezeButton.setGraphic(viewFor(FREEZE_16)); freezeTooltip.setText(appCtx().textFor(TOOLTIP_BUTTON_FREEZE_UNFROZEN)); info(freezeButton, INFO_BUTTON_FREEZE_UNFROZEN); } }
/* * $Id: RegistryArchivalUnit.java,v 1.26 2010-08-01 21:33:24 tlipkis Exp $ */ package org.lockss.plugin; import java.io.FileNotFoundException; import java.net.*; import java.util.List; import org.htmlparser.*; import org.htmlparser.tags.TitleTag; import org.htmlparser.filters.NodeClassFilter; import org.htmlparser.util.*; import org.lockss.config.*; import org.lockss.crawler.NewContentCrawler; import org.lockss.daemon.*; import org.lockss.plugin.base.BaseArchivalUnit; import org.lockss.state.*; import org.lockss.util.*; /** * <p>PluginArchivalUnit: The Archival Unit Class for PluginPlugin. * This archival unit uses a base url to define an archival unit. * @author Seth Morabito * @version 1.0 */ public class RegistryArchivalUnit extends BaseArchivalUnit { protected static final Logger log = Logger.getLogger("RegistryArchivalUnit"); /** The interval between recrawls of the loadable plugin registry AUs. */ static final String PARAM_REGISTRY_CRAWL_INTERVAL = RegistryPlugin.PREFIX + "crawlInterval"; static final long DEFAULT_REGISTRY_CRAWL_INTERVAL = Constants.DAY; /** If "au", registry AUs will crawl in parallel using individual * rate limiters; if "plugin" they'll crawl sequentially using a shared * rate limiter */ static final String PARAM_REGISTRY_FETCH_RATE_LIMITER_SOURCE = RegistryPlugin.PREFIX + "fetchRateLimiterSource"; static final String DEFAULT_REGISTRY_FETCH_RATE_LIMITER_SOURCE = "au"; /** Limits fetch rate of registry crawls */ static final String PARAM_REGISTRY_FETCH_RATE = RegistryPlugin.PREFIX + "fetchRate"; static final String DEFAULT_REGISTRY_FETCH_RATE = "20/10s"; /** Run polls on Plugin registry AUs */ static final String PARAM_ENABLE_REGISTRY_POLLS = RegistryPlugin.PREFIX + "enablePolls"; static final boolean DEFAULT_ENABLE_REGISTRY_POLLS = true; private String m_registryUrl = null; private int m_maxRefetchDepth = NewContentCrawler.DEFAULT_MAX_CRAWL_DEPTH; private List m_permissionCheckers = null; private boolean recomputeRegName = true; private boolean enablePolls = DEFAULT_ENABLE_REGISTRY_POLLS; private String regName = null; public RegistryArchivalUnit(RegistryPlugin plugin) { super(plugin); } // Called by RegistryPlugin iff any config below RegistryPlugin.PREFIX // has changed protected void setConfig(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) { m_maxRefetchDepth = config.getInt(NewContentCrawler.PARAM_MAX_CRAWL_DEPTH, NewContentCrawler.DEFAULT_MAX_CRAWL_DEPTH); fetchRateLimiter = recomputeFetchRateLimiter(fetchRateLimiter); enablePolls = config.getBoolean(PARAM_ENABLE_REGISTRY_POLLS, DEFAULT_ENABLE_REGISTRY_POLLS); } public void loadAuConfigDescrs(Configuration config) throws ConfigurationException { super.loadAuConfigDescrs(config); this.m_registryUrl = config.get(ConfigParamDescr.BASE_URL.getKey()); m_permissionCheckers = ListUtil.list(new CreativeCommonsPermissionChecker()); paramMap.putLong(KEY_AU_NEW_CONTENT_CRAWL_INTERVAL, CurrentConfig .getTimeIntervalParam(PARAM_REGISTRY_CRAWL_INTERVAL, DEFAULT_REGISTRY_CRAWL_INTERVAL)); if (log.isDebug2()) { log.debug2("Setting Registry AU recrawl interval to " + StringUtil.timeIntervalToString(paramMap.getLong(KEY_AU_NEW_CONTENT_CRAWL_INTERVAL))); } } /** * return a string that represents the plugin registry. This is * just the base URL. * @return The base URL. */ protected String makeName() { return "Plugin registry at '" + m_registryUrl + "'"; } public String getName() { if (recomputeRegName) { regName = recomputeRegName(); } if (regName != null) { return regName; } else { return super.getName(); } } // If there is a <title> element on the start page, use that as our AU // name. String recomputeRegName() { if (!isStarted()) { // This can get invoked (seveeral times, mostly from logging) before // enough mechanism has started to make it possible to resolve the CuUrl // below. return null; } try { CachedUrl cu = makeCachedUrl(m_registryUrl); if (cu == null) return null; URL cuUrl = CuUrl.fromCu(cu); Parser parser = new Parser(cuUrl.toString()); NodeList nodelst = parser.extractAllNodesThatMatch(new NodeClassFilter(TitleTag.class)); Node nodes [] = nodelst.toNodeArray(); recomputeRegName = false; if (nodes.length < 1) return null; // Get the first title found TitleTag tag = (TitleTag)nodes[0]; if (tag == null) return null; return tag.getTitle(); } catch (MalformedURLException e) { log.warning("recomputeRegName", e); return null; } catch (ParserException e) { if (e.getThrowable() instanceof FileNotFoundException) { log.warning("recomputeRegName: " + e.getThrowable().toString()); } else { log.warning("recomputeRegName", e); } return null; } } boolean isStarted() { return getPlugin().getDaemon().getPluginManager().getAuFromId(getAuId()) != null; } /** * return a string that points to the plugin registry page. * @return a string that points to the plugin registry page for * this registry. This is just the base URL. */ protected String makeStartUrl() { return m_registryUrl; } /** Call top level polls iff configured to do so. */ public boolean shouldCallTopLevelPoll(AuState aus) { if (!enablePolls) { return false; } return super.shouldCallTopLevelPoll(aus); } protected CrawlSpec makeCrawlSpec() throws LockssRegexpException { CrawlRule rule = makeRules(); List startUrls = getNewContentCrawlUrls(); return new SpiderCrawlSpec(startUrls, startUrls, rule, m_maxRefetchDepth, null, null); } /** * return the collection of crawl rules used to crawl and cache a * list of Plugin JAR files. * @return CrawlRule */ protected CrawlRule makeRules() { return new RegistryRule(); } // Might need to recompute name if refetch start page public UrlCacher makeUrlCacher(String url) { if (url.equals(m_registryUrl)) { recomputeRegName = true; } return super.makeUrlCacher(url); } protected RateLimiter recomputeFetchRateLimiter(RateLimiter oldLimiter) { String rate = CurrentConfig.getParam(PARAM_REGISTRY_FETCH_RATE, DEFAULT_REGISTRY_FETCH_RATE); Object limiterKey = getFetchRateLimiterKey(); if (limiterKey == null) { return RateLimiter.getRateLimiter(oldLimiter, rate, DEFAULT_REGISTRY_FETCH_RATE); } else { RateLimiter.Pool pool = RateLimiter.getPool(); return pool.findNamedRateLimiter(limiterKey, rate, DEFAULT_REGISTRY_FETCH_RATE); } } protected String getFetchRateLimiterSource() { return CurrentConfig.getParam(PARAM_REGISTRY_FETCH_RATE_LIMITER_SOURCE, DEFAULT_REGISTRY_FETCH_RATE_LIMITER_SOURCE); } // Registry AU crawl rule implementation private class RegistryRule implements CrawlRule { public int match(String url) { if (StringUtil.equalStringsIgnoreCase(url, m_registryUrl) || StringUtil.endsWithIgnoreCase(url, ".jar")) { return CrawlRule.INCLUDE; } else { return CrawlRule.EXCLUDE; } } } }
package no.uio.ifi.trackfind.backend.data.providers.trackhub; import com.google.common.collect.HashMultimap; import lombok.extern.slf4j.Slf4j; import no.uio.ifi.trackfind.backend.data.providers.AbstractDataProvider; import no.uio.ifi.trackfind.backend.pojo.TfHub; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.*; import java.util.stream.Collectors; /** * Draft of Data Provider for TrackHubRegistry. * * @author Dmytro Titov */ @Slf4j @Component @Transactional public class TrackHubRegistryDataProvider extends AbstractDataProvider { private static final String HUBS_URL = "https: @Cacheable(value = "thr-hubs", key = "#root.method.name", sync = true) @SuppressWarnings("unchecked") @Override public Collection<TfHub> getAllTrackHubs() { try (InputStream inputStream = new URL(HUBS_URL).openStream(); InputStreamReader reader = new InputStreamReader(inputStream)) { Collection<Map> hubs = gson.fromJson(reader, Collection.class); return hubs.stream().map(h -> new TfHub(getName(), String.valueOf(h.get("name")))) .filter(h -> h.getName().contains("Blueprint")) .collect(Collectors.toSet()); } catch (Exception e) { log.error(e.getMessage(), e); return Collections.emptyList(); } } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void fetchData(String hubName) { Collection<String> fetchURLs = getFetchURLs(hubName); HashMultimap<String, String> mapToSave = HashMultimap.create(); for (String fetchURL : fetchURLs) { try (InputStream inputStream = new URL(fetchURL).openStream(); InputStreamReader reader = new InputStreamReader(inputStream)) { Map<String, Object> hub = (Map<String, Object>) gson.fromJson(reader, Map.class); Map<String, Object> source = (Map<String, Object>) hub.get("_source"); Collection<Map<String, Object>> data = (Collection<Map<String, Object>>) source.get("data"); for (Map<String, Object> entry : data) { mapToSave.put("data", gson.toJson(entry)); } } catch (Exception e) { log.error(e.getMessage(), e); } } save(hubName, mapToSave.asMap()); } @SuppressWarnings("unchecked") private Collection<String> getFetchURLs(String hubName) { Collection<String> fetchURLs = new HashSet<>(); try (InputStream inputStream = new URL(HUBS_URL).openStream(); InputStreamReader reader = new InputStreamReader(inputStream)) { Collection<Map> hubs = gson.fromJson(reader, Collection.class); Optional<Map> hubOptional = hubs.stream().filter(h -> String.valueOf(h.get("name")).equalsIgnoreCase(hubName)).findAny(); if (!hubOptional.isPresent()) { log.warn("No hubs found!"); return Collections.emptyList(); } Map hub = hubOptional.get(); Collection<Map> trackDBs = (Collection<Map>) hub.get("trackdbs"); for (Map trackDB : trackDBs) { fetchURLs.add(String.valueOf(trackDB.get("uri"))); } } catch (Exception e) { log.error(e.getMessage(), e); return Collections.emptyList(); } return fetchURLs; } }
package analysis.harmonic; import org.junit.*; import tonality.Tonality; import tonality.Tonality.Mode; import static jm.constants.Pitches.*; import java.util.ArrayList; import java.util.Arrays; public class ChordDegreeProcessorTest { @Test public void CMajorChordToDegree() { // Testing with C Major ChordDegreeProcessor cMajor = new ChordDegreeProcessor(new Tonality(C4, Mode.MAJOR, false)); ArrayList<Integer> firstChord = new ArrayList<>(Arrays.asList(C4, E2, G6)); // Do Mi Sol ArrayList<Integer> secondChord = new ArrayList<>(Arrays.asList(D2, F1, A7)); // Re Fa La ArrayList<Integer> secondChordSeventh = new ArrayList<>(Arrays.asList(D1, F3, A3, C6)); // Re Fa La Do ArrayList<Integer> thirdChord = new ArrayList<>(Arrays.asList(G1, E2, B6)); // Sol Mi Si ArrayList<Integer> fourthChord = new ArrayList<>(Arrays.asList(C4, F4, A4)); // Do Fa La ArrayList<Integer> fifthChord = new ArrayList<>(Arrays.asList(G3, D2, B4, G1, D5, B6)); // Sol Re Si Sol Re Si ArrayList<Integer> fifthChordSeventh = new ArrayList<>(Arrays.asList(G3, D2, B4, G1, D5, F6)); // Sol Re Si Sol Re Fa ArrayList<Integer> sixthChord = new ArrayList<>(Arrays.asList(A3, C2, A2, C5, A1, C3, E1)); // La Do La Do La Do Mi ArrayList<Integer> seventhChord = new ArrayList<>(Arrays.asList(B6, D2, F1)); // Si Re Fa ArrayList<Integer> notADegreeChord = new ArrayList<>(Arrays.asList(C1, D4, F2)); // Do Re Fa Assert.assertEquals(new ChordDegree(1, false, 1), cMajor.chordToDegree(firstChord, 1)); Assert.assertEquals(new ChordDegree(2, false, 1), cMajor.chordToDegree(secondChord, 1)); Assert.assertEquals(new ChordDegree(2, true, 1), cMajor.chordToDegree(secondChordSeventh, 1)); Assert.assertEquals(new ChordDegree(3, false, 1), cMajor.chordToDegree(thirdChord, 1)); Assert.assertEquals(new ChordDegree(4, false, 1), cMajor.chordToDegree(fourthChord, 1)); Assert.assertEquals(new ChordDegree(5, false, 1), cMajor.chordToDegree(fifthChord, 1)); Assert.assertEquals(new ChordDegree(5, true, 1), cMajor.chordToDegree(fifthChordSeventh, 1)); Assert.assertEquals(new ChordDegree(6, false, 1), cMajor.chordToDegree(sixthChord, 1)); Assert.assertEquals(new ChordDegree(7, false, 1), cMajor.chordToDegree(seventhChord, 1)); // FIXME: Decide whether it is normal that this chord is the seventh chord of the second degree or if it should be null //Assert.assertNull(cMajor.chordToDegree(notADegreeChord)); } @Test public void CMinorChordToDegree() { ChordDegreeProcessor cMinor = new ChordDegreeProcessor(new Tonality(C4, Mode.MINOR, false)); ArrayList<Integer> firstChord = new ArrayList<>(Arrays.asList(C4, EF2, G6)); // Do Mib Sol ArrayList<Integer> secondChord = new ArrayList<>(Arrays.asList(D2, F1, AF7)); // Re Fa La ArrayList<Integer> secondChordSeventh = new ArrayList<>(Arrays.asList(D1, F3, AF3, C6)); // Re Fa Lab Do ArrayList<Integer> thirdChord = new ArrayList<>(Arrays.asList(G1, EF2, BF6)); // Sol Mib Sib ArrayList<Integer> fourthChord = new ArrayList<>(Arrays.asList(C4, F4, AF4)); // Do Fa Lab ArrayList<Integer> fifthChord = new ArrayList<>(Arrays.asList(G3, D2, BF4, G1, D5, BF6)); // Sol Re Sib Sol Re Sib ArrayList<Integer> fifthChordSeventh = new ArrayList<>(Arrays.asList(G3, D2, BF4, G1, D5, F6)); // Sol Re Sib Sol Re Fa ArrayList<Integer> sixthChord = new ArrayList<>(Arrays.asList(AF3, C2, AF2, C5, AF1, C3, EF1)); // Lab Do Lab Do Lab Do Mib ArrayList<Integer> seventhChord = new ArrayList<>(Arrays.asList(BF6, D2, F1)); // Sib Re Fa Assert.assertEquals(new ChordDegree(1, false, 1), cMinor.chordToDegree(firstChord, 1)); Assert.assertEquals(new ChordDegree(2, false, 1), cMinor.chordToDegree(secondChord, 1)); Assert.assertEquals(new ChordDegree(2, true, 1), cMinor.chordToDegree(secondChordSeventh, 1)); Assert.assertEquals(new ChordDegree(3, false, 1), cMinor.chordToDegree(thirdChord, 1)); Assert.assertEquals(new ChordDegree(4, false, 1), cMinor.chordToDegree(fourthChord, 1)); Assert.assertEquals(new ChordDegree(5, false, 1), cMinor.chordToDegree(fifthChord, 1)); Assert.assertEquals(new ChordDegree(5, true, 1), cMinor.chordToDegree(fifthChordSeventh, 1)); Assert.assertEquals(new ChordDegree(6, false, 1), cMinor.chordToDegree(sixthChord, 1)); Assert.assertEquals(new ChordDegree(7, false, 1), cMinor.chordToDegree(seventhChord, 1)); } @Test public void GbMajorChordToDegree() { ChordDegreeProcessor gBMajor = new ChordDegreeProcessor(new Tonality(GF4, Mode.MAJOR, false)); ArrayList<Integer> firstChord = new ArrayList<>(Arrays.asList(GF4, BF2, DF6)); // Solb Sib Reb ArrayList<Integer> secondChord = new ArrayList<>(Arrays.asList(AF2, CF1, EF7)); // Lab Dob Mib ArrayList<Integer> secondChordSeventh = new ArrayList<>(Arrays.asList(AF2, CF1, EF7, GF6)); // Lab Dob Mib Solb ArrayList<Integer> thirdChord = new ArrayList<>(Arrays.asList(BF1, DF2, F6)); // Sib Reb Fa ArrayList<Integer> fourthChord = new ArrayList<>(Arrays.asList(GF4, CF4, EF4)); // Solb Dob Mib ArrayList<Integer> fifthChord = new ArrayList<>(Arrays.asList(DF3, AF2, F4, DF1, AF5, F6)); // Reb Lab Fa Reb Lab Fa ArrayList<Integer> fifthChordSeventh = new ArrayList<>(Arrays.asList(DF3, AF2, F4, DF1, AF5, CF6)); // Reb Lab Fa Reb Lab Dob ArrayList<Integer> sixthChord = new ArrayList<>(Arrays.asList(EF3, GF3, EF2, GF5, EF1, GF3, BF1)); // Mib Solb Mib Solb Mib Solb Sib ArrayList<Integer> seventhChord = new ArrayList<>(Arrays.asList(F6, AF2, CF1)); // Fa Lab Dob Assert.assertEquals(new ChordDegree(1, false, 1), gBMajor.chordToDegree(firstChord, 1)); Assert.assertEquals(new ChordDegree(2, false, 1), gBMajor.chordToDegree(secondChord, 1)); Assert.assertEquals(new ChordDegree(2, true, 1), gBMajor.chordToDegree(secondChordSeventh, 1)); Assert.assertEquals(new ChordDegree(3, false, 1), gBMajor.chordToDegree(thirdChord, 1)); Assert.assertEquals(new ChordDegree(4, false, 1), gBMajor.chordToDegree(fourthChord, 1)); Assert.assertEquals(new ChordDegree(5, false, 1), gBMajor.chordToDegree(fifthChord, 1)); Assert.assertEquals(new ChordDegree(5, true, 1), gBMajor.chordToDegree(fifthChordSeventh, 1)); Assert.assertEquals(new ChordDegree(6, false, 1), gBMajor.chordToDegree(sixthChord, 1)); Assert.assertEquals(new ChordDegree(7, false, 1), gBMajor.chordToDegree(seventhChord, 1)); } }
// ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments // ZAP: 2014/03/23 Issue 503: Change the footer tabs to display the data // with tables instead of lists // ZAP: 2014/03/23 Issue 1106: HistoryList's mapping of history ID to list // indexes not updated when history entry is deleted package org.parosproxy.paros.model; import java.util.Hashtable; import java.util.Map.Entry; import javax.swing.DefaultListModel; /** * @deprecated (2.3.0) Replaced with use of {@link org.zaproxy.zap.view.table.HistoryReferencesTableModel}. It will be removed * in a future release. */ @Deprecated public class HistoryList extends DefaultListModel<HistoryReference> { private static final long serialVersionUID = 1L; // ZAP: Added hashtable to allow elements of the list to be accessed via historyid private Hashtable<Integer, Integer> historyIdToIndex = new Hashtable<>(); @Override public void addElement(final HistoryReference hRef) { int sizeBefore = super.size(); super.addElement(hRef); if (sizeBefore == super.size() -1 ) { historyIdToIndex.put(hRef.getHistoryId(), sizeBefore); } else { // Cope with multiple threads adding to the list historyIdToIndex.put(hRef.getHistoryId(), indexOf(hRef)); } } public synchronized void notifyItemChanged(Object obj) { int i = indexOf(obj); if (i >= 0) { fireContentsChanged(this, i, i); } } public synchronized void notifyItemChanged(int historyId) { Integer i = historyIdToIndex.get(historyId); if (i != null) { fireContentsChanged(this, i, i); } } public HistoryReference getHistoryReference (int historyId) { Integer i = historyIdToIndex.get(historyId); if (i != null) { return this.elementAt(i); } return null; } @Override public void clear() { super.clear(); historyIdToIndex.clear(); } @Override public void removeAllElements() { super.removeAllElements(); historyIdToIndex.clear(); } @Override public HistoryReference remove(int index) { HistoryReference hRef = super.remove(index); historyIdToIndex.remove(hRef.getHistoryId()); updateIndexes(index); return hRef; } @Override public boolean removeElement(Object obj) { if (super.removeElement(obj)) { int idx = historyIdToIndex.remove(((HistoryReference) obj).getHistoryId()); updateIndexes(idx); return true; } return false; } @Override public void removeElementAt(int index) { remove(index); } // Note: implementation copied from base class (DefaultListModel) but changed to call the local method removeElementAt(int) @Override public void removeRange(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException("fromIndex must be <= toIndex"); } for (int i = toIndex; i >= fromIndex; i removeElementAt(i); } fireIntervalRemoved(this, fromIndex, toIndex); } private void updateIndexes(int fromIndex) { for (Entry<Integer, Integer> entry : historyIdToIndex.entrySet()) { if (entry.getValue() > fromIndex) { entry.setValue(entry.getValue() - 1); } } } }
package tv.floe.metronome.deeplearning.neuralnetwork.optimize; import java.io.Serializable; import org.apache.mahout.math.DenseMatrix; import org.apache.mahout.math.Matrix; import tv.floe.metronome.deeplearning.neuralnetwork.core.LogisticRegression; import tv.floe.metronome.deeplearning.neuralnetwork.gradient.LogisticRegressionGradient; import tv.floe.metronome.math.ArrayUtils; import tv.floe.metronome.math.MatrixUtils; import cc.mallet.optimize.Optimizable; public class LogisticRegressionOptimizer implements Optimizable.ByGradientValue,OptimizableByGradientValueMatrix { private LogisticRegression logReg; private double lr; public LogisticRegressionOptimizer(LogisticRegression logReg, double lr) { super(); this.logReg = logReg; this.lr = lr; } @Override public int getNumParameters() { return MatrixUtils.length( logReg.connectionWeights ) + MatrixUtils.length( logReg.biasTerms ); } @Override public void getParameters(double[] buffer) { for(int i = 0; i < buffer.length; i++) { buffer[i] = getParameter(i); } } @Override public double getParameter(int index) { if ( index >= MatrixUtils.length(logReg.connectionWeights)) { return MatrixUtils.getElement( logReg.biasTerms, index - MatrixUtils.length(logReg.connectionWeights) ); } return MatrixUtils.getElement( logReg.connectionWeights , index); } @Override public void setParameters(double[] params) { for(int i = 0; i < params.length; i++) { setParameter(i,params[i]); } } @Override public void setParameter(int index, double value) { if (index >= MatrixUtils.length( logReg.connectionWeights )) { MatrixUtils.setElement( logReg.biasTerms, index - MatrixUtils.length(logReg.connectionWeights), value); } else { MatrixUtils.setElement( logReg.connectionWeights, index, value); } } @Override public void getValueGradient(double[] buffer) { LogisticRegressionGradient grad = logReg.getGradient( lr ); for (int i = 0; i < buffer.length; i++) { if ( i < MatrixUtils.length( logReg.connectionWeights )) { buffer[ i ] = MatrixUtils.getElement( grad.getwGradient(), i ); } else { buffer[ i ] = MatrixUtils.getElement( grad.getbGradient(), i - MatrixUtils.length( logReg.connectionWeights ) ); } } } @Override public double getValue() { return -logReg.negativeLogLikelihood(); } @Override public Matrix getParameters() { Matrix params = new DenseMatrix(1, getNumParameters() ); for (int i = 0; i < MatrixUtils.length( params ); i++) { // params.put(i,getParameter(i)); MatrixUtils.setElement( params, i, this.getParameter( i ) ); } return params; } @Override public void setParameters(Matrix params) { //this.setParameters(params.toArray()); this.setParameters( ArrayUtils.flatten( MatrixUtils.fromMatrix( params ) ) ); } @Override public Matrix getValueGradient() { LogisticRegressionGradient grad = logReg.getGradient( lr ); Matrix ret = new DenseMatrix( 1, getNumParameters() ); for (int i = 0; i < MatrixUtils.length( ret ); i++) { if ( i < MatrixUtils.length( logReg.connectionWeights ) ) { MatrixUtils.setElement( ret, i, MatrixUtils.getElement( grad.getwGradient(), i ) ); } else { MatrixUtils.setElement( ret, i, MatrixUtils.getElement( grad.getbGradient(), i - MatrixUtils.length( logReg.connectionWeights ) ) ); } } return ret; } }
package org.protorabbit.json; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Arrays; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class DefaultSerializer implements JSONSerializer { @SuppressWarnings("unchecked") public Object serialize(Object o) { // null is null if (o == null) { return JSONObject.NULL; } // collections if (Collection.class.isAssignableFrom(o.getClass())) { Iterator<?> it = ((Collection<?>)o).iterator(); JSONArray ja = new JSONArray(); while(it.hasNext()) { Object i = serialize(it.next()); ja.put(i); } return ja; } // maps if (Map.class.isAssignableFrom(o.getClass())) { JSONObject jo = new JSONObject(); Map m = ((Map<String, ?>)o); Iterator<String> ki = m.keySet().iterator(); while (ki.hasNext()) { String key = ki.next(); Object value = serialize(m.get(key)); try { jo.put(key, value); } catch (JSONException e) { e.printStackTrace(); } } return jo; } // primitives if (o instanceof Double || o instanceof Number || o instanceof Integer || o instanceof String || o instanceof Enum || o instanceof Boolean) { return o; } if (o instanceof Date) { return ((Date)o).getTime(); } // convert arrays to collections boolean b = o.getClass().isArray(); if (b) { Object[] objs = (Object[])o; List l = Arrays.asList(objs); return serialize(l); } // serialize using bean like methods return serializePOJO(o); } /* * Look at all the public methods in the object * find the ones that start with "get" * * create a property key for the methods and invoke the method using reflection * to get value. */ public Object serializePOJO(Object pojo) { Object[] args = {}; HashMap<String, Object> map = new HashMap<String, Object>(); Method[] methods = pojo.getClass().getMethods(); for (int i=0; i < methods.length;i++) { try { Method m = methods[i]; if (Modifier.isPublic(m.getModifiers()) && !"getClass".equals(m.getName()) && !"getSystemClassLoader".equals(m.getName()) && !"getMethods".equals(m.getName()) && !"getDeclaredClasses".equals(m.getName()) && !"getConstructors".equals(m.getName()) && !"getDeclaringClass".equals(m.getName()) && !"getEnclosingClass".equals(m.getName()) && !"getClassLoader".equals(m.getName()) && m.getName().startsWith("get") && m.getName().length() > 3 && m.getParameterTypes().length == 0) { // change the case of the property from camelCase String key = m.getName().substring(3,4).toLowerCase(); // get the rest of the name; if (m.getName().length() > 4) { key += m.getName().substring(4); } Object value = m.invoke(pojo, args); map.put(key, value); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } // use the serializer itself to serialize a map of properties we created if (map.keySet().size() > 0) { return serialize(map); } return JSONObject.NULL; } }
package org.mindinformatics.gwt.domeo.plugins.annotopia.persistence.src; import java.util.ArrayList; import java.util.List; import org.mindinformatics.gwt.domeo.client.IDomeo; import org.mindinformatics.gwt.domeo.model.MAnnotation; import org.mindinformatics.gwt.domeo.model.MAnnotationSet; import org.mindinformatics.gwt.domeo.plugins.annotation.persistence.src.APersistenceManager; import org.mindinformatics.gwt.domeo.plugins.annotation.persistence.src.IPersistenceManager; import org.mindinformatics.gwt.domeo.plugins.annotation.persistence.src.IRetrieveExistingAnnotationSetHandler; import org.mindinformatics.gwt.domeo.plugins.annotation.persistence.src.IRetrieveExistingAnnotationSetListHandler; import org.mindinformatics.gwt.domeo.plugins.annotation.persistence.src.IRetrieveExistingBibliographySetHandler; import org.mindinformatics.gwt.domeo.plugins.persistence.annotopia.model.JsAnnotopiaSetResultWrapper; import org.mindinformatics.gwt.domeo.plugins.persistence.annotopia.serializers.AnnotopiaSerializerManager; import org.mindinformatics.gwt.domeo.plugins.persistence.annotopia.src.AnnotopiaConverter; import org.mindinformatics.gwt.framework.src.ApplicationUtils; import org.mindinformatics.gwt.framework.src.ICommandCompleted; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.query.client.Function; import com.google.gwt.query.client.Properties; import com.google.gwt.query.client.js.JsUtils; import com.google.gwt.query.client.plugins.ajax.Ajax; import com.google.gwt.query.client.plugins.ajax.Ajax.Settings; import com.google.gwt.user.client.Window; /** * @author Paolo Ciccarese <paolo.ciccarese@gmail.com> */ public class AnnotopiaPersistenceManager extends APersistenceManager implements IPersistenceManager { private static final String API_KEY = "annotopia-api-key"; private static final String POST = "post", PUT = "put", DELETE = "delete", JSON = "json"; private static final String PREFIX = "s/annotationset"; public String URL = "http://127.0.0.1:8090/"; /** * @param domeo Pointer to main application * @param url The URL of the Annotopia server * @param callback The pointer to the entity that will be triggered */ public AnnotopiaPersistenceManager(IDomeo domeo, String url, ICommandCompleted callback) { super(domeo, callback); if(url!=null) URL = url; } @Override public void saveAnnotation() { _application.getLogger().debug(this, "Saving annotation sets..."); _application.getProgressPanelContainer().setProgressMessage("Saving annotation sets to Annotopia..."); ArrayList<MAnnotationSet> setToSerialize = new ArrayList<MAnnotationSet>(); for(MAnnotationSet set: ((IDomeo)_application).getAnnotationPersistenceManager().getAllDiscussionSets()) { if(set.getHasChanged() && set.getAnnotations().size()>0) setToSerialize.add(set); } for(MAnnotationSet set: ((IDomeo)_application).getAnnotationPersistenceManager().getAllUserSets()) { if(set.getHasChanged() && set.getAnnotations().size()>0) setToSerialize.add(set); } for(MAnnotationSet annotationSet: setToSerialize) { if((annotationSet.getVersionNumber()==null || annotationSet.getVersionNumber().isEmpty())) { postAnnotationSet(annotationSet); } else { putAnnotationSet(annotationSet); } } } /** * Posts a new Annotation Set */ private void postAnnotationSet(MAnnotationSet set) { _application.getLogger().debug(this, "Posting new annotation set"); try { Ajax.ajax(Ajax.createSettings() .setUrl(URL + PREFIX) .setHeaders(getHeaders()) .setDataType(JSON) .setType(POST) .setData(new JsUtils.JsUtilsImpl().parseJSON(AnnotopiaSerializerManager.getInstance((IDomeo)_application).serialize(set).toString())) .setTimeout(10000) .setSuccess(new Function(){ // callback to be run if the request success public void f() { IDomeo _domeo = ((IDomeo)_application); JsAnnotopiaSetResultWrapper wrapper = (JsAnnotopiaSetResultWrapper) parseJson(getDataProperties().toJsonString()); AnnotopiaConverter unmarshaller = new AnnotopiaConverter(_domeo); MAnnotationSet savedSet = unmarshaller.unmarshallAnnotationSet(wrapper.getResult().getSet().get(0), false); if(savedSet==null) { _application.getLogger().exception(this, "Annotation set not saved correctly"); _application.getProgressPanelContainer().setErrorMessage("Annotation set not saved correctly"); } else { MAnnotationSet currentSet = _domeo.getPersistenceManager().getAnnotationSetById(savedSet.getPreviousVersion()); currentSet.setIndividualUri(savedSet.getIndividualUri()); currentSet.setLastSavedOn(savedSet.getLastSavedOn()); currentSet.setVersionNumber(savedSet.getVersionNumber()); currentSet.setPreviousVersion(savedSet.getPreviousVersion()); currentSet.setHasChanged(false); _application.getLogger().info(this, "Set minted URI: " +currentSet.getIndividualUri()); int matched = 0; for(MAnnotation annotation: savedSet.getAnnotations()) { for(MAnnotation currentAnnotation: currentSet.getAnnotations()) { if(currentAnnotation.getIndividualUri().equals(annotation.getPreviousVersion())) { _application.getLogger().info(this, "Matched " + currentAnnotation.getIndividualUri()); matched++; currentAnnotation.setIndividualUri(annotation.getIndividualUri()); currentAnnotation.setLastSavedOn(annotation.getLastSavedOn()); currentAnnotation.setVersionNumber(annotation.getVersionNumber()); currentAnnotation.setPreviousVersion(annotation.getPreviousVersion()); currentAnnotation.setHasChanged(false); // TODO: Assumes one target currentAnnotation.getSelector().setUri(annotation.getSelector().getUri()); break; } } } _application.getProgressPanelContainer().hide(); _application.getLogger().debug(this, "Completed saving of Annotation Set in " + (System.currentTimeMillis()-((IDomeo)_application).getDocumentPipelineTimer())+ "ms"); } } }).setError(new Function(){ // callback to be run if the request success public void f() { Window.alert("There was an error " + getDataObject()); } }) ); } catch (Exception e) { _application.getLogger().exception(this, "Couldn't complete annotation set post"); } } /** * Updates an existing Annotation Set */ private void putAnnotationSet(MAnnotationSet set) { _application.getLogger().debug(this, "Updating annotation set " + set.getUuid()); try { Ajax.ajax(Ajax.createSettings() .setUrl(URL + PREFIX + "/" + set.getUuid()) .setHeaders(getHeaders()).setDataType(JSON).setType(PUT) .setData(new JsUtils.JsUtilsImpl().parseJSON(AnnotopiaSerializerManager.getInstance((IDomeo)_application).serialize(set).toString())) .setTimeout(10000) .setSuccess(new Function(){ // callback to be run if the request success public void f() { IDomeo _domeo = ((IDomeo)_application); } }) ); } catch (Exception e) { _application.getLogger().exception(this, "Couldn't complete annotation set post"); } } /** * Deletes an existing Annotation Set */ private void deleteAnnotationSet(MAnnotationSet set) { try { Ajax.ajax(Ajax.createSettings() .setUrl(URL + PREFIX + "/" + set.getUuid()) .setHeaders(getHeaders()).setDataType(JSON).setType(DELETE) .setTimeout(10000) .setSuccess(new Function(){ // callback to be run if the request success public void f() { } }) ); } catch (Exception e) { _application.getLogger().exception(this, "Couldn't complete annotation set post"); } } /** * Posts a new annotation to an existing set */ private void postAnnotationInSet(MAnnotation annotation, MAnnotationSet set) { } /** * Updates an existing annotation in an existing set */ private void putAnnotationInSet(MAnnotation annotation, MAnnotationSet set) { } /** * Deletes an existing annotation to an existing set */ private void deleteAnnotationInSet(MAnnotation annotation, MAnnotationSet set) { } @Override public void retrieveExistingBibliographySet( IRetrieveExistingBibliographySetHandler handler) { // TODO Auto-generated method stub } @Override public void retrieveExistingAnnotationSets(List<String> ids, IRetrieveExistingAnnotationSetHandler handler) { // TODO Auto-generated method stub } @Override public void retrieveExistingAnnotationSetList( IRetrieveExistingAnnotationSetListHandler handler) { // TODO Auto-generated method stub } @Override public void saveBibliography() { // TODO Auto-generated method stub } /** * Get the properties for the HTTP headers * @return The list of properties for the header */ private Properties getHeaders() { Properties props = getAnnotopiaOAuthToken(); props.set("Authorization", "annotopia-api-key " + ApplicationUtils.getAnnotopiaApiKey()); return props; } /** Return the user Annotopia OAuth token if it is enabled. * @return The user Annotopia OAuth token if it is enabled. */ private Properties getAnnotopiaOAuthToken() { return (ApplicationUtils.getAnnotopiaOauthEnabled().equalsIgnoreCase("true")? Properties.create("Authorization: Bearer " + ApplicationUtils.getAnnotopiaOauthToken()): Properties.create()); } public static native String stringify(JavaScriptObject obj) /*-{ return JSON.stringify(obj); }-*/; public static native JavaScriptObject parseJson(String jsonStr) /*-{ try { var jsonStr = jsonStr .replace(/[\\]/g, '\\\\') .replace(/[\/]/g, '\\/') .replace(/[\b]/g, '\\b') .replace(/[\f]/g, '\\f') .replace(/[\n]/g, '\\n') .replace(/[\r]/g, '\\r') .replace(/[\t]/g, '\\t') .replace(/[\\][\"]/g, '\\\\\"') .replace(/\\'/g, "\\'"); //alert(jsonStr); return JSON.parse(jsonStr); } catch (e) { alert("Error while parsing the JSON message: " + e); } }-*/; }
package org.usfirst.frc.team236.robot; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public class RobotMap { // For example to map the left and right motors, you could define the // following variables to use with your drivetrain subsystem. // public static int leftMotor = 1; // public static int rightMotor = 2; // If you are using multiple modules, make sure to define both the port // number and the module. For example you with a rangefinder: // public static int rangefinderPort = 1; // public static int rangefinderModule = 1; public static final String CAMERA_NAME = "cam3"; public class DriveMap { public static final int PWM_LEFT_FRONT = 0; public static final int PWM_LEFT_BACK = 1; public static final int PWM_RIGHT_FRONT = 2; public static final int PWM_RIGHT_BACK = 3; public static final int DIO_ENCODER_LEFT_A = 0; public static final int DIO_ENCODER_LEFT_B = 1; public static final int DIO_ENCODER_RIGHT_A = 2; public static final int DIO_ENCODER_RIGHT_B = 3; public static final int SOL_FORWARD = 0; public static final int SOL_REVERSE = 1; public static final boolean INV_LEFT_FRONT = true; public static final boolean INV_LEFT_BACK = true; public static final boolean INV_RIGHT_FRONT = false; public static final boolean INV_RIGHT_BACK = false; public static final boolean INV_ENCODER_LEFT = false; public static final boolean INV_ENCODER_RIGHT = false; // Circumference of Drive Wheel may need tweaking public static final double CIRCUMFERENCE = 28; // Gear ratio is 3:1, and raw encoder count is 512 per full revolution public static final double DISTANCE_PER_PULSE = CIRCUMFERENCE / (3 * 512); } public class IntakeMap { public static final int PWM_MOTOR = 4; public static final boolean INV_MOTOR = false; public static final int DIO_LIMIT = 8; } public class ArmMap { public static final int PWM_MOTOR_LEFT = 5; public static final boolean INV_MOTOR_LEFT = false; public static final int PWM_MOTOR_RIGHT = 6; public static final boolean INV_MOTOR_RIGHT = false; public static final int DIO_ENCODER_A = 4; public static final int DIO_ENCODER_B = 5; public static final double DEGREES_PER_PULSE = 360.0 / (3 * 128.0); public static final boolean INV_ENCODER = false; public static final int DIO_LIMIT_TOP = 6; public static final int DIO_LIMIT_BOTTOM = 7; public static final double MIN_ANGLE = -10.5; // Lowest angle of arm public static final double MAX_ANGLE = 90; // Highest angle of arm public static final double BATTER_HIGH_SHOT_ANGLE = 74.0; public static final double DEFENSE_HIGH_SHOT_ANGLE = 37.948; public class upPID { // TODO tune PID public static final double kP = .1; public static final double kI = 0; public static final double kD = 0; } public class downPID { // TODO tune PID public static final double kP = .05; public static final double kI = 0; public static final double kD = 0; } } public class ControlMap { // USB public static final int PORT_STICK_LEFT = 0; public static final int PORT_STICK_RIGHT = 1; public static final int PORT_CONTROLLER = 2; // Left stick public static final int BUTTON_SHOOT = 1; public static final int BUTTON_EJECT = 2; public static final int BUTTON_INTAKE = 3; public static final int BUTTON_COCK = 4; public static final int BUTTON_INTAKE_OVERRIDE = 5; // Right stick public static final int BUTTON_SHIFT_DOWN = 2; public static final int BUTTON_SHIFT_UP = 3; public static final int BUTTON_INVERT_DRIVE = 4; public static final int BUTTON_NORMAL_DRIVE = 5; // Controller //public static final int BUTTON_ARM_DOWN = 1; //public static final int BUTTON_ARM_UP = 4; public static final int BUTTON_ARM_BOTTOM = 1; public static final int BUTTON_ARM_HIGH_SHOT_BATTER = 4; public static final int BUTTON_ARM_WITH_POV = 5; public static final int BUTTON_SHOOT_CONTROLLER = 6; public static final int BUTTON_ARM_JOYSTICK = 9; public static final int BUTTON_ARM_HIGH_SHOT_DEFENSE = 3; } public class ShooterMap { public static final int PWM_MOTOR = 7; public static final boolean INV_MOTOR = false; public static final int SOL_FORWARD = 2; public static final int SOL_REVERSE = 3; } }
package org.helioviewer.jhv.plugins.eveplugin.radio.data; import java.awt.Color; import java.awt.Component; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutionException; import org.helioviewer.jhv.base.Range; import org.helioviewer.jhv.base.logging.Log; import org.helioviewer.jhv.base.time.TimeUtils; import org.helioviewer.jhv.io.APIRequestManager; import org.helioviewer.jhv.io.DataSources; import org.helioviewer.jhv.plugins.eveplugin.EVEPlugin; import org.helioviewer.jhv.plugins.eveplugin.draw.DrawController; import org.helioviewer.jhv.plugins.eveplugin.draw.DrawableElement; import org.helioviewer.jhv.plugins.eveplugin.draw.DrawableElementType; import org.helioviewer.jhv.plugins.eveplugin.draw.TimeAxis; import org.helioviewer.jhv.plugins.eveplugin.draw.YAxis; import org.helioviewer.jhv.plugins.eveplugin.radio.gui.RadioOptionsPanel; import org.helioviewer.jhv.plugins.eveplugin.radio.model.ColorLookupModel; import org.helioviewer.jhv.plugins.eveplugin.radio.model.ColorLookupModelListener; import org.helioviewer.jhv.plugins.eveplugin.settings.EVESettings; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorElement; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorModel; import org.helioviewer.jhv.threads.JHVWorker; import org.helioviewer.jhv.viewmodel.view.jp2view.JP2ViewCallisto; /** * The radio data manager manages all the downloaded data for radio * spectrograms. * * It receives all of its input from the radio downloader as listener of the * radio downloader. * * @author Bram.Bourgoignie@oma.be * */ public class RadioDataManager implements ColorLookupModelListener, LineDataSelectorElement, DrawableElement { private static RadioDataManager instance; private LineDataSelectorModel lineDataSelectorModel; private final DrawController drawController; private Map<Long, BufferedImage> bufferedImages; private YAxis yAxis; private boolean isVisible; private final HashMap<Long, DownloadedJPXData> cache = new HashMap<Long, DownloadedJPXData>();; private static final String ROBserver = DataSources.ROBsettings.get("API.jp2images.path"); public static final int MAX_AMOUNT_OF_DAYS = 3; public static final int DAYS_IN_CACHE = MAX_AMOUNT_OF_DAYS + 1; private RadioDataManager() { ColorLookupModel.getInstance().addFilterModelListener(this); drawController = EVEPlugin.dc; bufferedImages = new HashMap<Long, BufferedImage>(); yAxis = new YAxis(new Range(400, 20), "Mhz", false); isVisible = true; } public static RadioDataManager getSingletonInstance() { if (instance == null) { instance = new RadioDataManager(); instance.init(); } return instance; } private void init() { lineDataSelectorModel = LineDataSelectorModel.getSingletonInstance(); } public void clearCache() { for (DownloadedJPXData jpxData : cache.values()) { if (jpxData.isInited()) jpxData.remove(); } cache.clear(); } public HashMap<Long, DownloadedJPXData> getCache() { return cache; } public void requestAndOpenIntervals(long start, long end) { final ArrayList<Long> toDownloadStartDates = new ArrayList<Long>(); long startDate = start - start % TimeUtils.DAY_IN_MILLIS; ArrayList<Long> incomingStartDates = new ArrayList<Long>(DAYS_IN_CACHE); for (int i = 0; i < DAYS_IN_CACHE; i++) { incomingStartDates.add(startDate + i * TimeUtils.DAY_IN_MILLIS); } Iterator<Entry<Long, DownloadedJPXData>> it = cache.entrySet().iterator(); while (it.hasNext()) { Entry<Long, DownloadedJPXData> entry = it.next(); Long key = entry.getKey(); if (!incomingStartDates.contains(key)) { DownloadedJPXData jpxData = entry.getValue(); if (jpxData.isInited()) { jpxData.remove(); } it.remove(); } } for (long incomingStart : incomingStartDates) { if (!cache.containsKey(incomingStart)) { toDownloadStartDates.add(incomingStart); cache.put(incomingStart, new DownloadedJPXData(incomingStart, incomingStart + TimeUtils.DAY_IN_MILLIS)); } } if (!toDownloadStartDates.isEmpty()) { LineDataSelectorModel.getSingletonInstance().downloadStarted(RadioDataManager.getSingletonInstance()); JHVWorker<ArrayList<JP2ViewCallisto>, Void> imageDownloadWorker = new RadioJPXDownload().init(toDownloadStartDates); imageDownloadWorker.setThreadName("EVE--RadioDownloader"); EVESettings.getExecutorService().execute(imageDownloadWorker); } Iterator<Entry<Long, DownloadedJPXData>> itt = cache.entrySet().iterator(); } public void initJPX(ArrayList<JP2ViewCallisto> jpList, ArrayList<Long> datesToDownload) { for (int i = 0; i < jpList.size(); i++) { JP2ViewCallisto v = jpList.get(i); long date = datesToDownload.get(i); DownloadedJPXData jpxData = cache.get(date); if (v != null) { if (jpxData != null) { jpxData.init(v); } else { v.abolish(); } } else { jpxData.downloadJPXFailed(); } } } private void removeRadioData() { clearCache(); lineDataSelectorModel.removeLineData(this); } public void radioDataVisibilityChanged() { if (isVisible) { drawController.updateDrawableElement(this, true); } else { drawController.removeDrawableElement(this); } lineDataSelectorModel.lineDataElementUpdated(this); } void requestForData() { for (DownloadedJPXData jpxData : cache.values()) { jpxData.requestData(); } } @Override public void colorLUTChanged() { ColorModel cm = ColorLookupModel.getInstance().getColorModel(); Map<Long, BufferedImage> newBufferedImages = new HashMap<Long, BufferedImage>(); for (Map.Entry<Long, BufferedImage> entry : bufferedImages.entrySet()) { long index = entry.getKey(); BufferedImage old = entry.getValue(); BufferedImage newIm = new BufferedImage(cm, old.getRaster(), false, null); newBufferedImages.put(index, newIm); } bufferedImages = newBufferedImages; } @Override public YAxis getYAxis() { return yAxis; } @Override public void removeLineData() { removeRadioData(); } @Override public void setVisibility(boolean visible) { isVisible = visible; radioDataVisibilityChanged(); } @Override public boolean isVisible() { return isVisible; } @Override public String getName() { return "Callisto radiogram"; } @Override public Color getDataColor() { return null; } @Override public boolean isDownloading() { for (DownloadedJPXData jpxData : cache.values()) { if (jpxData.isDownloading()) { return true; } } return false; } @Override public Component getOptionsPanel() { return new RadioOptionsPanel(); } @Override public boolean hasData() { return true; } @Override public boolean isDeletable() { return true; } @Override public DrawableElementType getDrawableElementType() { return DrawableElementType.RADIO; } private long xmin; private long xmax; public boolean xAxisChanged(TimeAxis timeAxis) { boolean cond = timeAxis.min == xmin && timeAxis.max == xmax; xmin = timeAxis.min; xmax = timeAxis.max; return !cond; } private double ymin; private double ymax; public boolean yAxisChanged(YAxis yAxis) { boolean cond = yAxis.getSelectedRange().min == ymin && yAxis.getSelectedRange().max == ymax; ymin = yAxis.getSelectedRange().min; ymax = yAxis.getSelectedRange().max; return !cond; } @Override public void draw(Graphics2D g, Graphics2D leftAxisG, Rectangle graphArea, Rectangle leftAxisArea, TimeAxis timeAxis, Point mousePosition) { boolean timediffCond = timeAxis.max - timeAxis.min <= TimeUtils.DAY_IN_MILLIS * MAX_AMOUNT_OF_DAYS; if (timediffCond && (xAxisChanged(timeAxis) || yAxisChanged(yAxis))) { requestForData(); requestAndOpenIntervals(timeAxis.min, timeAxis.max); } if (timediffCond) { for (DownloadedJPXData djpx : cache.values()) { djpx.draw(g, graphArea, timeAxis, yAxis); } } else { String text1 = "The selected interval is too big."; String text2 = "Reduce the interval to see the radio spectrograms."; final int text1Width = (int) g.getFontMetrics().getStringBounds(text1, g).getWidth(); final int text2Width = (int) g.getFontMetrics().getStringBounds(text2, g).getWidth(); final int text1height = (int) g.getFontMetrics().getStringBounds(text2, g).getHeight(); final int text2height = (int) g.getFontMetrics().getStringBounds(text2, g).getHeight(); final int x1 = graphArea.x + (graphArea.width / 2) - (text1Width / 2); final int y1 = (int) (graphArea.y + (graphArea.height / 2) - 1.5 * text1height); final int x2 = graphArea.x + (graphArea.width / 2) - (text2Width / 2); final int y2 = (int) (graphArea.y + graphArea.height / 2 + 0.5 * text2height); g.setColor(Color.black); g.drawString(text1, x1, y1); g.drawString(text2, x2, y2); } } @Override public void setYAxis(YAxis _yAxis) { yAxis = _yAxis; } @Override public boolean hasElementsToDraw() { return true; } @Override public long getLastDateWithData() { return -1; } private static class RadioJPXDownload extends JHVWorker<ArrayList<JP2ViewCallisto>, Void> { private ArrayList<Long> datesToDownload; public RadioJPXDownload init(ArrayList<Long> toDownload) { datesToDownload = toDownload; return this; } @Override protected ArrayList<JP2ViewCallisto> backgroundWork() { ArrayList<JP2ViewCallisto> jpList = new ArrayList<JP2ViewCallisto>(); for (int i = 0; i < datesToDownload.size(); i++) { long date = datesToDownload.get(i); JP2ViewCallisto v = null; try { v = (JP2ViewCallisto) APIRequestManager.requestAndOpenRemoteFile(ROBserver, null, TimeUtils.apiDateFormat.format(date), TimeUtils.apiDateFormat.format(date), "ROB-Humain", "CALLISTO", "CALLISTO", "RADIOGRAM", false); } catch (IOException e) { Log.error("An error occured while opening the remote file!", e); } jpList.add(v); } return jpList; } @Override protected void done() { try { ArrayList<JP2ViewCallisto> jpList = get(); RadioDataManager.getSingletonInstance().initJPX(jpList, datesToDownload); } catch (InterruptedException e) { Log.error("ImageDownloadWorker execution interrupted: " + e.getMessage()); } catch (ExecutionException e) { Log.error("ImageDownloadWorker execution error: " + e.getMessage()); } } } }
package org.usfirst.frc.team997.robot; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.SPI.Port; import edu.wpi.first.wpilibj.SerialPort; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public class RobotMap { // For example to map the left and right motors, you could define the // following variables to use with your drivetrain subsystem. // public static int leftMotor = 1; // public static int rightMotor = 2; // If you are using multiple modules, make sure to define both the port // number and the module. For example you with a rangefinder: // public static int rangefinderPort = 1; // public static int rangefinderModule = 1; public static final SerialPort.Port AHRSPort = SerialPort.Port.kUSB; public static class PDP { public static final int[] leftDriveMotor = {0, 1, 2}, rightDriveMotor = {3, 14, 15}, climberTalon = {12, 13}, ballLiftTalon = {11}, gatherTalon = {10}; } public static class Ports { public static final int //PWM leftDriveMotor = 0, rightDriveMotor = 1, climberTalon = 2, elevatorTalon = 3, gatherTalon = 4, //Digital IO leftEncoderOne = 0, leftEncoderTwo = 1, rightEncoderOne = 2, rightEncoderTwo = 3, gatherSensor = 4, elevatorSensor = 5, //Analog ultraSonic = 0, //Pneumatic??? gatherSolenoidPort = 0; //Change this based on Lyla } public static class Values { public static final double shooterF = 3.965, shooterP = 30, shooterI = 0.0, shooterD = 500, shooterSpeed = 3500, climbSpeed = .5, gatherSpeed = -1; } }
package ca.corefacility.bioinformatics.irida.ria.unit.web.analysis; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.springframework.context.MessageSource; import org.springframework.mock.web.MockHttpServletResponse; import ca.corefacility.bioinformatics.irida.ria.unit.TestDataFactory; import ca.corefacility.bioinformatics.irida.ria.web.analysis.AnalysisController; import ca.corefacility.bioinformatics.irida.service.AnalysisSubmissionService; import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowsService; public class AnalysisControllerTest { /* * CONTROLLER */ private AnalysisController analysisController; /* * SERVICES */ private AnalysisSubmissionService analysisSubmissionServiceMock; private IridaWorkflowsService iridaWorkflowsServiceMock; @Before public void init() { analysisSubmissionServiceMock = mock(AnalysisSubmissionService.class); iridaWorkflowsServiceMock = mock(IridaWorkflowsService.class); MessageSource messageSourceMock = mock(MessageSource.class); analysisController = new AnalysisController(analysisSubmissionServiceMock, iridaWorkflowsServiceMock, messageSourceMock); } // AJAX TESTS @Test public void TestGetAjaxDownloadAnalysisSubmission() throws IOException { Long analysisSubmissionId = 1L; MockHttpServletResponse response = new MockHttpServletResponse(); when(analysisSubmissionServiceMock.read(analysisSubmissionId)).thenReturn(TestDataFactory.constructAnalysisSubmission()); analysisController.getAjaxDownloadAnalysisSubmission(analysisSubmissionId, response); assertEquals("Has the correct content type", "application/zip", response.getContentType()); assertEquals("Has the correct 'Content-Disposition' headers", "attachment;filename=submission-5.zip", response.getHeader("Content-Disposition")); } }
package org.jasig.ssp.util.importer.job.tasklet; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.jasig.ssp.util.importer.job.config.MetadataConfigurations; import org.jasig.ssp.util.importer.job.report.ReportGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.annotation.BeforeStep; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; public class DatabaseValidation implements Tasklet, StepExecutionListener { private StepExecution stepExecution; @Autowired private DataSource dataSource; private Boolean validateDatabase = true; String EOL = System.getProperty("line.separator"); Logger logger = LoggerFactory.getLogger(DatabaseValidation.class); public DatabaseValidation() { } @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { if(!validateDatabase) return RepeatStatus.FINISHED; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); StringBuilder validations = new StringBuilder(); for(Pair<String,String> sql:buildSQLValidation()){ String invalidRow = new String(sql.getLeft() + EOL); Boolean invalidRowFound = false; try{ SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql.getRight()); while(sqlRowSet.next()){ invalidRowFound = true; for(String columnName:sqlRowSet.getMetaData().getColumnNames()) { Object obj = sqlRowSet.getObject(columnName); invalidRow = invalidRow + columnName + ":" + obj.toString() + ","; } invalidRow = invalidRow + EOL; } }catch(Exception e){ validations.append("Error thrown on: " + sql.getLeft()); logger.error("Error thrown on: " + sql.getLeft(), e); }finally{ } if(invalidRowFound) validations.append(invalidRow + EOL); } this.stepExecution.getJobExecution().getExecutionContext().put("databaseValidations", validations.toString()); return RepeatStatus.FINISHED; } public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } private List<Pair<String,String>> buildSQLValidation(){ List<Pair<String,String>> statements = new ArrayList<Pair<String,String>>(); statements.add(new ImmutablePair<String,String>("Coach School Id does not Exist: ", "select distinct coach_school_id from external_person where coach_school_id IS NOT NULL AND coach_school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("Marital Status does not Exist: ", "select school_id,marital_status from external_person where marital_status IS NOT NULL AND marital_status NOT IN (select name from marital_status)")); statements.add(new ImmutablePair<String,String>("Ethnicity Value does not Exist: ","select school_id,ethnicity from external_person where ethnicity IS NOT NULL AND ethnicity NOT IN (select name from ethnicity)")); statements.add(new ImmutablePair<String,String>("Gender Value does not Exist: ", "select school_id,gender from external_person where gender IS NOT NULL AND gender NOT IN ('M','F','Male','Female')")); statements.add(new ImmutablePair<String,String>("Is Local Value does not Exist: ", "select school_id,is_local from external_person where is_local IS NOT NULL AND is_local NOT IN ('N','Y','n','y')")); statements.add(new ImmutablePair<String,String>("Student Type Code Value does not Exist: ", "select school_id,student_type_code from external_person where student_type_code IS NOT NULL AND student_type_code NOT IN (select code from student_type)")); statements.add(new ImmutablePair<String,String>("Non local address Value does not Exist: ", "select school_id,non_local_address from external_person where non_local_address IS NOT NULL AND non_local_address NOT IN ('Y','N','y', 'n')")); statements.add(new ImmutablePair<String,String>("Race Code Value does not Exist: ", "select school_id,race_code from external_person where race_code IS NOT NULL AND race_code NOT IN (select code from race)")); statements.add(new ImmutablePair<String,String>("external_student_transcript_term has term_code that does not exist: ", "select distinct term_code from external_student_transcript_term where term_code IS NOT NULL AND term_code NOT IN (select distinct code from external_term)")); statements.add(new ImmutablePair<String,String>("external_student_transcript_term has school_id that does not exist: ", "select distinct school_id from external_student_transcript_term where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_course_program has course_code that does not exist: ", "select distinct course_code from external_course_program where course_code IS NOT NULL AND course_code NOT IN (select distinct code from external_course)")); statements.add(new ImmutablePair<String,String>("external_course_term has course_code that does not exist: ", "select distinct course_code from external_course_term where course_code IS NOT NULL AND course_code NOT IN (select distinct code from external_course)")); statements.add(new ImmutablePair<String,String>("external_course_term has term_code that does not exist: ", "select distinct term_code from external_course_term where term_code IS NOT NULL AND term_code NOT IN (select distinct code from external_term)")); statements.add(new ImmutablePair<String,String>("external_faculty_course has faculty_school_id that does not exist: ", "select distinct faculty_school_id from external_faculty_course where faculty_school_id IS NOT NULL AND faculty_school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_faculty_course has term_code that does not exist: ", "select distinct term_code from external_faculty_course where term_code IS NOT NULL AND term_code NOT IN (select distinct code from external_term)")); statements.add(new ImmutablePair<String,String>("external_faculty_course has formatted_course that does not exist: ", "select distinct formatted_course from external_faculty_course where formatted_course IS NOT NULL AND formatted_course NOT IN (select distinct formatted_course from external_course)")); statements.add(new ImmutablePair<String,String>("external_course_requisite has requisite_code that does not exist: ", "select * from external_course_requisite where requisite_code NOT IN ('CO','PRE','PRE_CO')")); statements.add(new ImmutablePair<String,String>("external_course_requisite has requiring_course_code that does not exist: ", "select distinct requiring_course_code from external_course_requisite where requiring_course_code IS NOT NULL AND requiring_course_code NOT IN (select distinct code from external_course)")); statements.add(new ImmutablePair<String,String>("external_course_requisite has required_course_code that does not exist: ", "select distinct required_course_code from external_course_requisite where required_course_code IS NOT NULL AND required_course_code NOT IN (select distinct code from external_course)")); statements.add(new ImmutablePair<String,String>("external_course_tag has course_code that does not exist: ", "select distinct course_code from external_course_tag where course_code IS NOT NULL AND course_code NOT IN (select distinct code from external_course)")); statements.add(new ImmutablePair<String,String>("external_faculty_course_roster has faculty_school_id that does not exist: ", "select distinct faculty_school_id from external_faculty_course_roster where faculty_school_id IS NOT NULL AND faculty_school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_faculty_course_roster has term_code that does not exist: ", "select distinct term_code from external_faculty_course_roster where term_code IS NOT NULL AND term_code NOT IN (select distinct code from external_term)")); statements.add(new ImmutablePair<String,String>("external_faculty_course_roster has formatted_course that does not exist: ", "select distinct formatted_course from external_faculty_course_roster where formatted_course IS NOT NULL AND formatted_course NOT IN (select distinct formatted_course from external_course)")); statements.add(new ImmutablePair<String,String>("external_faculty_course_roster has school_id that does not exist: ", "select distinct school_id from external_faculty_course_roster where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_person_planning_status has status that does not exist: ", "select school_id,status from external_person_planning_status where status NOT IN ('ON','OFF')")); statements.add(new ImmutablePair<String,String>("external_person_planning_status has school_id that does not exist: ", "select distinct school_id from external_person_planning_status where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_person_note has school_id that does not exist: ", "select distinct school_id from external_person_note where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_registration_status_by_term has term_code that does not exist: ", "select distinct term_code from external_registration_status_by_term where term_code IS NOT NULL AND term_code NOT IN (select distinct code from external_term)")); statements.add(new ImmutablePair<String,String>("external_registration_status_by_term has school_id that does not exist: ", "select distinct school_id from external_registration_status_by_term where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_transcript_term has school_id that does not exist: ", "select distinct school_id from external_student_transcript_term where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_financial_aid has school_id that does not exist: ", "select distinct school_id from external_student_financial_aid where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_financial_aid has sap_status_code that does not exist: ", "select distinct school_id,sap_status_code from external_student_financial_aid where sap_status_code IS NOT NULL AND sap_status_code NOT IN (select distinct code from sap_status)")); statements.add(new ImmutablePair<String,String>("external_student_financial_aid has school_id that does not exist: ", "select distinct school_id,financial_aid_file_status from external_student_financial_aid where financial_aid_file_status IS NOT NULL AND financial_aid_file_status NOT IN ('COMPLETE','PENDING','INCOMPLETE')")); statements.add(new ImmutablePair<String,String>("external_student_test has school_id that does not exist: ", "select distinct school_id from external_student_test where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_transcript has school_id that does not exist: ", "select distinct school_id from external_student_transcript where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_transcript has school_id that does not exist: ", "select distinct school_id from external_student_transcript where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_transcript_course has term_code that does not exist: ", "select distinct term_code from external_student_transcript_course where term_code IS NOT NULL AND term_code NOT IN (select distinct code from external_term)")); statements.add(new ImmutablePair<String,String>("external_student_transcript_course has school_id that does not exist: ", "select distinct school_id from external_student_transcript_course where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_transcript_course has faculty_school_id that does not exist: ", "select distinct faculty_school_id from external_student_transcript_course where faculty_school_id IS NOT NULL AND faculty_school_id NOT IN (select distinct faculty_school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_transcript_course has formatted_course that does not exist: ", "select distinct formatted_course from external_student_transcript_course where formatted_course IS NOT NULL AND formatted_course NOT IN (select distinct formatted_course from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_financial_aid_file has school_id that does not exist: ", "select distinct school_id from external_student_financial_aid_file where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_financial_aid_file has status that does not exist: ", "select school_id,file_status from external_student_financial_aid_file where file_status IS NOT NULL AND file_status NOT IN ('COMPLETE','PENDING','INCOMPLETE')")); statements.add(new ImmutablePair<String,String>("external_student_financial_aid_file has status that does not exist: ", "select school_id,financial_file_code from external_student_financial_aid_file where financial_file_code IS NOT NULL AND financial_file_code NOT IN (select distinct code from financial_aid_file)")); statements.add(new ImmutablePair<String,String>("external_student_financial_aid_award_term has school_id that does not exist: ", "select distinct school_id from external_student_financial_aid_award_term where school_id IS NOT NULL AND school_id NOT IN (select distinct school_id from external_person)")); statements.add(new ImmutablePair<String,String>("external_student_financial_aid_award_term has accepted that does not exist: ", "select school_id,accepted from external_student_financial_aid_award_term where accepted IS NOT NULL AND accepted NOT IN ('Y','N','y','n')")); statements.add(new ImmutablePair<String,String>("external_student_financial_aid_award_term has term code that does not exist: ", "select school_id,term_code from external_student_financial_aid_award_term where term_code IS NOT NULL AND term_code NOT IN (select distinct code from external_term)")); statements.add(new ImmutablePair<String,String>("Count of External Courses: ", "SELECT COUNT(code) from external_course")); return statements; } public void setValidateDatabase(Boolean validateDatabase){ this.validateDatabase = validateDatabase; } @Override public void beforeStep(StepExecution arg0) { this.stepExecution = arg0; } @Override public ExitStatus afterStep(StepExecution arg0) { return ExitStatus.COMPLETED; } @BeforeStep public void saveStepExecution(StepExecution stepExecution) { this.stepExecution = stepExecution; } }
package org.telegram.telegrambots.meta.api.methods; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import org.telegram.telegrambots.meta.api.objects.UserProfilePhotos; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; /** * @author Ruben Bermudez * @version 1.0 * @brief Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object. * @date 20 of June of 2015 */ public class GetUserProfilePhotos extends BotApiMethod<UserProfilePhotos> { public static final String PATH = "getuserprofilephotos"; private static final String USERID_FIELD = "user_id"; private static final String OFFSET_FIELD = "offset"; private static final String LIMIT_FIELD = "limit"; @JsonProperty(USERID_FIELD) private Integer userId; ///< Unique identifier of the target user /** * Sequential number of the first photo to be returned. By default, all photos are returned. */ @JsonProperty(OFFSET_FIELD) private Integer offset; @JsonProperty(LIMIT_FIELD) private Integer limit; public GetUserProfilePhotos() { super(); } public Integer getUserId() { return userId; } public GetUserProfilePhotos setUserId(Integer userId) { this.userId = userId; return this; } public Integer getOffset() { return offset; } public GetUserProfilePhotos setOffset(Integer offset) { this.offset = offset; return this; } public Integer getLimit() { return limit; } public GetUserProfilePhotos setLimit(Integer limit) { this.limit = limit; return this; } @Override public String getMethod() { return PATH; } @Override public UserProfilePhotos deserializeResponse(String answer) throws TelegramApiRequestException { try { ApiResponse<UserProfilePhotos> result = OBJECT_MAPPER.readValue(answer, new TypeReference<ApiResponse<UserProfilePhotos>>(){}); if (result.getOk()) { return result.getResult(); } else { throw new TelegramApiRequestException("Error getting user profile photos", result); } } catch (IOException e) { throw new TelegramApiRequestException("Unable to deserialize response", e); } } @Override public void validate() throws TelegramApiValidationException { if (userId == null) { throw new TelegramApiValidationException("UserId parameter can't be empty", this); } } @Override public String toString() { return "GetUserProfilePhotos{" + "userId=" + userId + ", offset=" + offset + ", limit=" + limit + '}'; } }
package com.linkedin.thirdeye.dashboard.resources.v2; import com.linkedin.thirdeye.api.DimensionMap; import com.linkedin.thirdeye.dashboard.resources.v2.pojo.SearchFilters; import com.linkedin.thirdeye.datalayer.dto.MergedAnomalyResultDTO; import com.linkedin.thirdeye.datalayer.pojo.MergedAnomalyResultBean; import com.linkedin.thirdeye.detector.email.filter.AlertFilterFactory; import com.linkedin.thirdeye.detector.function.AnomalyFunctionFactory; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; import com.google.common.cache.LoadingCache; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.linkedin.thirdeye.api.TimeGranularity; import com.linkedin.thirdeye.api.TimeRange; import com.linkedin.thirdeye.constant.MetricAggFunction; import com.linkedin.thirdeye.dashboard.Utils; import com.linkedin.thirdeye.dashboard.resources.v2.pojo.AnomaliesSummary; import com.linkedin.thirdeye.dashboard.resources.v2.pojo.MetricSummary; import com.linkedin.thirdeye.dashboard.resources.v2.pojo.WowSummary; import com.linkedin.thirdeye.dashboard.views.GenericResponse; import com.linkedin.thirdeye.dashboard.views.heatmap.HeatMapViewHandler; import com.linkedin.thirdeye.dashboard.views.heatmap.HeatMapViewRequest; import com.linkedin.thirdeye.dashboard.views.heatmap.HeatMapViewResponse; import com.linkedin.thirdeye.dashboard.views.tabular.TabularViewHandler; import com.linkedin.thirdeye.dashboard.views.tabular.TabularViewRequest; import com.linkedin.thirdeye.dashboard.views.tabular.TabularViewResponse; import com.linkedin.thirdeye.datalayer.bao.DashboardConfigManager; import com.linkedin.thirdeye.datalayer.bao.DatasetConfigManager; import com.linkedin.thirdeye.datalayer.bao.MetricConfigManager; import com.linkedin.thirdeye.datalayer.dto.DashboardConfigDTO; import com.linkedin.thirdeye.datalayer.dto.DatasetConfigDTO; import com.linkedin.thirdeye.datalayer.dto.MetricConfigDTO; import com.linkedin.thirdeye.datasource.DAORegistry; import com.linkedin.thirdeye.datasource.MetricExpression; import com.linkedin.thirdeye.datasource.ThirdEyeCacheRegistry; import com.linkedin.thirdeye.datasource.cache.MetricDataset; import com.linkedin.thirdeye.datasource.cache.QueryCache; import com.linkedin.thirdeye.util.ThirdEyeUtils; @Path(value = "/data") @Produces(MediaType.APPLICATION_JSON) public class DataResource { private static final Logger LOG = LoggerFactory.getLogger(DataResource.class); private static final DAORegistry DAO_REGISTRY = DAORegistry.getInstance(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final ThirdEyeCacheRegistry CACHE_REGISTRY_INSTANCE = ThirdEyeCacheRegistry.getInstance(); private final MetricConfigManager metricConfigDAO; private final DatasetConfigManager datasetConfigDAO; private final DashboardConfigManager dashboardConfigDAO; private final LoadingCache<String, Long> collectionMaxDataTimeCache; private final LoadingCache<String, String> dimensionsFilterCache; private final QueryCache queryCache; private AnomaliesResource anomaliesResoure; public DataResource(AnomalyFunctionFactory anomalyFunctionFactory, AlertFilterFactory alertFilterFactory) { metricConfigDAO = DAO_REGISTRY.getMetricConfigDAO(); datasetConfigDAO = DAO_REGISTRY.getDatasetConfigDAO(); dashboardConfigDAO = DAO_REGISTRY.getDashboardConfigDAO(); this.queryCache = CACHE_REGISTRY_INSTANCE.getQueryCache(); this.collectionMaxDataTimeCache = CACHE_REGISTRY_INSTANCE.getCollectionMaxDataTimeCache(); this.dimensionsFilterCache = CACHE_REGISTRY_INSTANCE.getDimensionFiltersCache(); this.anomaliesResoure = new AnomaliesResource(anomalyFunctionFactory, alertFilterFactory); } @GET @Path("data/metricId") public List<MetricConfigDTO> getMetricsByName(@QueryParam("name") String name) { List<MetricConfigDTO> metricConfigDTOs = metricConfigDAO.findByMetricName(name); return metricConfigDTOs; } @GET @Path("metric/{metricId}") public MetricConfigDTO getMetricById(@PathParam("metricId") long metricId) { return metricConfigDAO.findById(metricId); } @GET @Path("summary/metrics") public List<String> getMetricNamesForDataset(@QueryParam("dataset") String dataset) { List<MetricConfigDTO> metrics = new ArrayList<>(); if (Strings.isNullOrEmpty(dataset)) { metrics.addAll(metricConfigDAO.findAll()); } else { metrics.addAll(metricConfigDAO.findActiveByDataset(dataset)); } List<String> metricsNames = new ArrayList<>(); for (MetricConfigDTO metricConfigDTO : metrics) { metricsNames.add(metricConfigDTO.getName()); } return metricsNames; } @GET @Path("summary/dashboards") public List<String> getDashboardNames() { List<String> output = new ArrayList<>(); List<DashboardConfigDTO> dashboardConfigDTOs = dashboardConfigDAO.findAll(); for (DashboardConfigDTO dashboardConfigDTO : dashboardConfigDTOs) { output.add(dashboardConfigDTO.getName()); } return output; } @GET @Path("summary/datasets") public List<String> getDatasetNames() { List<String> output = new ArrayList<>(); List<DatasetConfigDTO> datasetConfigDTOs = datasetConfigDAO.findAll(); for (DatasetConfigDTO dto : datasetConfigDTOs) { output.add(dto.getDataset()); } return output; } @GET @Path("maxDataTime/metricId/{metricId}") public Long getMetricMaxDataTime(@PathParam("metricId") Long metricId) { MetricConfigDTO metricConfig = DAO_REGISTRY.getMetricConfigDAO().findById(metricId); String dataset = metricConfig.getDataset(); long maxDataTime = Utils.getMaxDataTimeForDataset(dataset); return maxDataTime; } @GET @Path("autocomplete/anomalies") public List<? extends Object> getWhereNameLike(@QueryParam("mode") String mode, @QueryParam("name") String name){ if("metric".equalsIgnoreCase(mode)){ return getMetricsWhereNameLike(name); } if("dashboard".equalsIgnoreCase(mode)){ return getDashboardsWhereNameLike(name); } return Collections.emptyList(); } @GET @Path("autocomplete/dashboard") public List<DashboardConfigDTO> getDashboardsWhereNameLike(@QueryParam("name") String name) { List<DashboardConfigDTO> dashboardConfigs = Collections.emptyList(); if (StringUtils.isNotBlank(name)) { dashboardConfigs = dashboardConfigDAO.findWhereNameLikeAndActive("%" + name + "%"); } return dashboardConfigs; } @GET @Path("autocomplete/metric") public List<MetricConfigDTO> getMetricsWhereNameLike(@QueryParam("name") String name) { List<MetricConfigDTO> metricConfigs = Collections.emptyList(); if (StringUtils.isNotBlank(name)) { metricConfigs = metricConfigDAO.findWhereNameOrAliasLikeAndActive("%" + name + "%"); } return metricConfigs; } @GET @Path("autocomplete/dimensions/metric/{metricId}") public List<String> getDimensionsForMetric(@PathParam("metricId") Long metricId) { List<String> list = new ArrayList<>(); list.add("All"); try { MetricConfigDTO metricConfigDTO = metricConfigDAO.findById(metricId); DatasetConfigDTO datasetConfigDTO = datasetConfigDAO.findByDataset(metricConfigDTO.getDataset()); list.addAll(datasetConfigDTO.getDimensions()); } catch (Exception e) { LOG.error(e.getMessage(), e); } return list; } @GET @Path("autocomplete/filters/metric/{metricId}") public Map<String, List<String>> getFiltersForMetric(@PathParam("metricId") Long metricId) { Map<String, List<String>> filterMap = new HashMap<>(); try { // TODO : cache this MetricConfigDTO metricConfigDTO = metricConfigDAO.findById(metricId); DatasetConfigDTO datasetConfigDTO = datasetConfigDAO.findByDataset(metricConfigDTO.getDataset()); String dimensionFiltersJson = dimensionsFilterCache.get(datasetConfigDTO.getDataset()); if (!Strings.isNullOrEmpty(dimensionFiltersJson)) { filterMap = OBJECT_MAPPER.readValue(dimensionFiltersJson, LinkedHashMap.class); } } catch (Exception e) { LOG.error(e.getMessage(), e); throw new WebApplicationException(e); } return filterMap; } /** * Returns a list of all possible aggregations that we will support on the front end * For minute level datasets, we will also support HOURS and DAYS * For hour level datasets, we will also support DAYS * For day level datasets, we will only support DAYS * @param metricId * @return list of allowed data aggregations */ @GET @Path("agg/granularity/metric/{metricId}") public List<String> getDataAggregationGranularities(@PathParam("metricId") Long metricId) { MetricConfigDTO metricConfig = metricConfigDAO.findById(metricId); DatasetConfigDTO datasetConfig = ThirdEyeUtils.getDatasetConfigFromName(metricConfig.getDataset()); int dataTimeSize = datasetConfig.bucketTimeGranularity().getSize(); TimeUnit dataTimeUnit = datasetConfig.bucketTimeGranularity().getUnit(); List<String> dataGranularities = new ArrayList<>(); if (datasetConfig.isAdditive()) { // Add additional aggregation granularities only for additive datasets switch (dataTimeUnit) { case MILLISECONDS: case SECONDS: case MINUTES: dataGranularities.add(getDataGranularityString(dataTimeSize, TimeUnit.MINUTES)); case HOURS: dataGranularities.add(getDataGranularityString(1, TimeUnit.HOURS)); case DAYS: default: dataGranularities.add(getDataGranularityString(1, TimeUnit.DAYS)); break; } } else { // for non additive, keep only original granularity dataGranularities.add(getDataGranularityString(dataTimeSize, dataTimeUnit)); } return dataGranularities; } @GET @Path(value = "heatmap/{metricId}/{currentStart}/{currentEnd}/{baselineStart}/{baselineEnd}") @Produces(MediaType.APPLICATION_JSON) public HeatMapViewResponse getHeatMap( @QueryParam("filters") String filters, @PathParam("baselineStart") Long baselineStart, @PathParam("baselineEnd") Long baselineEnd, @PathParam("currentStart") Long currentStart, @PathParam("currentEnd") Long currentEnd, @PathParam("metricId") Long metricId) throws Exception { MetricConfigDTO metricConfigDTO = metricConfigDAO.findById(metricId); String collection = metricConfigDTO.getDataset(); String metric = metricConfigDTO.getName(); HeatMapViewRequest request = new HeatMapViewRequest(); request.setCollection(collection); List<MetricExpression> metricExpressions = Utils.convertToMetricExpressions(metric, MetricAggFunction.SUM, collection); request.setMetricExpressions(metricExpressions); long maxDataTime = collectionMaxDataTimeCache.get(collection); if (currentEnd > maxDataTime) { long delta = currentEnd - maxDataTime; currentEnd = currentEnd - delta; baselineEnd = baselineEnd - delta; } // See {@link #getDashboardData} for the reason that the start and end time are stored in a // DateTime object with data's timezone. DateTimeZone timeZoneForCollection = Utils.getDataTimeZone(collection); request.setBaselineStart(new DateTime(baselineStart, timeZoneForCollection)); request.setBaselineEnd(new DateTime(baselineEnd, timeZoneForCollection)); request.setCurrentStart(new DateTime(currentStart, timeZoneForCollection)); request.setCurrentEnd(new DateTime(currentEnd, timeZoneForCollection)); // filter if (filters != null && !filters.isEmpty()) { filters = URLDecoder.decode(filters, "UTF-8"); request.setFilters(ThirdEyeUtils.convertToMultiMap(filters)); } HeatMapViewHandler handler = new HeatMapViewHandler(queryCache); HeatMapViewResponse response = handler.process(request); return response; } @GET @Path("dashboard/metricids") public List<Long> getMetricIdsByDashboard(@QueryParam("name") String name) { if (StringUtils.isBlank(name)) { return Collections.emptyList(); } DashboardConfigDTO dashboard = dashboardConfigDAO.findByName(name); return dashboard.getMetricIds(); } /** * Returns percentage change between current values and baseline values. The values are * aggregated according to the number of buckets. If the bucket number is 1, then all values * between the given time ranges are sorted to the corresponding bucket and aggregated. * * Note: For current implementation, we assume the number of buckets is always 1. */ @GET @Path("dashboard/metricsummary") public List<MetricSummary> getMetricSummary(@QueryParam("dashboard") String dashboard, @QueryParam("timeRange") String timeRange) { List<MetricSummary> metricsSummary = new ArrayList<>(); if (StringUtils.isBlank(dashboard)) { return metricsSummary; } List<Long> metricIds = getMetricIdsByDashboard(dashboard); // Sort metric's id and metric expression by collections Multimap<String, Long> datasetToMetrics = ArrayListMultimap.create(); Multimap<String, MetricExpression> datasetToMetricExpressions = ArrayListMultimap.create(); Map<Long, MetricConfigDTO> metricIdToMetricConfig = new HashMap<>(); for (long metricId : metricIds) { MetricConfigDTO metricConfig = metricConfigDAO.findById(metricId); metricIdToMetricConfig.put(metricId, metricConfig); datasetToMetrics.put(metricConfig.getDataset(), metricId); datasetToMetricExpressions.put(metricConfig.getDataset(), ThirdEyeUtils.getMetricExpressionFromMetricConfig(metricConfig)); } // Create query request for each collection for (String dataset : datasetToMetrics.keySet()) { TabularViewRequest request = new TabularViewRequest(); request.setCollection(dataset); request.setMetricExpressions(new ArrayList<>(datasetToMetricExpressions.get(dataset))); // The input start and end time (i.e., currentStart, currentEnd, baselineStart, and // baselineEnd) are given in millisecond since epoch, which is timezone insensitive. On the // other hand, the start and end time of the request to be sent to backend database (e.g., // Pinot) could be converted to SimpleDateFormat, which is timezone sensitive. Therefore, // we need to store user's start and end time in DateTime objects with data's timezone // in order to ensure that the conversion to SimpleDateFormat is always correct regardless // user and server's timezone, including daylight saving time. String[] tokens = timeRange.split("_"); TimeGranularity timeGranularity = new TimeGranularity(Integer.valueOf(tokens[0]), TimeUnit.valueOf(tokens[1])); long currentEnd = Utils.getMaxDataTimeForDataset(dataset); long currentStart = currentEnd - TimeUnit.MILLISECONDS.convert(Long.valueOf(tokens[0]), TimeUnit.valueOf(tokens[1])); DateTimeZone timeZoneForCollection = Utils.getDataTimeZone(dataset); request.setBaselineStart(new DateTime(currentStart, timeZoneForCollection).minusDays(7)); request.setBaselineEnd(new DateTime(currentEnd, timeZoneForCollection).minusDays(7)); request.setCurrentStart(new DateTime(currentStart, timeZoneForCollection)); request.setCurrentEnd(new DateTime(currentEnd, timeZoneForCollection)); request.setTimeGranularity(timeGranularity); TabularViewHandler handler = new TabularViewHandler(queryCache); try { TabularViewResponse tabularViewResponse = handler.process(request); for (String metric : tabularViewResponse.getMetrics()) { MetricDataset metricDataset = new MetricDataset(metric, dataset); MetricConfigDTO metricConfig = CACHE_REGISTRY_INSTANCE.getMetricConfigCache().get(metricDataset); Long metricId = metricConfig.getId(); GenericResponse response = tabularViewResponse.getData().get(metric); MetricSummary metricSummary = new MetricSummary(); metricSummary.setMetricId(metricId); metricSummary.setMetricName(metricConfig.getName()); metricSummary.setMetricAlias(metricConfig.getAlias()); String[] responseData = response.getResponseData().get(0); double baselineValue = Double.valueOf(responseData[0]); double curentvalue = Double.valueOf(responseData[1]); double percentageChange = (curentvalue - baselineValue) * 100 / baselineValue; metricSummary.setBaselineValue(baselineValue); metricSummary.setCurrentValue(curentvalue); metricSummary.setWowPercentageChange(percentageChange); AnomaliesSummary anomaliesSummary = anomaliesResoure.getAnomalyCountForMetricInRange(metricId, currentStart, currentEnd); metricSummary.setAnomaliesSummary(anomaliesSummary); metricsSummary.add(metricSummary); } } catch (Exception e) { LOG.error("Exception while processing /data/tabular call", e); } } return metricsSummary; } @GET @Path("dashboard/anomalysummary") public Map<String, List<AnomaliesSummary>> getAnomalySummary( @QueryParam("dashboard") String dashboard, @QueryParam("timeRanges") String timeRanges) { List<Long> metricIds = getMetricIdsByDashboard(dashboard); List<String> timeRangesList = Lists.newArrayList(timeRanges.split(",")); Map<String, Long> timeRangeToDurationMap = new HashMap<>(); for (String timeRange : timeRangesList) { String[] tokens = timeRange.split("_"); long duration = TimeUnit.MILLISECONDS.convert(Long.valueOf(tokens[0]), TimeUnit.valueOf(tokens[1])); timeRangeToDurationMap.put(timeRange, duration); } Map<String, List<AnomaliesSummary>> metricAliasToAnomaliesSummariesMap = new HashMap<>(); for (Long metricId : metricIds) { List<AnomaliesSummary> summaries = new ArrayList<>(); MetricConfigDTO metricConfig = metricConfigDAO.findById(metricId); String metricAlias = metricConfig.getAlias(); String dataset = metricConfig.getDataset(); long endTime = Utils.getMaxDataTimeForDataset(dataset); for (String timeRange : timeRangesList) { long startTime = endTime - timeRangeToDurationMap.get(timeRange); AnomaliesSummary summary = anomaliesResoure.getAnomalyCountForMetricInRange(metricId, startTime, endTime); summaries.add(summary); } metricAliasToAnomaliesSummariesMap.put(metricAlias, summaries); } return metricAliasToAnomaliesSummariesMap; } @GET @Path("dashboard/wowsummary") public WowSummary getWowSummary( @QueryParam("dashboard") String dashboard, @QueryParam("timeRanges") String timeRanges) { WowSummary wowSummary = new WowSummary(); if (StringUtils.isBlank(dashboard)) { return wowSummary; } List<Long> metricIds = getMetricIdsByDashboard(dashboard); List<String> timeRangeLabels = Lists.newArrayList(timeRanges.split(",")); // Sort metric's id and metric expression by collections Multimap<String, Long> datasetToMetrics = ArrayListMultimap.create(); Multimap<String, MetricExpression> datasetToMetricExpressions = ArrayListMultimap.create(); Map<Long, MetricConfigDTO> metricIdToMetricConfig = new HashMap<>(); for (long metricId : metricIds) { MetricConfigDTO metricConfig = metricConfigDAO.findById(metricId); metricIdToMetricConfig.put(metricId, metricConfig); datasetToMetrics.put(metricConfig.getDataset(), metricId); datasetToMetricExpressions.put(metricConfig.getDataset(), ThirdEyeUtils.getMetricExpressionFromMetricConfig(metricConfig)); } Multimap<String, MetricSummary> metricAliasToMetricSummariesMap = ArrayListMultimap.create(); // Create query request for each collection for (String dataset : datasetToMetrics.keySet()) { TabularViewRequest request = new TabularViewRequest(); request.setCollection(dataset); request.setMetricExpressions(new ArrayList<>(datasetToMetricExpressions.get(dataset))); // The input start and end time (i.e., currentStart, currentEnd, baselineStart, and // baselineEnd) are given in millisecond since epoch, which is timezone insensitive. On the // other hand, the start and end time of the request to be sent to backend database (e.g., // Pinot) could be converted to SimpleDateFormat, which is timezone sensitive. Therefore, // we need to store user's start and end time in DateTime objects with data's timezone // in order to ensure that the conversion to SimpleDateFormat is always correct regardless // user and server's timezone, including daylight saving time. for (String timeRangeLabel : timeRangeLabels) { DateTimeZone timeZoneForCollection = Utils.getDataTimeZone(dataset); TimeRange timeRange = getTimeRangeFromLabel(dataset, timeZoneForCollection, timeRangeLabel); long currentEnd = timeRange.getEnd(); long currentStart = timeRange.getStart(); System.out.println(timeRangeLabel + "Current start end " + new DateTime(currentStart) + " " + new DateTime(currentEnd)); TimeGranularity timeGranularity = new TimeGranularity(1, TimeUnit.HOURS); request.setBaselineStart(new DateTime(currentStart, timeZoneForCollection).minusDays(7)); request.setBaselineEnd(new DateTime(currentEnd, timeZoneForCollection).minusDays(7)); request.setCurrentStart(new DateTime(currentStart, timeZoneForCollection)); request.setCurrentEnd(new DateTime(currentEnd, timeZoneForCollection)); request.setTimeGranularity(timeGranularity); TabularViewHandler handler = new TabularViewHandler(queryCache); try { TabularViewResponse tabularViewResponse = handler.process(request); for (String metric : tabularViewResponse.getMetrics()) { MetricDataset metricDataset = new MetricDataset(metric, dataset); MetricConfigDTO metricConfig = CACHE_REGISTRY_INSTANCE.getMetricConfigCache().get(metricDataset); Long metricId = metricConfig.getId(); String metricAlias = metricConfig.getAlias(); GenericResponse response = tabularViewResponse.getData().get(metric); MetricSummary metricSummary = new MetricSummary(); metricSummary.setMetricId(metricId); metricSummary.setMetricName(metricConfig.getName()); metricSummary.setMetricAlias(metricAlias); List<String[]> data = response.getResponseData(); double baselineValue = 0; double currentValue = 0; for (String[] responseData : data) { baselineValue = baselineValue + Double.valueOf(responseData[0]); currentValue = currentValue + Double.valueOf(responseData[1]); } double percentageChange = (currentValue - baselineValue) * 100 / baselineValue; metricSummary.setBaselineValue(baselineValue); metricSummary.setCurrentValue(currentValue); metricSummary.setWowPercentageChange(percentageChange); metricAliasToMetricSummariesMap.put(metricAlias, metricSummary); } } catch (Exception e) { LOG.error("Exception while processing /data/tabular call", e); } } } wowSummary.setMetricAliasToMetricSummariesMap(metricAliasToMetricSummariesMap); return wowSummary; } @GET @Path("anomalies/ranges") public Map<Long, List<TimeRange>> getAnomalyTimeRangesByMetricIds( @QueryParam("metricIds") String metricIds, @QueryParam("start") Long start, @QueryParam("end") Long end, @QueryParam("filters") String filters) { if (metricIds == null) throw new IllegalArgumentException("Must provide metricIds"); if (start == null) throw new IllegalArgumentException("Must provide start timestamp"); if (end == null) throw new IllegalArgumentException("Must provide end timestamp"); List<Long> ids = new ArrayList<>(); for (String metricId : metricIds.split(",")) { ids.add(Long.parseLong(metricId)); } // fetch anomalies in time range Map<Long, List<MergedAnomalyResultDTO>> anomalies = DAO_REGISTRY.getMergedAnomalyResultDAO().findAnomaliesByMetricIdsAndTimeRange(ids, start, end); int countAll = countNested(anomalies); // apply search filters if (filters != null && !filters.isEmpty()) { Multimap<String, String> filterMap = ThirdEyeUtils.convertToMultiMap(filters); for (Map.Entry<Long, List<MergedAnomalyResultDTO>> entry : anomalies.entrySet()) { entry.setValue(applyAnomalyFilters(entry.getValue(), filterMap)); } int countPassed = countNested(anomalies); LOG.info("Fetched {} anomalies ({} after filter) for time range {}-{}", countAll, countPassed, start, end); } else { // no filter LOG.info("Fetched {} anomalies for time range {}-{}", countAll, start, end); } // extract and truncate time ranges Map<Long, List<TimeRange>> output = new HashMap<>(); for(Map.Entry<Long, List<MergedAnomalyResultDTO>> entry : anomalies.entrySet()) { output.put(entry.getKey(), truncateRanges(extractAnomalyTimeRanges(entry.getValue()), start, end)); } return output; } /** * Returns a list of TimeRanges that correspond to anomalous time windows covered by at least * one anomaly. If multiple anomalies overlap or form adjacent time windows, they're merged * into a single range. * * @param anomalies merged anomalies * @return list of time ranges */ static List<TimeRange> extractAnomalyTimeRanges(List<MergedAnomalyResultDTO> anomalies) { if(anomalies.isEmpty()) { return Collections.emptyList(); } List<MergedAnomalyResultDTO> sorted = new ArrayList<>(anomalies); Collections.sort(sorted, new Comparator<MergedAnomalyResultDTO>() { @Override public int compare(MergedAnomalyResultDTO o1, MergedAnomalyResultDTO o2) { return Long.compare(o1.getStartTime(), o2.getStartTime()); } }); List<TimeRange> ranges = new ArrayList<>(); Iterator<MergedAnomalyResultDTO> itAnomaly = sorted.iterator(); MergedAnomalyResultDTO first = itAnomaly.next(); long currStart = first.getStartTime(); long currEnd = first.getEndTime(); while(itAnomaly.hasNext()) { MergedAnomalyResultDTO anomaly = itAnomaly.next(); if (currEnd >= anomaly.getStartTime()) { currEnd = Math.max(currEnd, anomaly.getEndTime()); } else { ranges.add(new TimeRange(currStart, currEnd)); currStart = anomaly.getStartTime(); currEnd = anomaly.getEndTime(); } } ranges.add(new TimeRange(currStart, currEnd)); return ranges; } /** * Returns a list of TimeRanges truncated to a given start and end timestamp. If the input * TimeRange is outside the boundaries it is omitted. If it overlaps partially, it is * truncated and included. * * @param ranges list of time ranges * @param start start timestamp (inclusive) * @param end end timestamp (exclusive) * @return list of truncated time ranges */ static List<TimeRange> truncateRanges(List<TimeRange> ranges, long start, long end) { List<TimeRange> output = new ArrayList<>(); for (TimeRange r : ranges) { if (r.getStart() < end && r.getEnd() > start) { output.add(new TimeRange(Math.max(r.getStart(), start), Math.min(r.getEnd(), end))); } } return output; } /** * Returns a list of anomalies that fulfills the dimension filter requirements specified in * {@code filters}. Returns an empty list if no anomaly passes the filter. If {@code filters} * contains multiple values for the same dimension key, ANY match will pass the filter. * * @param anomalies list of anomalies * @param filters dimension filter multimap * @return list of filtered anomalies */ static List<MergedAnomalyResultDTO> applyAnomalyFilters(List<MergedAnomalyResultDTO> anomalies, Multimap<String, String> filters) { List<MergedAnomalyResultDTO> output = new ArrayList<>(); for (MergedAnomalyResultDTO anomaly : anomalies) { if (applyAnomalyFilters(anomaly, filters)) { output.add(anomaly); } } return output; } /** * Returns {@code true} if a given anomaly passes the dimension filters {@code filters}, or * {@code false} otherwise. If {@code filters} contains multiple values for the same dimension * key, ANY match will pass the filter. * * @param anomaly anomaly to filter * @param filters dimension filter multimap * @return {@code true} if anomaly passed the filters, {@code false} otherwise */ static boolean applyAnomalyFilters(MergedAnomalyResultDTO anomaly, Multimap<String, String> filters) { DimensionMap dim = anomaly.getDimensions(); for (String filterKey : filters.keySet()) { if (!dim.containsKey(filterKey)) return false; Collection<String> filterValues = filters.get(filterKey); if (!filterValues.contains(dim.get(filterKey))) return false; } return true; } /** * Returns the total count of elements in collections nested within a map. * * @param map map with nested collection * @return total nested item count */ static int countNested(Map<?, ? extends Collection<?>> map) { int count = 0; for (Map.Entry<?, ? extends Collection<?>> entry : map.entrySet()) { count += entry.getValue().size(); } return count; } /** * convert label from WowSummaryModel to a TimeRange * @param dataset * @param timeZoneForCollection * @param label * @return */ private TimeRange getTimeRangeFromLabel(String dataset, DateTimeZone timeZoneForCollection, String label) { long start = 0; long end = 0; long datasetMaxTime = Utils.getMaxDataTimeForDataset(dataset); switch (label) { case "Most Recent Hour": end = datasetMaxTime; start = end - TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS); break; case "Today": end = System.currentTimeMillis(); start = new DateTime().withTimeAtStartOfDay().getMillis(); break; case "Yesterday": end = new DateTime().withTimeAtStartOfDay().getMillis(); start = end - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS); break; case "Last 7 Days": end = System.currentTimeMillis(); start = new DateTime(end).minusDays(6).withTimeAtStartOfDay().getMillis(); break; default: } TimeRange timeRange = new TimeRange(start, end); return timeRange; } /** * Generates data granularity string for dropdown in the root cause page * @param dataTimeSize * @param dataTimeUnit * @return data granularity string */ private String getDataGranularityString(int dataTimeSize, TimeUnit dataTimeUnit) { String dataGranularity = null; if (dataTimeSize == 1) { dataGranularity = dataTimeUnit.toString(); } else { dataGranularity = String.format("%d_%s", dataTimeSize, dataTimeUnit); } return dataGranularity; } }
package com.twelvemonkeys.imageio.plugins.psd; import javax.imageio.stream.ImageInputStream; import javax.imageio.IIOException; import java.io.IOException; class PSDLayerBlendMode { final int mBlendMode; final int mOpacity; // 0-255 final int mClipping; // 0: base, 1: non-base final int mFlags; public PSDLayerBlendMode(final ImageInputStream pInput) throws IOException { int blendModeSig = pInput.readInt(); if (blendModeSig != PSD.RESOURCE_TYPE) { // TODO: Is this really just a resource? throw new IIOException("Illegal PSD Blend Mode signature, expected 8BIM: " + PSDUtil.intToStr(blendModeSig)); } mBlendMode = pInput.readInt(); mOpacity = pInput.readUnsignedByte(); mClipping = pInput.readUnsignedByte(); mFlags = pInput.readUnsignedByte(); pInput.readByte(); // Pad } @Override public String toString() { StringBuilder builder = new StringBuilder(getClass().getSimpleName()); builder.append("["); builder.append("mode: \"").append(PSDUtil.intToStr(mBlendMode)); builder.append("\", opacity: ").append(mOpacity); builder.append(", clipping: ").append(mClipping); switch (mClipping) { case 0: builder.append(" (base)"); break; case 1: builder.append(" (non-base)"); break; default: builder.append(" (unknown)"); break; } builder.append(", flags: ").append(byteToBinary(mFlags)); /* bit 0 = transparency protected; bit 1 = visible; bit 2 = obsolete; bit 3 = 1 for Photoshop 5.0 and later, tells if bit 4 has useful information; bit 4 = pixel data irrelevant to appearance of document */ builder.append(" ("); if ((mFlags & 0x01) != 0) { builder.append("Transp. protected, "); } if ((mFlags & 0x02) != 0) { builder.append("Hidden, "); } if ((mFlags & 0x04) != 0) { builder.append("Obsolete bit, "); } if ((mFlags & 0x08) != 0) { builder.append("PS 5.0 data present, "); // "tells if next bit has useful information"... } if ((mFlags & 0x10) != 0) { builder.append("Pixel data irrelevant, "); } if ((mFlags & 0x20) != 0) { builder.append("Unknown bit 5, "); } if ((mFlags & 0x40) != 0) { builder.append("Unknown bit 6, "); } if ((mFlags & 0x80) != 0) { builder.append("Unknown bit 7, "); } // Stupidity... if (mFlags != 0) { builder.delete(builder.length() - 2, builder.length()); } builder.append(")"); builder.append("]"); return builder.toString(); } private static String byteToBinary(final int pFlags) { String flagStr = Integer.toBinaryString(pFlags); flagStr = "00000000".substring(flagStr.length()) + flagStr; return flagStr; } }
package net.orfjackal.visualvm4idea.plugin; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionResult; import com.intellij.execution.configurations.*; import com.intellij.execution.runners.JavaProgramRunner; import com.intellij.execution.runners.RunnerInfo; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.util.JDOMExternalizable; import net.orfjackal.visualvm4idea.handles.ProfiledAppHandle; import net.orfjackal.visualvm4idea.util.ServerConnection; import java.io.IOException; /** * @author Esko Luontola * @since 14.10.2008 */ public class ProfiledJavaProgramRunner implements JavaProgramRunner { private static final Logger log = Logger.getInstance(ProfiledJavaProgramRunner.class.getName()); public JDOMExternalizable createConfigurationData(ConfigurationInfoProvider settingsProvider) { log.info("ProfiledJavaProgramRunner.createConfigurationData"); return null; } // on run: 1 public void patch(JavaParameters javaParameters, RunnerSettings settings, boolean beforeExecution) throws ExecutionException { log.info("ProfiledJavaProgramRunner.patch"); // see: com.intellij.debugger.impl.DebuggerManagerImpl.createDebugParameters() // javaParameters.getVMParametersList().replaceOrAppend(...); try { // TODO: this starts up the agent, but VisualVM does not see the app before main() is executed ServerConnection server = new ServerConnection(); final ProfiledAppHandle handle = new ProfiledAppHandle(server); String agentPath = "D:\\DEVEL\\VisualVM for IDEA\\visualvm4idea\\visualvm4idea-dist\\target\\visualvm4idea\\lib\\visualvm4idea-program-agent.jar"; javaParameters.getVMParametersList().prepend("-javaagent:" + agentPath + "=port=" + server.getPort()); Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(10000); handle.resumeApplication(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); t.setDaemon(true); t.start(); } catch (IOException e) { throw new RuntimeException(e); } } public void checkConfiguration(RunnerSettings settings, ConfigurationPerRunnerSettings configurationPerRunnerSettings) throws RuntimeConfigurationException { log.info("ProfiledJavaProgramRunner.checkConfiguration"); } // on run: 2 public void onProcessStarted(RunnerSettings settings, ExecutionResult executionResult) { log.info("ProfiledJavaProgramRunner.onProcessStarted"); } // on run: 3 public AnAction[] createActions(ExecutionResult executionResult) { log.info("ProfiledJavaProgramRunner.createActions"); return new AnAction[0]; } public RunnerInfo getInfo() { log.info("ProfiledJavaProgramRunner.getInfo"); return new RunnerInfo("VisualVmId", "TODO: description", Resources.LOGO_16, "VisualVmToolWindowId", "VisualVmHelpId"); } public SettingsEditor getSettingsEditor(RunConfiguration configuration) { log.info("ProfiledJavaProgramRunner.getSettingsEditor"); return null; } }
package org.opendaylight.netvirt.vpnmanager; import java.math.BigInteger; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; import org.opendaylight.genius.mdsalutil.FlowEntity; import org.opendaylight.genius.mdsalutil.InstructionInfo; import org.opendaylight.genius.mdsalutil.InstructionType; import org.opendaylight.genius.mdsalutil.MDSALUtil; import org.opendaylight.genius.mdsalutil.MatchFieldType; import org.opendaylight.genius.mdsalutil.MatchInfo; import org.opendaylight.genius.mdsalutil.MetaDataUtil; import org.opendaylight.genius.mdsalutil.NwConstants; import org.opendaylight.genius.mdsalutil.NWUtil; import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager; import org.opendaylight.genius.utils.cache.DataStoreCache; import org.opendaylight.netvirt.fibmanager.api.RouteOrigin; import org.opendaylight.genius.utils.clustering.ClusteringUtils; import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronConstants; import org.opendaylight.netvirt.neutronvpn.interfaces.INeutronVpnManager; import org.opendaylight.netvirt.vpnmanager.utilities.InterfaceUtils; import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnAfConfig; import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInstances; import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInterfaces; import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstance; import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceKey; import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterface; import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceBuilder; import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceKey; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdPools; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPool; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPoolKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.LockManagerService; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.TimeUnits; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.TryLockInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.TryLockInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.UnlockInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.UnlockInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.FibEntries; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.VrfEntries; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTables; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTablesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTablesKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntry; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntryKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3nexthop.rev150409.L3nexthop; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3nexthop.rev150409.l3nexthop.VpnNexthops; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3nexthop.rev150409.l3nexthop.VpnNexthopsKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.Adjacencies; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.AdjacenciesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.PrefixToInterface; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.RouterInterfaces; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.LearntVpnVipToPortData; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.VpnIdToVpnInstance; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.VpnInstanceOpData; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.VpnInstanceToVpnId; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.VpnToExtraroute; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.adjacency.list.Adjacency; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.VpnIds; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.VpnIdsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.VpnIdsKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.vpn.ids.Prefixes; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.vpn.ids.PrefixesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.vpn.ids.PrefixesKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.router.interfaces.RouterInterface; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.router.interfaces.RouterInterfaceBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.router.interfaces.RouterInterfaceKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntryKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.vpn.instance.op.data.entry.VpnToDpnList; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.vpn.instance.op.data.entry.VpnToDpnListKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstanceBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.Vpn; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.VpnBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.VpnKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.vpn.Extraroute; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.vpn.ExtrarouteBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.vpn.ExtrarouteKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.learnt.vpn.vip.to.port.data.LearntVpnVipToPort; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.learnt.vpn.vip.to.port.data.LearntVpnVipToPortBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.learnt.vpn.vip.to.port.data.LearntVpnVipToPortKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExtRouters; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExternalNetworks; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.NaptSwitches; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.Routers; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.RoutersKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external.networks.Networks; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external.networks.NetworksKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitch; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitchKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.FibEntries; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTables; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTablesKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdPools; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPool; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPoolKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetPortFromInterfaceInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetPortFromInterfaceOutput; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3nexthop.rev150409.L3nexthop; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3nexthop.rev150409.l3nexthop.VpnNexthops; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3nexthop.rev150409.l3nexthop.VpnNexthopsKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.NeutronVpnPortipPortData; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.RouterInterfacesMap; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPort; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPortBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPortKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionBase; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionV4; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.PortKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.SubnetKey; import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.data.impl.schema.tree.SchemaValidationFailedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.primitives.Ints; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; public class VpnUtil { private static final Logger LOG = LoggerFactory.getLogger(VpnUtil.class); private static final int DEFAULT_PREFIX_LENGTH = 32; private static final String PREFIX_SEPARATOR = "/"; static InstanceIdentifier<VpnInterface> getVpnInterfaceIdentifier(String vpnInterfaceName) { return InstanceIdentifier.builder(VpnInterfaces.class) .child(VpnInterface.class, new VpnInterfaceKey(vpnInterfaceName)).build(); } static InstanceIdentifier<VpnInstance> getVpnInstanceIdentifier(String vpnName) { return InstanceIdentifier.builder(VpnInstances.class) .child(VpnInstance.class, new VpnInstanceKey(vpnName)).build(); } static VpnInterface getVpnInterface(String intfName, String vpnName, Adjacencies aug, BigInteger dpnId, Boolean isSheduledForRemove) { return new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(intfName)).setVpnInstanceName(vpnName).setDpnId(dpnId) .setScheduledForRemove(isSheduledForRemove).addAugmentation(Adjacencies.class, aug) .build(); } static InstanceIdentifier<Prefixes> getPrefixToInterfaceIdentifier(long vpnId, String ipPrefix) { return InstanceIdentifier.builder(PrefixToInterface.class) .child(VpnIds.class, new VpnIdsKey(vpnId)).child(Prefixes.class, new PrefixesKey(ipPrefix)).build(); } static InstanceIdentifier<VpnIds> getPrefixToInterfaceIdentifier(long vpnId) { return InstanceIdentifier.builder(PrefixToInterface.class) .child(VpnIds.class, new VpnIdsKey(vpnId)).build(); } static VpnIds getPrefixToInterface(long vpnId) { return new VpnIdsBuilder().setKey(new VpnIdsKey(vpnId)).setVpnId(vpnId).build(); } static Prefixes getPrefixToInterface(BigInteger dpId, String vpnInterfaceName, String ipPrefix) { return new PrefixesBuilder().setDpnId(dpId).setVpnInterfaceName( vpnInterfaceName).setIpAddress(ipPrefix).build(); } static InstanceIdentifier<Extraroute> getVpnToExtrarouteIdentifier(String vrfId, String ipPrefix) { return InstanceIdentifier.builder(VpnToExtraroute.class) .child(Vpn.class, new VpnKey(vrfId)).child(Extraroute.class, new ExtrarouteKey(ipPrefix)).build(); } static InstanceIdentifier<Vpn> getVpnToExtrarouteIdentifier(String vrfId) { return InstanceIdentifier.builder(VpnToExtraroute.class) .child(Vpn.class, new VpnKey(vrfId)).build(); } static Vpn getVpnToExtraRoute(String vrfId) { return new VpnBuilder().setKey(new VpnKey(vrfId)).setVrfId(vrfId).build(); } /** * Get VRF table given a Route Distinguisher * * @param broker dataBroker service reference * @param rd Route-Distinguisher * @return VrfTables that holds the list of VrfEntries of the specified rd */ public static VrfTables getVrfTable(DataBroker broker, String rd) { InstanceIdentifier<VrfTables> id = InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd)).build(); Optional<VrfTables> vrfTable = read(broker, LogicalDatastoreType.CONFIGURATION, id); return vrfTable.isPresent() ? vrfTable.get() : null; } /** * Retrieves the VrfEntries that belong to a given VPN filtered out by * Origin, searching by its Route-Distinguisher * * @param broker dataBroker service reference * @param rd Route-distinguisher of the VPN * @param originsToConsider Only entries whose origin is included in this * list will be considered * @return the list of VrfEntries */ public static List<VrfEntry> getVrfEntriesByOrigin(DataBroker broker, String rd, List<RouteOrigin> originsToConsider) { List<VrfEntry> result = new ArrayList<VrfEntry>(); List<VrfEntry> allVpnVrfEntries = getAllVrfEntries(broker, rd); for (VrfEntry vrfEntry : allVpnVrfEntries) { if (originsToConsider.contains(RouteOrigin.value(vrfEntry.getOrigin()))) { result.add(vrfEntry); } } return result; } static List<Prefixes> getAllPrefixesToInterface(DataBroker broker, long vpnId) { Optional<VpnIds> vpnIds = read(broker, LogicalDatastoreType.OPERATIONAL, getPrefixToInterfaceIdentifier(vpnId)); if (vpnIds.isPresent()) { return vpnIds.get().getPrefixes(); } return new ArrayList<Prefixes>(); } static List<Extraroute> getAllExtraRoutes(DataBroker broker, String vrfId) { Optional<Vpn> extraRoutes = read(broker, LogicalDatastoreType.OPERATIONAL, getVpnToExtrarouteIdentifier(vrfId)); if (extraRoutes.isPresent()) { return extraRoutes.get().getExtraroute(); } return new ArrayList<Extraroute>(); } /** * Retrieves all the VrfEntries that belong to a given VPN searching by its * Route-Distinguisher * * @param broker dataBroker service reference * @param rd Route-distinguisher of the VPN * @return the list of VrfEntries */ public static List<VrfEntry> getAllVrfEntries(DataBroker broker, String rd) { VrfTables vrfTables = VpnUtil.getVrfTable(broker, rd); return (vrfTables != null) ? vrfTables.getVrfEntry() : new ArrayList<VrfEntry>(); } //FIXME: Implement caches for DS reads public static VpnInstance getVpnInstance(DataBroker broker, String vpnInstanceName) { InstanceIdentifier<VpnInstance> id = InstanceIdentifier.builder(VpnInstances.class).child(VpnInstance.class, new VpnInstanceKey(vpnInstanceName)).build(); Optional<VpnInstance> vpnInstance = read(broker, LogicalDatastoreType.CONFIGURATION, id); return (vpnInstance.isPresent()) ? vpnInstance.get() : null; } static List<VpnInstance> getAllVpnInstances(DataBroker broker) { InstanceIdentifier<VpnInstances> id = InstanceIdentifier.builder(VpnInstances.class).build(); Optional<VpnInstances> optVpnInstances = VpnUtil.read(broker, LogicalDatastoreType.CONFIGURATION, id); if (optVpnInstances.isPresent()) { return optVpnInstances.get().getVpnInstance(); } else { return Collections.emptyList(); } } static List<VpnInstanceOpDataEntry> getAllVpnInstanceOpData(DataBroker broker) { InstanceIdentifier<VpnInstanceOpData> id = InstanceIdentifier.builder(VpnInstanceOpData.class).build(); Optional<VpnInstanceOpData> vpnInstanceOpDataOptional = VpnUtil.read(broker, LogicalDatastoreType.OPERATIONAL, id); if (vpnInstanceOpDataOptional.isPresent()) { return vpnInstanceOpDataOptional.get().getVpnInstanceOpDataEntry(); } else { return new ArrayList<VpnInstanceOpDataEntry>(); } } public static List<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.vpn .instance.op.data.entry.vpn.to.dpn.list.VpnInterfaces> getDpnVpnInterfaces(DataBroker broker, VpnInstance vpnInstance, BigInteger dpnId) { String rd = getRdFromVpnInstance(vpnInstance); InstanceIdentifier<VpnToDpnList> dpnToVpnId = getVpnToDpnListIdentifier(rd, dpnId); Optional<VpnToDpnList> dpnInVpn = VpnUtil.read(broker, LogicalDatastoreType.OPERATIONAL, dpnToVpnId); return dpnInVpn.isPresent() ? dpnInVpn.get().getVpnInterfaces() : Collections.emptyList(); } public static String getRdFromVpnInstance(VpnInstance vpnInstance) { VpnAfConfig vpnConfig = vpnInstance.getIpv4Family(); LOG.trace("vpnConfig {}", vpnConfig); String rd = vpnConfig.getRouteDistinguisher(); if (rd == null || rd.isEmpty()) { rd = vpnInstance.getVpnInstanceName(); LOG.trace("rd is null or empty. Assigning VpnInstanceName to rd {}", rd); } return rd; } static VrfEntry getVrfEntry(DataBroker broker, String rd, String ipPrefix) { VrfTables vrfTable = getVrfTable(broker, rd); // TODO: why check VrfTables if we later go for the specific VrfEntry? if (vrfTable != null) { InstanceIdentifier<VrfEntry> vrfEntryId = InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd)). child(VrfEntry.class, new VrfEntryKey(ipPrefix)).build(); Optional<VrfEntry> vrfEntry = read(broker, LogicalDatastoreType.CONFIGURATION, vrfEntryId); if (vrfEntry.isPresent()) { return vrfEntry.get(); } } return null; } static List<Adjacency> getAdjacenciesForVpnInterfaceFromConfig(DataBroker broker, String intfName) { final InstanceIdentifier<VpnInterface> identifier = getVpnInterfaceIdentifier(intfName); InstanceIdentifier<Adjacencies> path = identifier.augmentation(Adjacencies.class); Optional<Adjacencies> adjacencies = VpnUtil.read(broker, LogicalDatastoreType.CONFIGURATION, path); if (adjacencies.isPresent()) { List<Adjacency> nextHops = adjacencies.get().getAdjacency(); return nextHops; } return null; } static Extraroute getVpnToExtraroute(String ipPrefix, List<String> nextHopList) { return new ExtrarouteBuilder().setPrefix(ipPrefix).setNexthopIpList(nextHopList).build(); } public static List<Extraroute> getVpnExtraroutes(DataBroker broker, String vpnRd) { InstanceIdentifier<Vpn> vpnExtraRoutesId = InstanceIdentifier.builder(VpnToExtraroute.class).child(Vpn.class, new VpnKey(vpnRd)).build(); Optional<Vpn> vpnOpc = read(broker, LogicalDatastoreType.OPERATIONAL, vpnExtraRoutesId); return vpnOpc.isPresent() ? vpnOpc.get().getExtraroute() : new ArrayList<Extraroute>(); } static Adjacencies getVpnInterfaceAugmentation(List<Adjacency> nextHopList) { return new AdjacenciesBuilder().setAdjacency(nextHopList).build(); } public static InstanceIdentifier<IdPool> getPoolId(String poolName) { InstanceIdentifier.InstanceIdentifierBuilder<IdPool> idBuilder = InstanceIdentifier.builder(IdPools.class).child(IdPool.class, new IdPoolKey(poolName)); InstanceIdentifier<IdPool> id = idBuilder.build(); return id; } static InstanceIdentifier<VpnInterfaces> getVpnInterfacesIdentifier() { return InstanceIdentifier.builder(VpnInterfaces.class).build(); } static InstanceIdentifier<Interface> getInterfaceIdentifier(String interfaceName) { return InstanceIdentifier.builder(Interfaces.class) .child(Interface.class, new InterfaceKey(interfaceName)).build(); } static InstanceIdentifier<VpnToDpnList> getVpnToDpnListIdentifier(String rd, BigInteger dpnId) { return InstanceIdentifier.builder(VpnInstanceOpData.class) .child(VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(rd)) .child(VpnToDpnList.class, new VpnToDpnListKey(dpnId)).build(); } public static BigInteger getCookieArpFlow(int interfaceTag) { return VpnConstants.COOKIE_L3_BASE.add(new BigInteger("0110000", 16)).add( BigInteger.valueOf(interfaceTag)); } public static BigInteger getCookieL3(int vpnId) { return VpnConstants.COOKIE_L3_BASE.add(new BigInteger("0610000", 16)).add(BigInteger.valueOf(vpnId)); } public static String getFlowRef(BigInteger dpnId, short tableId, int ethType, int lPortTag, int arpType) { return new StringBuffer().append(VpnConstants.FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR) .append(tableId).append(NwConstants.FLOWID_SEPARATOR).append(ethType).append(lPortTag) .append(NwConstants.FLOWID_SEPARATOR).append(arpType).toString(); } public static int getUniqueId(IdManagerService idManager, String poolName, String idKey) { AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build(); try { Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput); RpcResult<AllocateIdOutput> rpcResult = result.get(); if (rpcResult.isSuccessful()) { return rpcResult.getResult().getIdValue().intValue(); } else { LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors()); } } catch (InterruptedException | ExecutionException e) { LOG.warn("Exception when getting Unique Id", e); } return 0; } public static void releaseId(IdManagerService idManager, String poolName, String idKey) { ReleaseIdInput idInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build(); try { Future<RpcResult<Void>> result = idManager.releaseId(idInput); RpcResult<Void> rpcResult = result.get(); if (!rpcResult.isSuccessful()) { LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors()); } } catch (InterruptedException | ExecutionException e) { LOG.warn("Exception when getting Unique Id for key {}", idKey, e); } } public static String getNextHopLabelKey(String rd, String prefix) { return rd + VpnConstants.SEPARATOR + prefix; } /** * Retrieves the VpnInstance name (typically the VPN Uuid) out from the * route-distinguisher * * @param broker dataBroker service reference * @param rd Route-Distinguisher * @return the VpnInstance name */ public static String getVpnNameFromRd(DataBroker broker, String rd) { VpnInstanceOpDataEntry vpnInstanceOpData = getVpnInstanceOpData(broker, rd); return (vpnInstanceOpData != null) ? vpnInstanceOpData.getVpnInstanceName() : null; } /** * Retrieves the dataplane identifier of a specific VPN, searching by its * VpnInstance name. * * @param broker dataBroker service reference * @param vpnName Name of the VPN * @return the dataplane identifier of the VPN, the VrfTag. */ public static long getVpnId(DataBroker broker, String vpnName) { InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance> id = getVpnInstanceToVpnIdIdentifier(vpnName); Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance> vpnInstance = read(broker, LogicalDatastoreType.CONFIGURATION, id); long vpnId = VpnConstants.INVALID_ID; if (vpnInstance.isPresent()) { vpnId = vpnInstance.get().getVpnId(); } return vpnId; } /** * Retrieves the VPN Route Distinguisher searching by its Vpn instance name * * @param broker dataBroker service reference * @param vpnName Name of the VPN * @return the route-distinguisher of the VPN */ public static String getVpnRd(DataBroker broker, String vpnName) { InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance> id = getVpnInstanceToVpnIdIdentifier(vpnName); Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance> vpnInstance = read(broker, LogicalDatastoreType.CONFIGURATION, id); String rd = null; if (vpnInstance.isPresent()) { rd = vpnInstance.get().getVrfId(); } return rd; } /** * Get VPN Route Distinguisher from VPN Instance Configuration * * @param broker dataBroker service reference * @param vpnName Name of the VPN * @return the route-distinguisher of the VPN */ public static String getVpnRdFromVpnInstanceConfig(DataBroker broker, String vpnName) { InstanceIdentifier<VpnInstance> id = InstanceIdentifier.builder(VpnInstances.class) .child(VpnInstance.class, new VpnInstanceKey(vpnName)).build(); Optional<VpnInstance> vpnInstance = VpnUtil.read(broker, LogicalDatastoreType.CONFIGURATION, id); String rd = null; if (vpnInstance.isPresent()) { VpnInstance instance = vpnInstance.get(); VpnAfConfig config = instance.getIpv4Family(); rd = config.getRouteDistinguisher(); } return rd; } /** * Remove from MDSAL all those VrfEntries in a VPN that have an specific RouteOrigin * * @param broker dataBroker service reference * @param rd Route Distinguisher * @param origin Origin of the Routes to be removed (see {@link RouteOrigin}) */ public static void removeVrfEntriesByOrigin(DataBroker broker, String rd, RouteOrigin origin) { InstanceIdentifier<VrfTables> vpnVrfTableIid = InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd)).build(); Optional<VrfTables> vrfTablesOpc = read(broker, LogicalDatastoreType.CONFIGURATION, vpnVrfTableIid); if (vrfTablesOpc.isPresent()) { VrfTables vrfTables = vrfTablesOpc.get(); WriteTransaction tx = broker.newWriteOnlyTransaction(); for (VrfEntry vrfEntry : vrfTables.getVrfEntry()) { if (origin == RouteOrigin.value(vrfEntry.getOrigin())) { tx.delete(LogicalDatastoreType.CONFIGURATION, vpnVrfTableIid.child(VrfEntry.class, vrfEntry.getKey())); } } tx.submit(); } } public static List<VrfEntry> findVrfEntriesByNexthop(DataBroker broker, String rd, String nexthop) { InstanceIdentifier<VrfTables> vpnVrfTableIid = InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd)).build(); Optional<VrfTables> vrfTablesOpc = read(broker, LogicalDatastoreType.CONFIGURATION, vpnVrfTableIid); List<VrfEntry> matches = new ArrayList<VrfEntry>(); if (vrfTablesOpc.isPresent()) { VrfTables vrfTables = vrfTablesOpc.get(); for (VrfEntry vrfEntry : vrfTables.getVrfEntry()) { if (vrfEntry.getNextHopAddressList() != null && vrfEntry.getNextHopAddressList().contains(nexthop)) { matches.add(vrfEntry); } } } return matches; } public static void removeVrfEntries(DataBroker broker, String rd, List<VrfEntry> vrfEntries) { InstanceIdentifier<VrfTables> vpnVrfTableIid = InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd)).build(); WriteTransaction tx = broker.newWriteOnlyTransaction(); for (VrfEntry vrfEntry : vrfEntries) { tx.delete(LogicalDatastoreType.CONFIGURATION, vpnVrfTableIid.child(VrfEntry.class, vrfEntry.getKey())); } tx.submit(); } static org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance getVpnInstanceToVpnId(String vpnName, long vpnId, String rd) { return new VpnInstanceBuilder().setVpnId(vpnId).setVpnInstanceName(vpnName).setVrfId(rd).build(); } static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance> getVpnInstanceToVpnIdIdentifier(String vpnName) { return InstanceIdentifier.builder(VpnInstanceToVpnId.class) .child(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstanceKey(vpnName)).build(); } static RouterInterface getConfiguredRouterInterface(DataBroker broker, String interfaceName) { Optional<RouterInterface> optRouterInterface = read(broker, LogicalDatastoreType.CONFIGURATION, VpnUtil.getRouterInterfaceId(interfaceName)); if(optRouterInterface.isPresent()) { return optRouterInterface.get(); } return null; } static org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds getVpnIdToVpnInstance(long vpnId, String vpnName, String rd, boolean isExternalVpn) { return new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIdsBuilder() .setVpnId(vpnId).setVpnInstanceName(vpnName).setVrfId(rd).setExternalVpn(isExternalVpn).build(); } public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds> getVpnIdToVpnInstanceIdentifier(long vpnId) { return InstanceIdentifier.builder(VpnIdToVpnInstance.class) .child(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIdsKey(Long.valueOf(vpnId))).build(); } /** * Retrieves the Vpn Name searching by its VPN Tag. * * @param broker dataBroker service reference * @param vpnId Dataplane identifier of the VPN * @return the Vpn instance name */ public static String getVpnName(DataBroker broker, long vpnId) { InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds> id = getVpnIdToVpnInstanceIdentifier(vpnId); Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds> vpnInstance = read(broker, LogicalDatastoreType.CONFIGURATION, id); String vpnName = null; if (vpnInstance.isPresent()) { vpnName = vpnInstance.get().getVpnInstanceName(); } return vpnName; } public static InstanceIdentifier<VpnInstanceOpDataEntry> getVpnInstanceOpDataIdentifier(String rd) { return InstanceIdentifier.builder(VpnInstanceOpData.class) .child(VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(rd)).build(); } static InstanceIdentifier<RouterInterface> getRouterInterfaceId(String interfaceName) { return InstanceIdentifier.builder(RouterInterfaces.class) .child(RouterInterface.class, new RouterInterfaceKey(interfaceName)).build(); } static RouterInterface getRouterInterface(String interfaceName, String routerName) { return new RouterInterfaceBuilder().setKey(new RouterInterfaceKey(interfaceName)) .setInterfaceName(interfaceName).setRouterName(routerName).build(); } public static VpnInstanceOpDataEntry getVpnInstanceOpData(DataBroker broker, String rd) { InstanceIdentifier<VpnInstanceOpDataEntry> id = VpnUtil.getVpnInstanceOpDataIdentifier(rd); return read(broker, LogicalDatastoreType.OPERATIONAL, id).orNull(); } static VpnInstanceOpDataEntry getVpnInstanceOpDataFromCache(DataBroker broker, String rd) { InstanceIdentifier<VpnInstanceOpDataEntry> id = VpnUtil.getVpnInstanceOpDataIdentifier(rd); return (VpnInstanceOpDataEntry) DataStoreCache.get(VpnConstants.VPN_OP_INSTANCE_CACHE_NAME, id, rd, broker, false); } static VpnInterface getConfiguredVpnInterface(DataBroker broker, String interfaceName) { InstanceIdentifier<VpnInterface> interfaceId = getVpnInterfaceIdentifier(interfaceName); Optional<VpnInterface> configuredVpnInterface = read(broker, LogicalDatastoreType.CONFIGURATION, interfaceId); if (configuredVpnInterface.isPresent()) { return configuredVpnInterface.get(); } return null; } static String getNeutronRouterFromInterface(DataBroker broker, String interfaceName) { InstanceIdentifier.InstanceIdentifierBuilder<RouterInterfacesMap> idBuilder = InstanceIdentifier.builder(RouterInterfacesMap.class); InstanceIdentifier<RouterInterfacesMap> id = idBuilder.build(); Optional<RouterInterfacesMap> RouterInterfacesMap = MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, id); if (RouterInterfacesMap.isPresent()) { List<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.router.interfaces.map.RouterInterfaces> rtrInterfaces = RouterInterfacesMap.get().getRouterInterfaces(); for (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.router.interfaces.map.RouterInterfaces rtrInterface : rtrInterfaces) { List<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.router.interfaces.map.router.interfaces.Interfaces> rtrIfc = rtrInterface.getInterfaces(); for(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.router.interfaces.map.router.interfaces.Interfaces ifc : rtrIfc) { if (ifc.getInterfaceId().equals(interfaceName)) { return rtrInterface.getRouterId().getValue(); } } } } return null; } static VpnInterface getOperationalVpnInterface(DataBroker broker, String interfaceName) { InstanceIdentifier<VpnInterface> interfaceId = getVpnInterfaceIdentifier(interfaceName); Optional<VpnInterface> operationalVpnInterface = read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId); if (operationalVpnInterface.isPresent()) { return operationalVpnInterface.get(); } return null; } static boolean isVpnInterfaceConfigured(DataBroker broker, String interfaceName) { InstanceIdentifier<VpnInterface> interfaceId = getVpnInterfaceIdentifier(interfaceName); Optional<VpnInterface> configuredVpnInterface = read(broker, LogicalDatastoreType.CONFIGURATION, interfaceId); if (configuredVpnInterface.isPresent()) { return true; } return false; } static boolean isInterfaceAssociatedWithVpn(DataBroker broker, String vpnName, String interfaceName) { InstanceIdentifier<VpnInterface> interfaceId = getVpnInterfaceIdentifier(interfaceName); Optional<VpnInterface> optConfiguredVpnInterface = read(broker, LogicalDatastoreType.CONFIGURATION, interfaceId); if (optConfiguredVpnInterface.isPresent()) { String configuredVpnName = optConfiguredVpnInterface.get().getVpnInstanceName(); if ((configuredVpnName != null) && (configuredVpnName.equalsIgnoreCase(vpnName))) { return true; } } return false; } static String getIpPrefix(String prefix) { String prefixValues[] = prefix.split("/"); if (prefixValues.length == 1) { prefix = prefix + PREFIX_SEPARATOR + DEFAULT_PREFIX_LENGTH; } return prefix; } static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() { @Override public void onSuccess(Void result) { LOG.debug("Success in Datastore operation"); } @Override public void onFailure(Throwable error) { LOG.error("Error in Datastore operation", error); } ; }; public static <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) { ReadOnlyTransaction tx = broker.newReadOnlyTransaction(); Optional<T> result = Optional.absent(); try { result = tx.read(datastoreType, path).get(); } catch (Exception e) { throw new RuntimeException(e); } finally { tx.close(); } return result; } public static <T extends DataObject> void asyncUpdate(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path, T data) { asyncUpdate(broker, datastoreType, path, data, DEFAULT_CALLBACK); } public static <T extends DataObject> void asyncUpdate(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) { WriteTransaction tx = broker.newWriteOnlyTransaction(); tx.merge(datastoreType, path, data, true); Futures.addCallback(tx.submit(), callback); } public static <T extends DataObject> void asyncWrite(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path, T data) { asyncWrite(broker, datastoreType, path, data, DEFAULT_CALLBACK); } public static <T extends DataObject> void asyncWrite(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) { WriteTransaction tx = broker.newWriteOnlyTransaction(); tx.put(datastoreType, path, data, true); Futures.addCallback(tx.submit(), callback); } public static <T extends DataObject> void tryDelete(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) { try { delete(broker, datastoreType, path, DEFAULT_CALLBACK); } catch ( SchemaValidationFailedException sve ) { LOG.info("Could not delete {}. SchemaValidationFailedException: {}", path, sve.getMessage()); } catch ( Exception e) { LOG.info("Could not delete {}. Unhandled error: {}", path, e.getMessage()); } } public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) { delete(broker, datastoreType, path, DEFAULT_CALLBACK); } public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path, FutureCallback<Void> callback) { WriteTransaction tx = broker.newWriteOnlyTransaction(); tx.delete(datastoreType, path); Futures.addCallback(tx.submit(), callback); } public static <T extends DataObject> void syncWrite(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path, T data) { WriteTransaction tx = broker.newWriteOnlyTransaction(); tx.put(datastoreType, path, data, true); CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit(); try { futures.get(); } catch (InterruptedException | ExecutionException e) { LOG.error("Error writing to datastore (path, data) : ({}, {})", path, data); throw new RuntimeException(e.getMessage()); } } public static <T extends DataObject> void syncUpdate(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path, T data) { WriteTransaction tx = broker.newWriteOnlyTransaction(); tx.merge(datastoreType, path, data, true); CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit(); try { futures.get(); } catch (InterruptedException | ExecutionException e) { LOG.error("Error writing to datastore (path, data) : ({}, {})", path, data); throw new RuntimeException(e.getMessage()); } } public static long getRemoteBCGroup(long elanTag) { return VpnConstants.ELAN_GID_MIN + ((elanTag % VpnConstants.ELAN_GID_MIN) * 2); } // interface-index-tag operational container public static IfIndexInterface getInterfaceInfoByInterfaceTag(DataBroker broker, long interfaceTag) { InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag); Optional<IfIndexInterface> existingInterfaceInfo = VpnUtil.read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId); if (existingInterfaceInfo.isPresent()) { return existingInterfaceInfo.get(); } return null; } private static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) { return InstanceIdentifier.builder(IfIndexesInterfaceMap.class).child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build(); } public static ElanTagName getElanInfoByElanTag(DataBroker broker, long elanTag) { InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag); Optional<ElanTagName> existingElanInfo = VpnUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanId); if (existingElanInfo.isPresent()) { return existingElanInfo.get(); } return null; } private static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) { return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag)).build(); } /** * Returns the Path identifier to reach a specific interface in a specific DPN in a given VpnInstance * * @param vpnRd Route-Distinguisher of the VpnInstance * @param dpnId Id of the DPN where the interface is * @param ifaceName Interface name * @return the Instance Identifier */ public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn .instance.op.data.vpn.instance.op.data.entry.vpn.to.dpn.list.VpnInterfaces> getVpnToDpnInterfacePath(String vpnRd, BigInteger dpnId, String ifaceName) { return InstanceIdentifier.builder(VpnInstanceOpData.class) .child(VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(vpnRd)) .child(VpnToDpnList.class, new VpnToDpnListKey(dpnId)) .child(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn .instance.op.data.vpn.instance.op.data.entry.vpn.to.dpn.list.VpnInterfaces.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn .instance.op.data.vpn.instance.op.data.entry.vpn.to.dpn.list.VpnInterfacesKey(ifaceName)) .build(); } public static void removePrefixToInterfaceForVpnId(DataBroker broker, long vpnId, WriteTransaction writeTxn) { try { // Clean up PrefixToInterface Operational DS if (writeTxn != null) { writeTxn.delete(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.builder(PrefixToInterface.class).child( VpnIds.class, new VpnIdsKey(vpnId)).build()); } else { delete(broker, LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.builder(PrefixToInterface.class).child(VpnIds.class, new VpnIdsKey(vpnId)).build(), DEFAULT_CALLBACK); } } catch (Exception e) { LOG.error("Exception during cleanup of PrefixToInterface for VPN ID {}", vpnId, e); } } public static void removeVpnExtraRouteForVpn(DataBroker broker, String vpnName, WriteTransaction writeTxn) { try { // Clean up VPNExtraRoutes Operational DS if (writeTxn != null) { writeTxn.delete(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.builder(VpnToExtraroute.class).child(Vpn.class, new VpnKey(vpnName)).build()); } else { delete(broker, LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.builder(VpnToExtraroute.class).child(Vpn.class, new VpnKey(vpnName)).build(), DEFAULT_CALLBACK); } } catch (Exception e) { LOG.error("Exception during cleanup of VPNToExtraRoute for VPN {}", vpnName, e); } } public static void removeVpnOpInstance(DataBroker broker, String vpnName, WriteTransaction writeTxn) { try { // Clean up VPNInstanceOpDataEntry if (writeTxn != null) { writeTxn.delete(LogicalDatastoreType.OPERATIONAL, getVpnInstanceOpDataIdentifier(vpnName)); } else { delete(broker, LogicalDatastoreType.OPERATIONAL, getVpnInstanceOpDataIdentifier(vpnName), DEFAULT_CALLBACK); } } catch (Exception e) { LOG.error("Exception during cleanup of VPNInstanceOpDataEntry for VPN {}", vpnName, e); } } public static void removeVpnInstanceToVpnId(DataBroker broker, String vpnName, WriteTransaction writeTxn) { try { if (writeTxn != null) { writeTxn.delete(LogicalDatastoreType.CONFIGURATION, getVpnInstanceToVpnIdIdentifier(vpnName)); } else { delete(broker, LogicalDatastoreType.CONFIGURATION, getVpnInstanceToVpnIdIdentifier(vpnName), DEFAULT_CALLBACK); } } catch (Exception e) { LOG.error("Exception during clean up of VpnInstanceToVpnId for VPN {}", vpnName, e); } } public static void removeVpnIdToVpnInstance(DataBroker broker, long vpnId, WriteTransaction writeTxn) { try { if (writeTxn != null) { writeTxn.delete(LogicalDatastoreType.CONFIGURATION, getVpnIdToVpnInstanceIdentifier(vpnId)); } else { delete(broker, LogicalDatastoreType.CONFIGURATION, getVpnIdToVpnInstanceIdentifier(vpnId), DEFAULT_CALLBACK); } } catch (Exception e) { LOG.error("Exception during clean up of VpnIdToVpnInstance for VPNID {}", vpnId, e); } } public static void removeVrfTableForVpn(DataBroker broker, String vpnName, WriteTransaction writeTxn) { // Clean up FIB Entries Config DS try { if (writeTxn != null) { writeTxn.delete(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(vpnName)).build()); } else { delete(broker, LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(vpnName)).build(), DEFAULT_CALLBACK); } } catch (Exception e) { LOG.error("Exception during clean up of VrfTable from FIB for VPN {}", vpnName, e); } } public static void removeL3nexthopForVpnId(DataBroker broker, long vpnId, WriteTransaction writeTxn) { try { // Clean up L3NextHop Operational DS if (writeTxn != null) { writeTxn.delete(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.builder(L3nexthop.class).child(VpnNexthops.class, new VpnNexthopsKey(vpnId)).build()); } else { delete(broker, LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.builder(L3nexthop.class).child(VpnNexthops.class, new VpnNexthopsKey(vpnId)).build(), DEFAULT_CALLBACK); } } catch (Exception e) { LOG.error("Exception during cleanup of L3NextHop for VPN ID {}", vpnId, e); } } public static void scheduleVpnInterfaceForRemoval(DataBroker broker,String interfaceName, BigInteger dpnId, String vpnInstanceName, Boolean isScheduledToRemove, WriteTransaction writeOperTxn){ InstanceIdentifier<VpnInterface> interfaceId = VpnUtil.getVpnInterfaceIdentifier(interfaceName); VpnInterface interfaceToUpdate = new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(interfaceName)).setName(interfaceName) .setDpnId(dpnId).setVpnInstanceName(vpnInstanceName).setScheduledForRemove(isScheduledToRemove).build(); if (writeOperTxn != null) { writeOperTxn.merge(LogicalDatastoreType.OPERATIONAL, interfaceId, interfaceToUpdate, true); } else { VpnUtil.syncUpdate(broker, LogicalDatastoreType.OPERATIONAL, interfaceId, interfaceToUpdate); } } protected static void createLearntVpnVipToPort(DataBroker broker, String vpnName, String fixedIp, String portName, String macAddress) { synchronized ((vpnName + fixedIp).intern()) { InstanceIdentifier<LearntVpnVipToPort> id = buildLearntVpnVipToPortIdentifier(vpnName, fixedIp); LearntVpnVipToPortBuilder builder = new LearntVpnVipToPortBuilder().setKey( new LearntVpnVipToPortKey(fixedIp, vpnName)).setVpnName(vpnName).setPortFixedip(fixedIp).setPortName (portName).setMacAddress(macAddress.toLowerCase()); MDSALUtil.syncWrite(broker, LogicalDatastoreType.OPERATIONAL, id, builder.build()); LOG.debug("ARP learned for fixedIp: {}, vpn {}, interface {}, mac {}, isSubnetIp {} added to " + "VpnPortipToPort DS", fixedIp, vpnName, portName, macAddress); } } private static InstanceIdentifier<LearntVpnVipToPort> buildLearntVpnVipToPortIdentifier(String vpnName, String fixedIp) { InstanceIdentifier<LearntVpnVipToPort> id = InstanceIdentifier.builder(LearntVpnVipToPortData.class).child (LearntVpnVipToPort.class, new LearntVpnVipToPortKey(fixedIp, vpnName)).build(); return id; } protected static void removeLearntVpnVipToPort(DataBroker broker, String vpnName, String fixedIp) { synchronized ((vpnName + fixedIp).intern()) { InstanceIdentifier<LearntVpnVipToPort> id = buildLearntVpnVipToPortIdentifier(vpnName, fixedIp); MDSALUtil.syncDelete(broker, LogicalDatastoreType.OPERATIONAL, id); LOG.debug("Delete learned ARP for fixedIp: {}, vpn {} removed from VpnPortipToPort DS", fixedIp, vpnName); } } static InstanceIdentifier<VpnPortipToPort> buildVpnPortipToPortIdentifier(String vpnName, String fixedIp) { InstanceIdentifier<VpnPortipToPort> id = InstanceIdentifier.builder(NeutronVpnPortipPortData.class).child (VpnPortipToPort.class, new VpnPortipToPortKey(fixedIp, vpnName)).build(); return id; } static VpnPortipToPort getNeutronPortFromVpnPortFixedIp(DataBroker broker, String vpnName, String fixedIp) { InstanceIdentifier id = buildVpnPortipToPortIdentifier(vpnName, fixedIp); Optional<VpnPortipToPort> vpnPortipToPortData = read(broker, LogicalDatastoreType.CONFIGURATION, id); if (vpnPortipToPortData.isPresent()) { return (vpnPortipToPortData.get()); } return null; } static LearntVpnVipToPort getLearntVpnVipToPort(DataBroker broker, String vpnName, String fixedIp) { InstanceIdentifier id = buildLearntVpnVipToPortIdentifier(vpnName, fixedIp); Optional<LearntVpnVipToPort> learntVpnVipToPort = read(broker, LogicalDatastoreType.OPERATIONAL, id); if (learntVpnVipToPort.isPresent()) { return (learntVpnVipToPort.get()); } return null; } public static List<BigInteger> getDpnsOnVpn(DataBroker dataBroker, String vpnInstanceName) { List<BigInteger> result = new ArrayList<BigInteger>(); String rd = getVpnRd(dataBroker, vpnInstanceName); if ( rd == null ) { LOG.debug("Could not find Route-Distinguisher for VpnName={}", vpnInstanceName); return result; } VpnInstanceOpDataEntry vpnInstanceOpData = getVpnInstanceOpData(dataBroker, rd); if ( vpnInstanceOpData == null ) { LOG.debug("Could not find OpState for VpnName={}", vpnInstanceName); return result; } List<VpnToDpnList> vpnToDpnList = vpnInstanceOpData.getVpnToDpnList(); if ( vpnToDpnList == null ) { LOG.debug("Could not find DPN footprint for VpnName={}", vpnInstanceName); return result; } for ( VpnToDpnList vpnToDpn : vpnToDpnList) { result.add(vpnToDpn.getDpnId()); } return result; } static String getAssociatedExternalNetwork(DataBroker dataBroker, String routerId) { InstanceIdentifier<Routers> id = buildRouterIdentifier(routerId); Optional<Routers> routerData = read(dataBroker, LogicalDatastoreType.CONFIGURATION, id); if (routerData.isPresent()) { Uuid networkId = routerData.get().getNetworkId(); if(networkId != null) { return networkId.getValue(); } } return null; } static InstanceIdentifier<Routers> buildRouterIdentifier(String routerId) { InstanceIdentifier<Routers> routerInstanceIndentifier = InstanceIdentifier.builder(ExtRouters.class).child (Routers.class, new RoutersKey(routerId)).build(); return routerInstanceIndentifier; } static Networks getExternalNetwork(DataBroker dataBroker, Uuid networkId) { InstanceIdentifier<Networks> netsIdentifier = InstanceIdentifier.builder(ExternalNetworks.class) .child(Networks.class, new NetworksKey(networkId)).build(); Optional<Networks> optionalNets = VpnUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION, netsIdentifier); return optionalNets.isPresent() ? optionalNets.get() : null; } static Uuid getExternalNetworkVpnId(DataBroker dataBroker, Uuid networkId) { Networks extNetwork = getExternalNetwork(dataBroker, networkId); return extNetwork != null ? extNetwork.getVpnid() : null; } static List<Uuid> getExternalNetworkRouterIds(DataBroker dataBroker, Uuid networkId) { Networks extNetwork = getExternalNetwork(dataBroker, networkId); return extNetwork != null ? extNetwork.getRouterIds() : null; } static Routers getExternalRouter(DataBroker dataBroker, String routerId) { InstanceIdentifier<Routers> id = InstanceIdentifier.builder(ExtRouters.class) .child(Routers.class, new RoutersKey(routerId)).build(); Optional<Routers> routerData = read(dataBroker, LogicalDatastoreType.CONFIGURATION, id); return routerData.isPresent() ? routerData.get() : null; } static Optional<List<String>> getAllSubnetGatewayMacAddressesforVpn(DataBroker broker, String vpnName) { Optional<List<String>> macAddressesOptional = Optional.absent(); List<String> macAddresses = new ArrayList<>(); Optional<Subnetmaps> subnetMapsData = read(broker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath()); if (subnetMapsData.isPresent()) { List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap(); if (subnetMapList != null && !subnetMapList.isEmpty()) { for (Subnetmap subnet: subnetMapList) { if (subnet.getVpnId() !=null && subnet.getVpnId().equals(Uuid.getDefaultInstance(vpnName))) { String routerIntfMacAddress = subnet.getRouterIntfMacAddress(); if (routerIntfMacAddress != null && !routerIntfMacAddress.isEmpty()) { macAddresses.add(subnet.getRouterIntfMacAddress()); } } } } if (!macAddresses.isEmpty()) { return Optional.of(macAddresses); } } return macAddressesOptional; } static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() { return InstanceIdentifier.create(Subnetmaps.class); } static void setupSubnetMacIntoVpnInstance(DataBroker dataBroker, IMdsalApiManager mdsalManager, String vpnName, String srcMacAddress, BigInteger dpnId, WriteTransaction writeTx, int addOrRemove) { long vpnId = getVpnId(dataBroker, vpnName); if (dpnId.equals(BigInteger.ZERO)) { /* Apply the MAC on all DPNs in a VPN */ List<BigInteger> dpIds = getDpnsOnVpn(dataBroker, vpnName); if (dpIds == null || dpIds.isEmpty()) { return; } for (BigInteger dpId : dpIds) { addGwMacIntoTx(mdsalManager, srcMacAddress, writeTx, addOrRemove, vpnId, dpId); } } else { addGwMacIntoTx(mdsalManager, srcMacAddress, writeTx, addOrRemove, vpnId, dpnId); } } static void addGwMacIntoTx(IMdsalApiManager mdsalManager, String srcMacAddress, WriteTransaction writeTx, int addOrRemove, long vpnId, BigInteger dpId) { FlowEntity flowEntity = buildL3vpnGatewayFlow(dpId, srcMacAddress, vpnId); if (addOrRemove == NwConstants.ADD_FLOW) { mdsalManager.addFlowToTx(flowEntity, writeTx); } else { mdsalManager.removeFlowToTx(flowEntity, writeTx); } } public static FlowEntity buildL3vpnGatewayFlow(BigInteger dpId, String gwMacAddress, long vpnId) { List<MatchInfo> mkMatches = new ArrayList<MatchInfo>(); mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] { MetaDataUtil.getVpnIdMetadata(vpnId), MetaDataUtil.METADATA_MASK_VRFID })); mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { gwMacAddress })); List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>(); mkInstructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { NwConstants.L3_FIB_TABLE })); String flowId = getL3VpnGatewayFlowRef(NwConstants.L3_GW_MAC_TABLE, dpId, vpnId, gwMacAddress); FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.L3_GW_MAC_TABLE, flowId, 20, flowId, 0, 0, NwConstants.COOKIE_L3_GW_MAC_TABLE, mkMatches, mkInstructions); return flowEntity; } private static String getL3VpnGatewayFlowRef(short l3GwMacTable, BigInteger dpId, long vpnId, String gwMacAddress) { return gwMacAddress+NwConstants.FLOWID_SEPARATOR+vpnId+NwConstants.FLOWID_SEPARATOR+dpId+NwConstants.FLOWID_SEPARATOR+l3GwMacTable; } public static void lockSubnet(LockManagerService lockManager, String subnetId) { TryLockInput input = new TryLockInputBuilder().setLockName(subnetId).setTime(3000L).setTimeUnit(TimeUnits.Milliseconds).build(); Future<RpcResult<Void>> result = lockManager.tryLock(input); String errMsg = "Unable to getLock for subnet " + subnetId; try { if ((result != null) && (result.get().isSuccessful())) { LOG.debug("Acquired lock for {}", subnetId); } else { throw new RuntimeException(errMsg); } } catch (InterruptedException | ExecutionException e) { LOG.error(errMsg); throw new RuntimeException(errMsg, e.getCause()); } } public static void unlockSubnet(LockManagerService lockManager, String subnetId) { UnlockInput input = new UnlockInputBuilder().setLockName(subnetId).build(); Future<RpcResult<Void>> result = lockManager.unlock(input); try { if ((result != null) && (result.get().isSuccessful())) { LOG.debug("Unlocked {}", subnetId); } else { LOG.debug("Unable to unlock subnet {}", subnetId); } } catch (InterruptedException | ExecutionException e) { LOG.error("Unable to unlock subnet {}", subnetId); throw new RuntimeException(String.format("Unable to unlock subnetId %s", subnetId), e.getCause()); } } static Optional<IpAddress> getGatewayIpAddressFromInterface(String srcInterface, INeutronVpnManager neutronVpnService, DataBroker dataBroker) { Optional <IpAddress> gatewayIp = Optional.absent(); if (neutronVpnService != null) { //TODO(Gobinath): Need to fix this as assuming port will belong to only one Subnet would be incorrect" Port port = neutronVpnService.getNeutronPort(srcInterface); if (port != null && port.getFixedIps() != null && port.getFixedIps().get(0) != null && port.getFixedIps().get(0).getSubnetId() != null) { gatewayIp = Optional.of(neutronVpnService.getNeutronSubnet(port.getFixedIps().get(0).getSubnetId()).getGatewayIp()); } } else { LOG.debug("neutron vpn service is not configured"); } return gatewayIp; } static Optional<String> getGWMacAddressFromInterface(MacEntry macEntry, IpAddress gatewayIp, DataBroker dataBroker, OdlInterfaceRpcService interfaceRpc) { Optional <String> gatewayMac = Optional.absent(); long vpnId = getVpnId(dataBroker, macEntry.getVpnName()); InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds> vpnIdsInstanceIdentifier = VpnUtil.getVpnIdToVpnInstanceIdentifier(vpnId); Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds> vpnIdsOptional = VpnUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION, vpnIdsInstanceIdentifier); if (!vpnIdsOptional.isPresent()) { LOG.trace("VPN {} not configured", vpnId); return gatewayMac; } VpnPortipToPort vpnTargetIpToPort = VpnUtil.getNeutronPortFromVpnPortFixedIp(dataBroker, macEntry.getVpnName(), gatewayIp.getIpv4Address().getValue()); if (vpnTargetIpToPort != null && vpnTargetIpToPort.isSubnetIp()) { gatewayMac = Optional.of(vpnTargetIpToPort.getMacAddress()); } else { org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds vpnIds = vpnIdsOptional.get(); if(vpnIds.isExternalVpn()) { gatewayMac = InterfaceUtils.getMacAddressForInterface(dataBroker, macEntry.getInterfaceName()); } } return gatewayMac; } public static void runOnlyInLeaderNode(EntityOwnershipService entityOwnershipService, Runnable job) { runOnlyInLeaderNode(entityOwnershipService, job, ""); } public static void runOnlyInLeaderNode(EntityOwnershipService entityOwnershipService, final Runnable job, final String jobDescription) { ListenableFuture<Boolean> checkEntityOwnerFuture = ClusteringUtils.checkNodeEntityOwner( entityOwnershipService, VpnConstants.ARP_MONITORING_ENTITY, VpnConstants.ARP_MONITORING_ENTITY); Futures.addCallback(checkEntityOwnerFuture, new FutureCallback<Boolean>() { @Override public void onSuccess(Boolean isOwner) { if (isOwner) { job.run(); } else { LOG.trace("job is not run as i m not cluster owner desc :{} ", jobDescription); } } @Override public void onFailure(Throwable error) { LOG.error("Failed to identity cluster owner ", error); } }); } public static boolean isVpnIntfPresentInVpnToDpnList(DataBroker broker, VpnInterface vpnInterface) { BigInteger dpnId = vpnInterface.getDpnId(); String rd = VpnUtil.getVpnRd(broker, vpnInterface.getVpnInstanceName()); VpnInstanceOpDataEntry vpnInstanceOpData = VpnUtil.getVpnInstanceOpDataFromCache(broker, rd); if (vpnInstanceOpData != null) { List<VpnToDpnList> dpnToVpns = vpnInstanceOpData.getVpnToDpnList(); if (dpnToVpns!= null) { for (VpnToDpnList dpn :dpnToVpns) { if (dpn.getDpnId().equals(dpnId)) { if (dpn.getVpnInterfaces().contains(vpnInterface.getName())) { return true; } else { return false; } } } } } return false; } public static void setupGwMacIfExternalVpn(DataBroker dataBroker, IMdsalApiManager mdsalManager, BigInteger dpnId, String interfaceName, long vpnId, WriteTransaction writeInvTxn, int addOrRemove) { InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds> vpnIdsInstanceIdentifier = getVpnIdToVpnInstanceIdentifier(vpnId); Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds> vpnIdsOptional = read(dataBroker, LogicalDatastoreType.CONFIGURATION, vpnIdsInstanceIdentifier); if (vpnIdsOptional.isPresent() && vpnIdsOptional.get().isExternalVpn()) { Optional<String> gwMacAddressOptional = InterfaceUtils.getMacAddressForInterface(dataBroker, interfaceName); if (!gwMacAddressOptional.isPresent()) { LOG.error("Failed to get gwMacAddress for interface {}", interfaceName); return; } String gwMacAddress = gwMacAddressOptional.get(); FlowEntity flowEntity = VpnUtil.buildL3vpnGatewayFlow(dpnId, gwMacAddress, vpnId); if (addOrRemove == NwConstants.ADD_FLOW) { mdsalManager.addFlowToTx(flowEntity, writeInvTxn); } else if (addOrRemove == NwConstants.DEL_FLOW) { mdsalManager.removeFlowToTx(flowEntity, writeInvTxn); } } } public static Optional<VpnPortipToPort> getRouterInterfaceForVpnInterface(DataBroker dataBroker, String interfaceName, String vpnName, Uuid subnetUuid) { Optional<VpnPortipToPort> gwPortOptional = Optional.absent(); if (subnetUuid != null) { final Optional<String> gatewayIp = getVpnSubnetGatewayIp(dataBroker, subnetUuid); if (gatewayIp.isPresent()) { String gwIp = gatewayIp.get(); gwPortOptional = Optional.fromNullable(getNeutronPortFromVpnPortFixedIp(dataBroker, vpnName, gwIp)); } } return gwPortOptional; } public static Optional<String> getVpnSubnetGatewayIp(DataBroker dataBroker, final Uuid subnetUuid) { Optional<String> gwIpAddress = Optional.absent(); final SubnetKey subnetkey = new SubnetKey(subnetUuid); final InstanceIdentifier<Subnet> subnetidentifier = InstanceIdentifier.create(Neutron.class) .child(Subnets.class) .child(Subnet.class, subnetkey); final Optional<Subnet> subnet = read(dataBroker, LogicalDatastoreType.CONFIGURATION, subnetidentifier); if (subnet.isPresent()) { Class<? extends IpVersionBase> ipVersionBase = subnet.get().getIpVersion(); if (ipVersionBase.equals(IpVersionV4.class)) { LOG.trace("Obtained subnet {} for vpn interface", subnet.get().getUuid().getValue()); gwIpAddress = Optional.of(subnet.get().getGatewayIp().getIpv4Address().getValue()); return gwIpAddress; } } return gwIpAddress; } public static RouterToNaptSwitch getRouterToNaptSwitch(DataBroker dataBroker, String routerName) { InstanceIdentifier<RouterToNaptSwitch> id = InstanceIdentifier.builder(NaptSwitches.class) .child(RouterToNaptSwitch.class, new RouterToNaptSwitchKey(routerName)).build(); Optional<RouterToNaptSwitch> routerToNaptSwitchData = read(dataBroker, LogicalDatastoreType.CONFIGURATION, id); return routerToNaptSwitchData.isPresent() ? routerToNaptSwitchData.get() : null; } public static BigInteger getPrimarySwitchForRouter(DataBroker dataBroker, String routerName) { RouterToNaptSwitch routerToNaptSwitch = getRouterToNaptSwitch(dataBroker, routerName); return routerToNaptSwitch != null ? routerToNaptSwitch.getPrimarySwitchId() : null; } }
package com.chiralbehaviors.CoRE.phantasm.model; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import com.chiralbehaviors.CoRE.ExistentialRuleform; import com.chiralbehaviors.CoRE.Ruleform; import com.chiralbehaviors.CoRE.agency.Agency; import com.chiralbehaviors.CoRE.attribute.Attribute; import com.chiralbehaviors.CoRE.attribute.AttributeAuthorization; import com.chiralbehaviors.CoRE.attribute.AttributeValue; import com.chiralbehaviors.CoRE.location.Location; import com.chiralbehaviors.CoRE.meta.Aspect; import com.chiralbehaviors.CoRE.meta.Model; import com.chiralbehaviors.CoRE.meta.NetworkedModel; import com.chiralbehaviors.CoRE.network.NetworkAuthorization; import com.chiralbehaviors.CoRE.network.NetworkRuleform; import com.chiralbehaviors.CoRE.network.XDomainNetworkAuthorization; import com.chiralbehaviors.CoRE.product.Product; import com.chiralbehaviors.CoRE.relationship.Relationship; import com.google.common.base.Function; /** * CRUD for Phantasms. This class is the animation procedure that maintains and * mediates the Phantasm/Facet constructs in Ultrastructure. It's a bit * unwieldy, because of the type signatures required for erasure. Provides a * centralized implementation of Phantasm CRUD and the security model for such. * * @author hhildebrand * */ public class PhantasmCRUD<RuleForm extends ExistentialRuleform<RuleForm, Network>, Network extends NetworkRuleform<RuleForm>> { private final Relationship apply; private final Relationship create; private final Relationship delete; private final Relationship invoke; private final Relationship read; private final Relationship remove; private final Relationship update; protected final Model model; public PhantasmCRUD(Model model) { this.model = model; create = model.getKernel() .getCREATE(); delete = model.getKernel() .getDELETE(); invoke = model.getKernel() .getINVOKE(); read = model.getKernel() .getREAD(); remove = model.getKernel() .getREMOVE(); update = model.getKernel() .getUPDATE(); apply = model.getKernel() .getAPPLY(); } /** * Add the child to the list of children of the instance * * @param facet * @param instance * @param auth * @param child */ public RuleForm addChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, RuleForm child) { if (instance == null) { return null; } cast(child, auth); NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } networkedModel.link(instance, model.getEntityManager() .getReference(Relationship.class, auth.getChildRelationship() .getId()), child, model.getCurrentPrincipal() .getPrincipal()); return instance; } public RuleForm addChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, ExistentialRuleform<?, ?> child) { if (instance == null) { return null; } cast(child, auth); NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } ExistentialRuleform<?, ?> childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); if (childAuthClassification instanceof Agency) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Agency) child); } else if (childAuthClassification instanceof Location) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Location) child); } else if (childAuthClassification instanceof Product) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Product) child); } else if (childAuthClassification instanceof Relationship) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Relationship) child); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } return instance; } /** * Add the list of children to the instance * * @param facet * @param instance * @param auth * @param children */ public RuleForm addChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, List<RuleForm> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } children.stream() .filter(child -> checkREAD(child, networkedModel)) .peek(child -> cast(child, auth)) .forEach(child -> networkedModel.link(instance, model.getEntityManager() .getReference(Relationship.class, auth.getChildRelationship() .getId()), child, model.getCurrentPrincipal() .getPrincipal())); return instance; } public RuleForm addChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, List<ExistentialRuleform<?, ?>> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } ExistentialRuleform<?, ?> childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); children.stream() .filter(child -> checkREAD(child, model.getUnknownNetworkedModel(child))) .peek(child -> cast(child, auth)) .forEach(child -> { if (childAuthClassification instanceof Agency) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Agency) child); } else if (childAuthClassification instanceof Location) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Location) child); } else if (childAuthClassification instanceof Product) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Product) child); } else if (childAuthClassification instanceof Relationship) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Relationship) child); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } }); return instance; } /** * Apply the facet to the instance * * @param facet * @param instance * @return * @throws SecurityException */ @SuppressWarnings("unchecked") public RuleForm apply(NetworkAuthorization<RuleForm> facet, RuleForm instance, Function<RuleForm, RuleForm> constructor) throws SecurityException { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(facet.getClassification()); if (!networkedModel.checkFacetCapability(model.getCurrentPrincipal() .getPrincipal(), facet, getAPPLY())) { return instance; } networkedModel.initialize(instance, model.getEntityManager() .getReference(facet.getClass(), facet.getId()), model.getCurrentPrincipal() .getPrincipal()); if (!checkInvoke(facet, instance)) { return null; } return constructor.apply(instance); } @SuppressWarnings({ "rawtypes", "unchecked" }) /** * Throws ClassCastException if not an instance of the authorized facet type * * @param ruleform * @param facet */ public void cast(ExistentialRuleform ruleform, NetworkAuthorization authorization) { NetworkedModel networkedModel = model.getUnknownNetworkedModel(ruleform); if (!networkedModel.isAccessible(ruleform, authorization.getAuthorizedRelationship(), authorization.getAuthorizedParent())) { throw new ClassCastException(String.format("%s not of facet type %s:%s", ruleform, authorization.getAuthorizedRelationship() .getName(), authorization.getAuthorizedParent() .getName())); } } @SuppressWarnings({ "rawtypes", "unchecked" }) /** * Throws ClassCastException if not an instance of the to/from facet type, * depending on directionality * * @param ruleform * @param facet */ public void cast(ExistentialRuleform ruleform, XDomainNetworkAuthorization authorization) { NetworkedModel networkedModel = model.getUnknownNetworkedModel(ruleform); Relationship classifier = authorization.isForward() ? authorization.getToRelationship() : authorization.getFromRelationship(); ExistentialRuleform classification = authorization.isForward() ? authorization.getToParent() : authorization.getFromParent(); if (!networkedModel.isAccessible(ruleform, classifier, classification)) { throw new ClassCastException(String.format("%s not of facet type %s:%s", ruleform, classifier.getName(), classification.getName())); } } public boolean checkInvoke(NetworkAuthorization<RuleForm> facet, RuleForm instance) { Agency principal = model.getCurrentPrincipal() .getPrincipal(); NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); Relationship invoke = getINVOKE(); return networkedModel.checkCapability(principal, instance, invoke) && networkedModel.checkFacetCapability(principal, facet, invoke); } /** * Create a new instance of the facet * * @param facet * @param name * @param description * @return * @throws InstantiationException * @throws NoSuchMethodException * @throws SecurityException */ @SuppressWarnings("unchecked") public RuleForm createInstance(NetworkAuthorization<RuleForm> facet, String name, String description, Function<RuleForm, RuleForm> constructor) { NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(facet.getClassification()); if (!networkedModel.checkFacetCapability(model.getCurrentPrincipal() .getPrincipal(), facet, getCREATE())) { return null; } RuleForm instance; try { instance = (RuleForm) Ruleform.initializeAndUnproxy(facet.getClassification()) .getClass() .getConstructor(String.class, String.class, Agency.class) .newInstance(name, description, model.getCurrentPrincipal() .getPrincipal()); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException | NoSuchMethodException e) { throw new IllegalStateException(String.format("Cannot construct instance of existential ruleform for %s", new Aspect<RuleForm>(facet.getClassifier(), facet.getClassification())), e); } networkedModel.initialize(instance, model.getEntityManager() .getReference(facet.getClass(), facet.getId()), model.getCurrentPrincipal() .getPrincipal()); if (!checkInvoke(facet, instance)) { return null; } return constructor.apply(instance); } public Relationship getAPPLY() { return apply; } /** * Answer the attribute value of the instance * * @param facet * @param instance * @param stateAuth * * @return */ public Object getAttributeValue(NetworkAuthorization<RuleForm> facet, RuleForm instance, AttributeAuthorization<RuleForm, Network> stateAuth) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(stateAuth.getNetworkAuthorization() .getClassification()); if (!checkREAD(facet, networkedModel) || !checkREAD(stateAuth, networkedModel)) { return null; } Attribute authorizedAttribute = stateAuth.getAuthorizedAttribute(); if (authorizedAttribute.getIndexed()) { return getIndexedAttributeValue(instance, authorizedAttribute, networkedModel); } else if (authorizedAttribute.getKeyed()) { return getMappedAttributeValue(instance, authorizedAttribute, networkedModel); } Object value = networkedModel.getAttributeValue(instance, authorizedAttribute) .getValue(); return value; } /** * Answer the inferred and immediate network children of the instance * * @param facet * @param instance * @param auth * * @return */ public List<RuleForm> getChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth) { if (instance == null) { return Collections.emptyList(); } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkREAD(facet, networkedModel) || !checkREAD(auth, networkedModel)) { return Collections.emptyList(); } return networkedModel.getChildren(instance, auth.getChildRelationship()) .stream() .filter(child -> networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .collect(Collectors.toList()); } /*** * Answer the xd children of the instance * * @param facet * @param instance * @param auth * * @return */ public List<ExistentialRuleform<?, ?>> getChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth) { if (instance == null) { return Collections.emptyList(); } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkREAD(facet, networkedModel) || !checkREAD(auth, networkedModel)) { return Collections.emptyList(); } ExistentialRuleform<?, ?> childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); List<? extends ExistentialRuleform<?, ?>> result; if (childAuthClassification instanceof Agency) { result = networkedModel.getAuthorizedAgencies(instance, auth.getConnection()); } else if (childAuthClassification instanceof Location) { result = networkedModel.getAuthorizedLocations(instance, auth.getConnection()); } else if (childAuthClassification instanceof Product) { result = networkedModel.getAuthorizedProducts(instance, auth.getConnection()); } else if (childAuthClassification instanceof Relationship) { result = networkedModel.getAuthorizedRelationships(instance, auth.getConnection()); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } NetworkedModel<?, ?, ?, ?> childNetworkModel = model.getUnknownNetworkedModel(childAuthClassification); return result.stream() .filter(child -> childNetworkModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .collect(Collectors.toList()); } public Relationship getCREATE() { return create; } public Relationship getDELETE() { return delete; } /** * Answer the immediate, non inferred children of the instance * * @param facet * @param instance * @param auth * * @return */ public List<RuleForm> getImmediateChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth) { if (instance == null) { return Collections.emptyList(); } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkREAD(facet, networkedModel) || !checkREAD(auth, networkedModel)) { return Collections.emptyList(); } return networkedModel.getImmediateChildren(instance, auth.getChildRelationship()) .stream() .filter(child -> networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .collect(Collectors.toList()); } /** * Answer the list of instances of this facet. * * @param facet * @return */ public List<RuleForm> getInstances(NetworkAuthorization<RuleForm> facet) { NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(facet.getClassification()); if (!networkedModel.checkFacetCapability(model.getCurrentPrincipal() .getPrincipal(), facet, getREAD())) { return Collections.emptyList(); } return networkedModel.getChildren(facet.getClassification(), facet.getClassifier() .getInverse()) .stream() .filter(instance -> checkREAD(networkedModel, instance)) .collect(Collectors.toList()); } public Relationship getINVOKE() { return invoke; } public Model getModel() { return model; } public Relationship getREAD() { return read; } public Relationship getREMOVE() { return remove; } /** * Answer the singular network child of the instance * * @param facet * @param instance * @param auth * * @return */ public RuleForm getSingularChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkREAD(facet, networkedModel) || !checkREAD(auth, networkedModel)) { return null; } RuleForm child = networkedModel.getImmediateChild(instance, auth.getChildRelationship()); return checkREAD(child, networkedModel) ? child : null; } /** * Answer the singular xd child of the instance * * @param facet * @param instance * @param auth * * @return */ public ExistentialRuleform<?, ?> getSingularChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkREAD(facet, networkedModel) || !checkREAD(auth, networkedModel)) { return null; } @SuppressWarnings("rawtypes") ExistentialRuleform childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); @SuppressWarnings("rawtypes") ExistentialRuleform child; if (childAuthClassification instanceof Agency) { child = networkedModel.getAuthorizedAgency(instance, auth.getConnection()); } else if (childAuthClassification instanceof Location) { child = networkedModel.getAuthorizedLocation(instance, auth.getConnection()); } else if (childAuthClassification instanceof Product) { child = networkedModel.getAuthorizedProduct(instance, auth.getConnection()); } else if (childAuthClassification instanceof Relationship) { child = networkedModel.getAuthorizedRelationship(instance, auth.getConnection()); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } return checkREAD(child, model.getUnknownNetworkedModel(childAuthClassification)) ? child : null; } public Relationship getUPDATE() { return update; } public List<ExistentialRuleform<?, ?>> lookup(NetworkAuthorization<?> auth, List<String> ids) { NetworkedModel<?, ?, ?, ?> networkedModel = model.getUnknownNetworkedModel(auth.getClassification()); return ids.stream() .map(id -> networkedModel.find(UUID.fromString(id))) .filter(rf -> rf != null) .filter(child -> networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .collect(Collectors.toList()); } public ExistentialRuleform<?, ?> lookup(NetworkAuthorization<?> auth, String id) { NetworkedModel<?, ?, ?, ?> networkedModel = model.getUnknownNetworkedModel(auth.getClassification()); return Optional.of(networkedModel.find(UUID.fromString(id))) .filter(rf -> rf != null) .filter(child -> networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .get(); } public List<RuleForm> lookupRuleForm(NetworkAuthorization<RuleForm> auth, List<String> ids) { NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); return ids.stream() .map(id -> networkedModel.find(UUID.fromString(id))) .filter(rf -> rf != null) .filter(child -> networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .collect(Collectors.toList()); } /** * Remove the facet from the instance * * @param facet * @param instance * @return * @throws SecurityException */ public RuleForm remove(NetworkAuthorization<RuleForm> facet, RuleForm instance, boolean deleteAttributes) throws SecurityException { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(facet.getClassification()); if (!networkedModel.checkFacetCapability(model.getCurrentPrincipal() .getPrincipal(), facet, getREMOVE())) { return instance; } networkedModel.initialize(instance, facet, model.getCurrentPrincipal() .getPrincipal()); return instance; } /** * Remove a child from the instance * * @param facet * @param instance * @param auth * @param child */ public RuleForm removeChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, RuleForm child) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } networkedModel.unlink(instance, auth.getChildRelationship(), child); return instance; } public RuleForm removeChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, ExistentialRuleform<?, ?> child) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } @SuppressWarnings("rawtypes") ExistentialRuleform childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); if (childAuthClassification instanceof Agency) { networkedModel.deauthorize(instance, auth.getConnection(), (Agency) child); } else if (childAuthClassification instanceof Location) { networkedModel.deauthorize(instance, auth.getConnection(), (Location) child); } else if (childAuthClassification instanceof Product) { networkedModel.deauthorize(instance, auth.getConnection(), (Product) child); } else if (childAuthClassification instanceof Relationship) { networkedModel.deauthorize(instance, auth.getConnection(), (Relationship) child); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } return instance; } /** * Remove the immediate child links from the instance * * @param facet * @param instance * @param auth * @param children */ public RuleForm removeChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, List<RuleForm> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } for (RuleForm child : children) { networkedModel.unlink(instance, auth.getChildRelationship(), child); } return instance; } public RuleForm removeChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, List<ExistentialRuleform<?, ?>> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } ExistentialRuleform<?, ?> childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); for (ExistentialRuleform<?, ?> child : children) { if (childAuthClassification instanceof Agency) { networkedModel.deauthorize(instance, auth.getConnection(), (Agency) child); } else if (childAuthClassification instanceof Location) { networkedModel.deauthorize(instance, auth.getConnection(), (Location) child); } else if (childAuthClassification instanceof Product) { networkedModel.deauthorize(instance, auth.getConnection(), (Product) child); } else if (childAuthClassification instanceof Relationship) { networkedModel.deauthorize(instance, auth.getConnection(), (Relationship) child); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } } return instance; } public RuleForm setAttributeValue(NetworkAuthorization<RuleForm> facet, RuleForm instance, AttributeAuthorization<RuleForm, Network> stateAuth, List<Object> value) { return setAttributeValue(facet, instance, stateAuth, value.toArray()); } public RuleForm setAttributeValue(NetworkAuthorization<RuleForm> facet, RuleForm instance, AttributeAuthorization<RuleForm, Network> stateAuth, Map<String, Object> value) { NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(stateAuth, networkedModel)) { return instance; } setAttributeMap(instance, stateAuth.getAuthorizedAttribute(), value, networkedModel); return instance; } public RuleForm setAttributeValue(NetworkAuthorization<RuleForm> facet, RuleForm instance, AttributeAuthorization<RuleForm, Network> stateAuth, Object value) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(stateAuth.getNetworkAuthorization() .getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(stateAuth, networkedModel)) { return instance; } networkedModel.getAttributeValue(instance, model.getEntityManager() .getReference(Attribute.class, stateAuth.getAuthorizedAttribute() .getId())) .setValue(value); return instance; } public RuleForm setAttributeValue(NetworkAuthorization<RuleForm> facet, RuleForm instance, AttributeAuthorization<RuleForm, Network> stateAuth, Object[] value) { NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(stateAuth, networkedModel)) { return instance; } setAttributeArray(instance, stateAuth.getAuthorizedAttribute(), value, networkedModel); return instance; } /** * Set the immediate children of the instance to be the list of supplied * children. No inferred links will be explicitly added or deleted. * * @param facet * @param instance * @param auth * @param children */ public RuleForm setChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, List<RuleForm> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } for (NetworkRuleform<RuleForm> childLink : networkedModel.getImmediateChildrenLinks(instance, auth.getChildRelationship())) { model.getEntityManager() .remove(childLink); } Relationship reference = model.getEntityManager() .getReference(Relationship.class, auth.getChildRelationship() .getId()); children.stream() .filter(child -> checkREAD(child, networkedModel)) .peek(child -> cast(child, auth)) .forEach(child -> networkedModel.link(instance, reference, child, model.getCurrentPrincipal() .getPrincipal())); return instance; } /** * Set the xd children of the instance. * * @param facet * @param instance * @param auth * @param children */ @SuppressWarnings({ "unchecked", "rawtypes" }) public RuleForm setChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, List<?> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } children.stream() .forEach(child -> cast((ExistentialRuleform) child, auth)); ExistentialRuleform childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); if (childAuthClassification instanceof Agency) { networkedModel.setAuthorizedAgencies(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (List<Agency>) children); } else if (childAuthClassification instanceof Location) { networkedModel.setAuthorizedLocations(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (List<Location>) children); } else if (childAuthClassification instanceof Product) { networkedModel.setAuthorizedProducts(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (List<Product>) children); } else if (childAuthClassification instanceof Relationship) { networkedModel.setAuthorizedRelationships(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (List<Relationship>) children); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } return instance; } /** * @param description * @param id * @return */ public RuleForm setDescription(RuleForm instance, String description) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(instance, networkedModel)) { return instance; } instance.setDescription(description); return instance; } public RuleForm setName(RuleForm instance, String name) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(instance, networkedModel)) { return instance; } instance.setName(name); return instance; } /** * Set the singular child of the instance. * * @param facet * @param instance * @param auth * @param child */ public RuleForm setSingularChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, RuleForm child) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } if (child == null) { networkedModel.unlinkImmediate(child, auth.getChildRelationship()); } else { cast(child, auth); networkedModel.setImmediateChild(instance, model.getEntityManager() .getReference(Relationship.class, auth.getChildRelationship() .getId()), child, model.getCurrentPrincipal() .getPrincipal()); } return instance; } /** * Set the singular xd child of the instance * * @param facet * @param instance * @param auth * @param child * * @return */ public RuleForm setSingularChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, ExistentialRuleform<?, ?> child) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } cast(child, auth); ExistentialRuleform<?, ?> childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); if (childAuthClassification instanceof Agency) { networkedModel.authorizeSingular(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Agency) child); } else if (childAuthClassification instanceof Location) { networkedModel.authorizeSingular(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Location) child); } else if (childAuthClassification instanceof Product) { networkedModel.authorizeSingular(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Product) child); } else if (childAuthClassification instanceof Relationship) { networkedModel.authorizeSingular(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Relationship) child); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } return instance; } private boolean checkREAD(AttributeAuthorization<RuleForm, Network> stateAuth, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), stateAuth, getREAD()); } private boolean checkREAD(@SuppressWarnings("rawtypes") ExistentialRuleform child, NetworkedModel<?, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD()); } private boolean checkREAD(NetworkAuthorization<RuleForm> auth, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { return networkedModel.checkFacetCapability(model.getCurrentPrincipal() .getPrincipal(), auth, getREAD()); } private boolean checkREAD(NetworkedModel<RuleForm, ?, ?, ?> networkedModel, RuleForm instance) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), instance, getREAD()); } private boolean checkREAD(XDomainNetworkAuthorization<?, ?> auth, NetworkedModel<?, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), auth, getREAD()); } private boolean checkUPDATE(AttributeAuthorization<RuleForm, Network> stateAuth, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), stateAuth, getUPDATE()); } private boolean checkUPDATE(@SuppressWarnings("rawtypes") ExistentialRuleform child, NetworkedModel<?, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getUPDATE()); } private boolean checkUPDATE(NetworkAuthorization<RuleForm> auth, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), auth, getUPDATE()); } private boolean checkUPDATE(XDomainNetworkAuthorization<?, ?> auth, NetworkedModel<?, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), auth, getUPDATE()); } private Object[] getIndexedAttributeValue(RuleForm instance, Attribute authorizedAttribute, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { AttributeValue<RuleForm>[] attributeValues = getValueArray(instance, authorizedAttribute, networkedModel); Object[] values = (Object[]) Array.newInstance(authorizedAttribute.valueClass(), attributeValues.length); for (AttributeValue<RuleForm> value : attributeValues) { values[value.getSequenceNumber()] = value.getValue(); } return values; } private Map<String, Object> getMappedAttributeValue(RuleForm instance, Attribute authorizedAttribute, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { Map<String, Object> map = new HashMap<>(); for (Map.Entry<String, AttributeValue<RuleForm>> entry : getValueMap(instance, authorizedAttribute, networkedModel).entrySet()) { map.put(entry.getKey(), entry.getValue() .getValue()); } return map; } private AttributeValue<RuleForm>[] getValueArray(RuleForm instance, Attribute attribute, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { List<? extends AttributeValue<RuleForm>> values = networkedModel.getAttributeValues(instance, attribute); int max = 0; for (AttributeValue<RuleForm> value : values) { max = Math.max(max, value.getSequenceNumber() + 1); } @SuppressWarnings("unchecked") AttributeValue<RuleForm>[] returnValue = new AttributeValue[max]; for (AttributeValue<RuleForm> form : values) { returnValue[form.getSequenceNumber()] = form; } return returnValue; } private Map<String, AttributeValue<RuleForm>> getValueMap(RuleForm instance, Attribute attribute, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { Map<String, AttributeValue<RuleForm>> map = new HashMap<>(); for (AttributeValue<RuleForm> value : networkedModel.getAttributeValues(instance, attribute)) { map.put(value.getKey(), value); } return map; } private AttributeValue<RuleForm> newAttributeValue(RuleForm instance, Attribute attribute, int i, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { AttributeValue<RuleForm> value = networkedModel.create(instance, attribute, model.getCurrentPrincipal() .getPrincipal()); value.setSequenceNumber(i); return value; } private void setAttributeArray(RuleForm instance, Attribute authorizedAttribute, Object[] values, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { AttributeValue<RuleForm>[] old = getValueArray(instance, authorizedAttribute, networkedModel); authorizedAttribute = model.getEntityManager() .getReference(Attribute.class, authorizedAttribute.getId()); if (values == null) { if (old != null) { for (AttributeValue<RuleForm> value : old) { model.getEntityManager() .remove(value); } } } else if (old == null) { for (int i = 0; i < values.length; i++) { setValue(instance, authorizedAttribute, i, null, values[i], networkedModel); } } else if (old.length == values.length) { for (int i = 0; i < values.length; i++) { setValue(instance, authorizedAttribute, i, old[i], values[i], networkedModel); } } else if (old.length < values.length) { int i; for (i = 0; i < old.length; i++) { setValue(instance, authorizedAttribute, i, old[i], values[i], networkedModel); } for (; i < values.length; i++) { setValue(instance, authorizedAttribute, i, null, values[i], networkedModel); } } else if (old.length > values.length) { int i; for (i = 0; i < values.length; i++) { setValue(instance, authorizedAttribute, i, old[i], values[i], networkedModel); } for (; i < old.length; i++) { model.getEntityManager() .remove(old[i]); } } } private void setAttributeMap(RuleForm instance, Attribute authorizedAttribute, Map<String, Object> values, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { Map<String, AttributeValue<RuleForm>> valueMap = getValueMap(instance, authorizedAttribute, networkedModel); values.keySet() .stream() .filter(keyName -> !valueMap.containsKey(keyName)) .forEach(keyName -> valueMap.remove(keyName)); int maxSeq = 0; for (AttributeValue<RuleForm> value : valueMap.values()) { maxSeq = Math.max(maxSeq, value.getSequenceNumber()); } authorizedAttribute = model.getEntityManager() .getReference(Attribute.class, authorizedAttribute.getId()); for (Map.Entry<String, Object> entry : values.entrySet()) { AttributeValue<RuleForm> value = valueMap.get(entry.getKey()); if (value == null) { value = newAttributeValue(instance, authorizedAttribute, ++maxSeq, networkedModel); model.getEntityManager() .persist(value); value.setKey(entry.getKey()); } value.setValue(entry.getValue()); } } private void setValue(RuleForm instance, Attribute attribute, int i, AttributeValue<RuleForm> existing, Object newValue, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { if (existing == null) { existing = newAttributeValue(instance, attribute, i, networkedModel); model.getEntityManager() .persist(existing); } existing.setValue(newValue); } }
package com.xpn.xwiki.plugin.feed; import java.util.Date; import org.xwiki.context.Execution; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.util.AbstractXWikiRunnable; import com.xpn.xwiki.web.Utils; public class UpdateThread extends AbstractXWikiRunnable { protected boolean fullContent; protected String space; protected FeedPlugin feedPlugin; protected int scheduleTimer; protected boolean updateInProgress = false; protected boolean forceUpdate = false; protected boolean stopUpdate = false; protected Date startDate; protected Date endDate; protected int nbLoadedArticles; protected int nbLoadedFeeds; protected int nbLoadedFeedsErrors; protected Exception exception; public UpdateThread(String space, boolean fullContent, int scheduleTimer, FeedPlugin feedPlugin, XWikiContext context) { super(XWikiContext.EXECUTIONCONTEXT_KEY, context); this.fullContent = fullContent; this.space = space; this.feedPlugin = feedPlugin; this.scheduleTimer = scheduleTimer; } public void update() { if (!stopUpdate) { if (updateInProgress == false) { updateInProgress = true; nbLoadedFeeds = 0; nbLoadedFeedsErrors = 0; exception = null; nbLoadedArticles = 0; endDate = null; startDate = new Date(); XWikiContext context = getXWikiContext(); try { // Make sure store sessions are cleaned up context.getWiki().getStore().cleanUp(context); // update the feeds nbLoadedArticles = feedPlugin.updateFeedsInSpace(space, fullContent, true, false, context); } catch (XWikiException e) { exception = e; e.printStackTrace(); } finally { updateInProgress = false; endDate = new Date(); context.getWiki().getStore().cleanUp(context); } // an update has been schedule.. if ((forceUpdate == true) && (stopUpdate == false)) { forceUpdate = false; update(); } } else { // let's schedule an update at the end of the current update forceUpdate = true; } } } private XWikiContext getXWikiContext() { return (XWikiContext) Utils.getComponent(Execution.class).getContext().getProperty("xwikicontext"); } public String getSpace() { return space; } public boolean isUpdateInProgress() { return updateInProgress; } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } public int getNbLoadedArticles() { return nbLoadedArticles; } public Exception getException() { return exception; } public void stopUpdate() { if (!updateInProgress) { feedPlugin.removeUpdateThread(space, this, getXWikiContext()); } stopUpdate = true; } public int getNbLoadedFeeds() { return nbLoadedFeeds; } public void setNbLoadedFeeds(int nbLoadedFeeds) { this.nbLoadedFeeds = nbLoadedFeeds; } public int getNbLoadedFeedsErrors() { return nbLoadedFeedsErrors; } public void setNbLoadedFeedsErrors(int nbLoadedFeedsErrors) { this.nbLoadedFeedsErrors = nbLoadedFeedsErrors; } @Override protected void runInternal() { while (true) { update(); if (stopUpdate) { feedPlugin.removeUpdateThread(space, this, getXWikiContext()); break; } try { Thread.sleep(scheduleTimer); } catch (InterruptedException e) { break; } } } }
package com.xpn.xwiki.plugin.packaging; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.input.CloseShieldInputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMElement; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xwiki.extension.Extension; import org.xwiki.extension.ExtensionId; import org.xwiki.extension.InstalledExtension; import org.xwiki.extension.LocalExtension; import org.xwiki.extension.ResolveException; import org.xwiki.extension.event.ExtensionInstalledEvent; import org.xwiki.extension.repository.ExtensionRepositoryManager; import org.xwiki.extension.repository.InstalledExtensionRepository; import org.xwiki.extension.repository.LocalExtensionRepository; import org.xwiki.model.reference.SpaceReference; import org.xwiki.observation.ObservationManager; import org.xwiki.query.QueryException; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.internal.event.XARImportedEvent; import com.xpn.xwiki.internal.event.XARImportingEvent; import com.xpn.xwiki.internal.xml.XMLWriter; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.web.Utils; import net.sf.json.JSONObject; /** * @version $Id$ * @deprecated since 5.2, use Filter framework instead */ @Deprecated public class Package { public static final int OK = 0; public static final int Right = 1; public static final String DEFAULT_FILEEXT = "xml"; public static final String XAR_FILENAME_ENCODING = "UTF-8"; public static final String DefaultPackageFileName = "package.xml"; public static final String DefaultPluginName = "package"; private static final Logger LOGGER = LoggerFactory.getLogger(Package.class); private String name = "My package"; private String description = ""; /** * @see #isInstallExension() */ private boolean installExtension = true; private String extensionId; private String version = "1.0.0"; private String licence = "LGPL"; private String authorName = "XWiki"; private List<DocumentInfo> files = null; private List<DocumentInfo> customMappingFiles = null; private List<DocumentInfo> classFiles = null; private boolean backupPack = false; private boolean preserveVersion = false; private boolean withVersions = true; private List<DocumentFilter> documentFilters = new ArrayList<DocumentFilter>(); public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getId() { return this.extensionId; } public void setId(String id) { this.extensionId = id; } /** * @return <code>true</code> if the extension packaged in the XAR should be registered as such automatically, * <code>false</code> otherwise. * @deprecated since 6.4.5, 7.0.1, 7.1M1, use {@link #isInstallExtension()} instead */ @Deprecated public boolean isInstallExension() { return isInstallExtension(); } /** * @return <code>true</code> if the extension packaged in the XAR should be registered as such automatically, * <code>false</code> otherwise. * @since 6.4.5 * @since 7.0.1 * @since 7.1M1 */ public boolean isInstallExtension() { return this.installExtension; } /** * @param installExension <code>true</code> if the extension packaged in the XAR should be registered as such * automatically, <code>false</code> otherwise. * @deprecated since 6.4.5, 7.0.1, 7.1M1, use {@link #setInstallExension(boolean)} instead */ @Deprecated public void setInstallExension(boolean installExension) { this.installExtension = installExension; } /** * @param installExtension <code>true</code> if the extension packaged in the XAR should be registered as such * automatically, <code>false</code> otherwise. * @since 6.4.5 * @since 7.0.1 * @since 7.1M1 */ public void setInstallExtension(boolean installExtension) { this.installExtension = installExtension; } public String getExtensionId() { return this.extensionId; } public void setExtensionId(String extensionId) { this.extensionId = extensionId; } public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } public String getLicence() { return this.licence; } public void setLicence(String licence) { this.licence = licence; } public String getAuthorName() { return this.authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } /** * If true, the package will preserve the original author during import, rather than updating the author to the * current (importing) user. * * @see #isWithVersions() * @see #isVersionPreserved() */ public boolean isBackupPack() { return this.backupPack; } public void setBackupPack(boolean backupPack) { this.backupPack = backupPack; } public boolean hasBackupPackImportRights(XWikiContext context) { return isFarmAdmin(context); } /** * If true, the package will preserve the current document version during import, regardless of whether or not the * document history is included. * * @see #isWithVersions() * @see #isBackupPack() */ public boolean isVersionPreserved() { return this.preserveVersion; } public void setPreserveVersion(boolean preserveVersion) { this.preserveVersion = preserveVersion; } public List<DocumentInfo> getFiles() { return this.files; } public List<DocumentInfo> getCustomMappingFiles() { return this.customMappingFiles; } public boolean isWithVersions() { return this.withVersions; } /** * If set to true, history revisions in the archive will be imported when importing documents. */ public void setWithVersions(boolean withVersions) { this.withVersions = withVersions; } public void addDocumentFilter(Object filter) throws PackageException { if (filter instanceof DocumentFilter) { this.documentFilters.add((DocumentFilter) filter); } else { throw new PackageException(PackageException.ERROR_PACKAGE_INVALID_FILTER, "Invalid Document Filter"); } } public Package() { this.files = new ArrayList<DocumentInfo>(); this.customMappingFiles = new ArrayList<DocumentInfo>(); this.classFiles = new ArrayList<DocumentInfo>(); } public boolean add(XWikiDocument doc, int defaultAction, XWikiContext context) throws XWikiException { if (!context.getWiki().checkAccess("edit", doc, context)) { return false; } for (int i = 0; i < this.files.size(); i++) { DocumentInfo di = this.files.get(i); if (di.getFullName().equals(doc.getFullName()) && (di.getLanguage().equals(doc.getLanguage()))) { if (defaultAction != DocumentInfo.ACTION_NOT_DEFINED) { di.setAction(defaultAction); } if (!doc.isNew()) { di.setDoc(doc); } return true; } } doc = doc.clone(); try { filter(doc, context); DocumentInfo docinfo = new DocumentInfo(doc); docinfo.setAction(defaultAction); this.files.add(docinfo); BaseClass bclass = doc.getXClass(); if (bclass.getFieldList().size() > 0) { this.classFiles.add(docinfo); } if (bclass.getCustomMapping() != null) { this.customMappingFiles.add(docinfo); } return true; } catch (ExcludeDocumentException e) { LOGGER.info("Skip the document " + doc.getDocumentReference()); return false; } } public boolean add(XWikiDocument doc, XWikiContext context) throws XWikiException { return add(doc, DocumentInfo.ACTION_NOT_DEFINED, context); } public boolean updateDoc(String docFullName, int action, XWikiContext context) throws XWikiException { XWikiDocument doc = new XWikiDocument(); doc.setFullName(docFullName, context); return add(doc, action, context); } public boolean add(String docFullName, int DefaultAction, XWikiContext context) throws XWikiException { XWikiDocument doc = context.getWiki().getDocument(docFullName, context); add(doc, DefaultAction, context); List<String> languages = doc.getTranslationList(context); for (String language : languages) { if (!((language == null) || (language.equals("")) || (language.equals(doc.getDefaultLanguage())))) { add(doc.getTranslatedDocument(language, context), DefaultAction, context); } } return true; } public boolean add(String docFullName, String language, int DefaultAction, XWikiContext context) throws XWikiException { XWikiDocument doc = context.getWiki().getDocument(docFullName, context); if ((language == null) || (language.equals(""))) { add(doc, DefaultAction, context); } else { add(doc.getTranslatedDocument(language, context), DefaultAction, context); } return true; } public boolean add(String docFullName, XWikiContext context) throws XWikiException { return add(docFullName, DocumentInfo.ACTION_NOT_DEFINED, context); } public boolean add(String docFullName, String language, XWikiContext context) throws XWikiException { return add(docFullName, language, DocumentInfo.ACTION_NOT_DEFINED, context); } public void filter(XWikiDocument doc, XWikiContext context) throws ExcludeDocumentException { for (DocumentFilter docFilter : this.documentFilters) { docFilter.filter(doc, context); } } public String export(OutputStream os, XWikiContext context) throws IOException, XWikiException { if (this.files.size() == 0) { return "No Selected file"; } ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); zos.setEncoding(XAR_FILENAME_ENCODING); // By including the unicode extra fields, it is possible to extract XAR-files // containing documents with non-ascii characters in the document name using InfoZIP, // and the filenames will be correctly converted to the character set of the local // file system. zos.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS); for (int i = 0; i < this.files.size(); i++) { DocumentInfo docinfo = this.files.get(i); XWikiDocument doc = docinfo.getDoc(); addToZip(doc, zos, this.withVersions, context); } addInfosToZip(zos, context); zos.finish(); zos.flush(); return ""; } public String exportToDir(File dir, XWikiContext context) throws IOException, XWikiException { if (!dir.exists()) { if (!dir.mkdirs()) { Object[] args = new Object[1]; args[0] = dir.toString(); throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_MKDIR, "Error creating directory {0}", null, args); } } for (int i = 0; i < this.files.size(); i++) { DocumentInfo docinfo = this.files.get(i); XWikiDocument doc = docinfo.getDoc(); addToDir(doc, dir, this.withVersions, context); } addInfosToDir(dir, context); return ""; } /** * Load this package in memory from a byte array. It may be installed later using {@link #install(XWikiContext)}. * Your should prefer {@link #Import(InputStream, XWikiContext)} which may avoid loading the package twice in * memory. * * @param file a byte array containing the content of a zipped package file * @param context current XWikiContext * @return an empty string, useless. * @throws IOException while reading the ZipFile * @throws XWikiException when package content is broken */ public String Import(byte file[], XWikiContext context) throws IOException, XWikiException { return Import(new ByteArrayInputStream(file), context); } /** * Load this package in memory from an InputStream. It may be installed later using {@link #install(XWikiContext)}. * * @param file an InputStream of a zipped package file * @param context current XWikiContext * @return an empty string, useless. * @throws IOException while reading the ZipFile * @throws XWikiException when package content is broken * @since 2.3M2 */ public String Import(InputStream file, XWikiContext context) throws IOException, XWikiException { ZipArchiveInputStream zis; ArchiveEntry entry; Document description = null; try { zis = new ZipArchiveInputStream(file, XAR_FILENAME_ENCODING, false); List<XWikiDocument> docsToLoad = new LinkedList<XWikiDocument>(); /* * Loop 1: Cycle through the zip input stream and load out all of the documents, when we find the * package.xml file we put it aside to so that we only include documents which are in the file. */ while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory() || (entry.getName().indexOf("META-INF") != -1)) { // The entry is either a directory or is something inside of the META-INF dir. continue; } else if (entry.getName().compareTo(DefaultPackageFileName) == 0) { // The entry is the manifest (package.xml). Read this differently. description = fromXml(new CloseShieldInputStream(zis)); } else { XWikiDocument doc = null; try { doc = readFromXML(new CloseShieldInputStream(zis)); } catch (Throwable e) { LOGGER.warn( "Failed to parse document [{}] from XML during import, thus it will not be installed. " + "The error was: " + ExceptionUtils.getRootCauseMessage(e)); // It will be listed in the "failed documents" section after the import. addToErrors(entry.getName().replaceAll("/", "."), context); continue; } // Run all of the registered DocumentFilters on this document and // if no filters throw exceptions, add it to the list to import. try { this.filter(doc, context); docsToLoad.add(doc); } catch (ExcludeDocumentException e) { LOGGER.info("Skip the document '" + doc.getDocumentReference() + "'"); } } } // Make sure a manifest was included in the package... if (description == null) { throw new PackageException(XWikiException.ERROR_XWIKI_UNKNOWN, "Could not find the package definition"); } /* * Loop 2: Cycle through the list of documents and if they are in the manifest then add them, otherwise log * a warning and add them to the skipped list. */ for (XWikiDocument doc : docsToLoad) { if (documentExistInPackageFile(doc.getFullName(), doc.getLanguage(), description)) { this.add(doc, context); } else { LOGGER.warn("document " + doc.getDocumentReference() + " does not exist in package definition." + " It will not be installed."); // It will be listed in the "skipped documents" section after the // import. addToSkipped(doc.getFullName(), context); } } updateFileInfos(description); } catch (DocumentException e) { throw new PackageException(XWikiException.ERROR_XWIKI_UNKNOWN, "Error when reading the XML"); } return ""; } private boolean documentExistInPackageFile(String docName, String language, Document xml) { Element docFiles = xml.getRootElement(); Element infosFiles = docFiles.element("files"); @SuppressWarnings("unchecked") List<Element> fileList = infosFiles.elements("file"); for (Element el : fileList) { String tmpDocName = el.getStringValue(); if (tmpDocName.compareTo(docName) != 0) { continue; } String tmpLanguage = el.attributeValue("language"); if (tmpLanguage == null) { tmpLanguage = ""; } if (tmpLanguage.compareTo(language) == 0) { return true; } } return false; } private void updateFileInfos(Document xml) { Element docFiles = xml.getRootElement(); Element infosFiles = docFiles.element("files"); @SuppressWarnings("unchecked") List<Element> fileList = infosFiles.elements("file"); for (Element el : fileList) { String defaultAction = el.attributeValue("defaultAction"); String language = el.attributeValue("language"); if (language == null) { language = ""; } String docName = el.getStringValue(); setDocumentDefaultAction(docName, language, Integer.parseInt(defaultAction)); } } private void setDocumentDefaultAction(String docName, String language, int defaultAction) { if (this.files == null) { return; } for (DocumentInfo docInfo : this.files) { if (docInfo.getFullName().equals(docName) && docInfo.getLanguage().equals(language)) { docInfo.setAction(defaultAction); return; } } } public int testInstall(boolean isAdmin, XWikiContext context) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Package test install"); } int result = DocumentInfo.INSTALL_IMPOSSIBLE; try { if (this.files.size() == 0) { return result; } result = this.files.get(0).testInstall(isAdmin, context); for (DocumentInfo docInfo : this.files) { int res = docInfo.testInstall(isAdmin, context); if (res < result) { result = res; } } return result; } finally { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Package test install result " + result); } } } public int install(XWikiContext context) throws XWikiException { boolean isAdmin = context.getWiki().getRightService().hasWikiAdminRights(context); if (testInstall(isAdmin, context) == DocumentInfo.INSTALL_IMPOSSIBLE) { setStatus(DocumentInfo.INSTALL_IMPOSSIBLE, context); return DocumentInfo.INSTALL_IMPOSSIBLE; } boolean hasCustomMappings = false; for (DocumentInfo docinfo : this.customMappingFiles) { BaseClass bclass = docinfo.getDoc().getXClass(); hasCustomMappings |= context.getWiki().getStore().injectCustomMapping(bclass, context); } if (hasCustomMappings) { context.getWiki().getStore().injectUpdatedCustomMappings(context); } int status = DocumentInfo.INSTALL_OK; // Determine if the user performing the installation is a farm admin. // We allow author preservation from the package only to farm admins. // In order to prevent sub-wiki admins to take control of a farm with forged packages. // We test it once for the whole import in case one of the document break user during the import process. boolean backup = this.backupPack && isFarmAdmin(context); // Notify all the listeners about import ObservationManager om = Utils.getComponent(ObservationManager.class); // FIXME: should be able to pass some sort of source here, the name of the attachment or the list of // imported documents. But for the moment it's fine om.notify(new XARImportingEvent(), null, context); try { // Start by installing all documents having a class definition so that their // definitions are available when installing documents using them. for (DocumentInfo classFile : this.classFiles) { if (installDocument(classFile, isAdmin, backup, context) == DocumentInfo.INSTALL_ERROR) { status = DocumentInfo.INSTALL_ERROR; } } // Install the remaining documents (without class definitions). for (DocumentInfo docInfo : this.files) { if (!this.classFiles.contains(docInfo)) { if (installDocument(docInfo, isAdmin, backup, context) == DocumentInfo.INSTALL_ERROR) { status = DocumentInfo.INSTALL_ERROR; } } } setStatus(status, context); } finally { // FIXME: should be able to pass some sort of source here, the name of the attachment or the list of // imported documents. But for the moment it's fine om.notify(new XARImportedEvent(), null, context); registerExtension(context); } return status; } private void registerExtension(XWikiContext context) { // Register the package as extension if it's one if (isInstallExtension() && StringUtils.isNotEmpty(getExtensionId()) && StringUtils.isNotEmpty(getVersion())) { ExtensionId extensionId = new ExtensionId(getExtensionId(), getVersion()); try { LocalExtensionRepository localRepository = Utils.getComponent(LocalExtensionRepository.class); LocalExtension localExtension = localRepository.getLocalExtension(extensionId); if (localExtension == null) { Extension extension; try { // Try to find and download the extension from a repository extension = Utils.getComponent(ExtensionRepositoryManager.class).resolve(extensionId); } catch (ResolveException e) { LOGGER.debug("Can't find extension [{}]", extensionId, e); // FIXME: Create a dummy extension. Need support for partial/lazy extension. return; } localExtension = localRepository.storeExtension(extension); } InstalledExtensionRepository installedRepository = Utils.getComponent(InstalledExtensionRepository.class); String namespace = "wiki:" + context.getWikiId(); // Make sure it's not already there if (installedRepository.getInstalledExtension(localExtension.getId().getId(), namespace) == null) { for (ExtensionId feature : localExtension.getExtensionFeatures()) { if (installedRepository.getInstalledExtension(feature.getId(), namespace) != null) { // Already exist so don't register it or it could create a mess return; } } } else { return; } // Register the extension as installed InstalledExtension installedExtension = installedRepository.installExtension(localExtension, namespace, false); // Tell the world about it Utils.getComponent(ObservationManager.class) .notify(new ExtensionInstalledEvent(installedExtension.getId(), namespace), installedExtension); } catch (Exception e) { LOGGER.error("Failed to register extenion [{}] from the XAR", extensionId, e); } } } /** * Indicate of the user has amin rights on the farm, i.e. that he has admin rights on the main wiki. * * @param context the XWiki context * @return true if the current user is farm admin */ private boolean isFarmAdmin(XWikiContext context) { String wiki = context.getWikiId(); try { context.setWikiId(context.getMainXWiki()); return context.getWiki().getRightService().hasWikiAdminRights(context); } finally { context.setWikiId(wiki); } } private int installDocument(DocumentInfo doc, boolean isAdmin, boolean backup, XWikiContext context) throws XWikiException { if (this.preserveVersion && this.withVersions) { // Right now importing an archive and the history revisions it contains // without overriding the existing document is not supported. // We fallback on adding a new version to the existing history without importing the // archive's revisions. this.withVersions = false; } int result = DocumentInfo.INSTALL_OK; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Package installing document " + doc.getFullName() + " " + doc.getLanguage()); } if (doc.getAction() == DocumentInfo.ACTION_SKIP) { addToSkipped(doc.getFullName() + ":" + doc.getLanguage(), context); return DocumentInfo.INSTALL_OK; } int status = doc.testInstall(isAdmin, context); if (status == DocumentInfo.INSTALL_IMPOSSIBLE) { addToErrors(doc.getFullName() + ":" + doc.getLanguage(), context); return DocumentInfo.INSTALL_IMPOSSIBLE; } if (status == DocumentInfo.INSTALL_OK || status == DocumentInfo.INSTALL_ALREADY_EXIST && doc.getAction() == DocumentInfo.ACTION_OVERWRITE) { XWikiDocument previousdoc = null; if (status == DocumentInfo.INSTALL_ALREADY_EXIST) { previousdoc = context.getWiki().getDocument(doc.getFullName(), context); // if this document is a translation: we should only delete the translation if (doc.getDoc().getTranslation() != 0) { previousdoc = previousdoc.getTranslatedDocument(doc.getLanguage(), context); } // we should only delete the previous document // if we are overridding the versions and/or if this is a backup pack if (!this.preserveVersion || this.withVersions) { try { // This is not a real document delete, it's a upgrade. To be sure to not // generate DELETE notification we directly use {@link XWikiStoreInterface} context.getWiki().getStore().deleteXWikiDoc(previousdoc, context); } catch (Exception e) { // let's log the error but not stop result = DocumentInfo.INSTALL_ERROR; addToErrors(doc.getFullName() + ":" + doc.getLanguage(), context); if (LOGGER.isErrorEnabled()) { LOGGER.error("Failed to delete document " + previousdoc.getDocumentReference()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Failed to delete document " + previousdoc.getDocumentReference(), e); } } } else if (previousdoc.hasElement(XWikiDocument.HAS_ATTACHMENTS)) { // We conserve the old attachments in the new documents List<XWikiAttachment> newDocAttachments = doc.getDoc().getAttachmentList(); for (XWikiAttachment att : previousdoc.getAttachmentList()) { if (doc.getDoc().getAttachment(att.getFilename()) == null) { // We add the attachment to new document newDocAttachments.add(att); // But then we add it in the "to remove list" of the document // So the attachment will be removed from the database when XWiki#saveDocument // will be called doc.getDoc().removeAttachment(att); } } } doc.getDoc().addXObjectsToRemoveFromVersion(previousdoc); doc.getDoc().setOriginalDocument(previousdoc); } try { if (!backup) { doc.getDoc().setAuthorReference(context.getUserReference()); doc.getDoc().setContentAuthorReference(context.getUserReference()); // if the import is not a backup pack we set the date to now Date date = new Date(); doc.getDoc().setDate(date); doc.getDoc().setContentUpdateDate(date); } if (!this.withVersions) { doc.getDoc().setVersion("1.1"); } // Does the document to be imported already exists in the wiki ? boolean isNewDocument = previousdoc == null; // Conserve existing history only if asked for it and if this history exists boolean conserveExistingHistory = this.preserveVersion && !isNewDocument; // Does the document from the package contains history revisions ? boolean packageHasHistory = this.documentContainsHistory(doc); // Reset to initial (1.1) version when we don't want to conserve existing history and either we don't // want the package history or this latter one is empty boolean shouldResetToInitialVersion = !isNewDocument && !conserveExistingHistory && (!this.withVersions || !packageHasHistory); if (conserveExistingHistory) { // Insert the archive from the existing document doc.getDoc().setDocumentArchive(previousdoc.getDocumentArchive(context)); } else { // Reset or replace history // if there was not history in the source package then we should reset the version number to 1.1 if (shouldResetToInitialVersion) { // Make sure the save will not increment the version to 2.1 doc.getDoc().setContentDirty(false); doc.getDoc().setMetaDataDirty(false); } } String saveMessage = context.getMessageTool().get("core.importer.saveDocumentComment"); context.getWiki().saveDocument(doc.getDoc(), saveMessage, context); addToInstalled(doc.getFullName() + ":" + doc.getLanguage(), context); if ((this.withVersions && packageHasHistory) || conserveExistingHistory) { // we need to force the saving the document archive. if (doc.getDoc().getDocumentArchive() != null) { context.getWiki().getVersioningStore() .saveXWikiDocArchive(doc.getDoc().getDocumentArchive(context), true, context); } } if (shouldResetToInitialVersion) { // If we override and do not import version, (meaning reset document to 1.1) // We need manually reset possible existing revision for the document // This means making the history empty (it does not affect the version number) doc.getDoc().resetArchive(context); } } catch (XWikiException e) { addToErrors(doc.getFullName() + ":" + doc.getLanguage(), context); if (LOGGER.isErrorEnabled()) { LOGGER.error("Failed to save document " + doc.getFullName(), e); } result = DocumentInfo.INSTALL_ERROR; } } return result; } /** * @return true if the passed document contains a (not-empty) history of previous versions, false otherwise */ private boolean documentContainsHistory(DocumentInfo doc) { if ((doc.getDoc().getDocumentArchive() == null) || (doc.getDoc().getDocumentArchive().getNodes() == null) || (doc.getDoc().getDocumentArchive().getNodes().size() == 0)) { return false; } return true; } private List<String> getStringList(String name, XWikiContext context) { @SuppressWarnings("unchecked") List<String> list = (List<String>) context.get(name); if (list == null) { list = new ArrayList<String>(); context.put(name, list); } return list; } private void addToErrors(String fullName, XWikiContext context) { if (fullName.endsWith(":")) { fullName = fullName.substring(0, fullName.length() - 1); } getErrors(context).add(fullName); } private void addToSkipped(String fullName, XWikiContext context) { if (fullName.endsWith(":")) { fullName = fullName.substring(0, fullName.length() - 1); } getSkipped(context).add(fullName); } private void addToInstalled(String fullName, XWikiContext context) { if (fullName.endsWith(":")) { fullName = fullName.substring(0, fullName.length() - 1); } getInstalled(context).add(fullName); } private void setStatus(int status, XWikiContext context) { context.put("install_status", status); } public List<String> getErrors(XWikiContext context) { return getStringList("install_errors", context); } public List<String> getSkipped(XWikiContext context) { return getStringList("install_skipped", context); } public List<String> getInstalled(XWikiContext context) { return getStringList("install_installed", context); } public int getStatus(XWikiContext context) { Integer status = (Integer) context.get("install_status"); if (status == null) { return -1; } else { return status.intValue(); } } /** * Create a {@link XWikiDocument} from xml stream. * * @param is the xml stream. * @return the {@link XWikiDocument}. * @throws XWikiException error when creating the {@link XWikiDocument}. */ private XWikiDocument readFromXML(InputStream is) throws XWikiException { XWikiDocument doc = new XWikiDocument(); doc.fromXML(is, this.withVersions); return doc; } /** * Create a {@link XWikiDocument} from xml {@link Document}. * * @param domDoc the xml {@link Document}. * @return the {@link XWikiDocument}. * @throws XWikiException error when creating the {@link XWikiDocument}. */ private XWikiDocument readFromXML(Document domDoc) throws XWikiException { XWikiDocument doc = new XWikiDocument(); doc.fromXML(domDoc, this.withVersions); return doc; } /** * You should prefer {@link #toXML(com.xpn.xwiki.internal.xml.XMLWriter)}. If an error occurs, a stacktrace is dump * to logs, and an empty String is returned. * * @return a package.xml file for the this package */ public String toXml(XWikiContext context) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { toXML(baos, context); return baos.toString(context.getWiki().getEncoding()); } catch (IOException e) { e.printStackTrace(); return ""; } } /** * Write the package.xml file to an {@link XMLWriter}. * * @param wr the writer to write to * @throws IOException when an error occurs during streaming operation * @since 2.3M2 */ public void toXML(XMLWriter wr) throws IOException { Element docel = new DOMElement("package"); wr.writeOpen(docel); Element elInfos = new DOMElement("infos"); wr.write(elInfos); Element el = new DOMElement("name"); el.addText(this.name); wr.write(el); el = new DOMElement("description"); el.addText(this.description); wr.write(el); el = new DOMElement("licence"); el.addText(this.licence); wr.write(el); el = new DOMElement("author"); el.addText(this.authorName); wr.write(el); el = new DOMElement("version"); el.addText(this.version); wr.write(el); el = new DOMElement("backupPack"); el.addText(new Boolean(this.backupPack).toString()); wr.write(el); el = new DOMElement("preserveVersion"); el.addText(new Boolean(this.preserveVersion).toString()); wr.write(el); Element elfiles = new DOMElement("files"); wr.writeOpen(elfiles); for (DocumentInfo docInfo : this.files) { Element elfile = new DOMElement("file"); elfile.addAttribute("defaultAction", String.valueOf(docInfo.getAction())); elfile.addAttribute("language", String.valueOf(docInfo.getLanguage())); elfile.addText(docInfo.getFullName()); wr.write(elfile); } } /** * Write the package.xml file to an OutputStream * * @param out the OutputStream to write to * @param context curent XWikiContext * @throws IOException when an error occurs during streaming operation * @since 2.3M2 */ public void toXML(OutputStream out, XWikiContext context) throws IOException { XMLWriter wr = new XMLWriter(out, new OutputFormat("", true, context.getWiki().getEncoding())); Document doc = new DOMDocument(); wr.writeDocumentStart(doc); toXML(wr); wr.writeDocumentEnd(doc); } /** * Write the package.xml file to a ZipOutputStream * * @param zos the ZipOutputStream to write to * @param context current XWikiContext */ private void addInfosToZip(ZipArchiveOutputStream zos, XWikiContext context) { try { String zipname = DefaultPackageFileName; ZipArchiveEntry zipentry = new ZipArchiveEntry(zipname); zos.putArchiveEntry(zipentry); toXML(zos, context); zos.closeArchiveEntry(); } catch (Exception e) { e.printStackTrace(); } } /** * Generate a relative path based on provided document. * * @param doc the document to export. * @return the corresponding path. */ public String getPathFromDocument(XWikiDocument doc, XWikiContext context) { return getDirectoryForDocument(doc) + getFileNameFromDocument(doc, context); } /** * Generate a file name based on provided document. * * @param doc the document to export. * @return the corresponding file name. */ public String getFileNameFromDocument(XWikiDocument doc, XWikiContext context) { StringBuilder fileName = new StringBuilder(doc.getDocumentReference().getName()); // Add language String language = doc.getLanguage(); if ((language != null) && (!language.equals(""))) { fileName.append("."); fileName.append(language); } // Add extension fileName.append('.').append(DEFAULT_FILEEXT); return fileName.toString(); } /** * Generate a relative path based on provided document for the directory where the document should be stored. * * @param doc the document to export * @return the corresponding path */ public String getDirectoryForDocument(XWikiDocument doc) { StringBuilder path = new StringBuilder(); for (SpaceReference space : doc.getDocumentReference().getSpaceReferences()) { path.append(space.getName()).append('/'); } return path.toString(); } /** * Write an XML serialized XWikiDocument to a ZipOutputStream * * @param doc the document to serialize * @param zos the ZipOutputStream to write to * @param withVersions if true, also serialize all document versions * @param context current XWikiContext * @throws XWikiException when an error occurs during documents access * @throws IOException when an error occurs during streaming operation * @deprecated since 4.1M2 */ @Deprecated public void addToZip(XWikiDocument doc, ZipOutputStream zos, boolean withVersions, XWikiContext context) throws XWikiException, IOException { String zipname = getPathFromDocument(doc, context); ZipEntry zipentry = new ZipEntry(zipname); zos.putNextEntry(zipentry); doc.toXML(zos, true, false, true, withVersions, context); zos.closeEntry(); } /** * Write an XML serialized XWikiDocument to a ZipOutputStream * * @param doc the document to serialize * @param zos the ZipOutputStream to write to * @param withVersions if true, also serialize all document versions * @param context current XWikiContext * @throws XWikiException when an error occurs during documents access * @throws IOException when an error occurs during streaming operation * @since 4.1M2 */ private void addToZip(XWikiDocument doc, ZipArchiveOutputStream zos, boolean withVersions, XWikiContext context) throws XWikiException, IOException { String zipname = getPathFromDocument(doc, context); ZipArchiveEntry zipentry = new ZipArchiveEntry(zipname); zos.putArchiveEntry(zipentry); doc.toXML(zos, true, false, true, withVersions, context); zos.closeArchiveEntry(); } public void addToDir(XWikiDocument doc, File dir, boolean withVersions, XWikiContext context) throws XWikiException { try { filter(doc, context); File spacedir = new File(dir, getDirectoryForDocument(doc)); if (!spacedir.exists()) { if (!spacedir.mkdirs()) { Object[] args = new Object[1]; args[0] = dir.toString(); throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_MKDIR, "Error creating directory {0}", null, args); } } String filename = getFileNameFromDocument(doc, context); File file = new File(spacedir, filename); FileOutputStream fos = new FileOutputStream(file); doc.toXML(fos, true, false, true, withVersions, context); fos.flush(); fos.close(); } catch (ExcludeDocumentException e) { LOGGER.info("Skip the document " + doc.getDocumentReference()); } catch (Exception e) { Object[] args = new Object[1]; args[0] = doc.getDocumentReference(); throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_XWIKI_DOC_EXPORT, "Error creating file {0}", e, args); } } private void addInfosToDir(File dir, XWikiContext context) { try { String filename = DefaultPackageFileName; File file = new File(dir, filename); FileOutputStream fos = new FileOutputStream(file); toXML(fos, context); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } protected String getElementText(Element docel, String name) { return getElementText(docel, name, ""); } protected String getElementText(Element docel, String name, String def) { Element el = docel.element(name); if (el == null) { return def; } else { return el.getText(); } } protected Document fromXml(InputStream xml) throws DocumentException { SAXReader reader = new SAXReader(); Document domdoc = reader.read(xml); Element docEl = domdoc.getRootElement(); Element infosEl = docEl.element("infos"); this.name = getElementText(infosEl, "name"); this.description = getElementText(infosEl, "description"); this.licence = getElementText(infosEl, "licence"); this.authorName = getElementText(infosEl, "author"); this.extensionId = getElementText(infosEl, "extensionId", null); this.version = getElementText(infosEl, "version"); this.backupPack = new Boolean(getElementText(infosEl, "backupPack")).booleanValue(); this.preserveVersion = new Boolean(getElementText(infosEl, "preserveVersion")).booleanValue(); return domdoc; } public void addAllWikiDocuments(XWikiContext context) throws XWikiException { XWiki wiki = context.getWiki(); try { List<String> documentNames = wiki.getStore().getQueryManager().getNamedQuery("getAllDocuments").execute(); for (String docName : documentNames) { add(docName, DocumentInfo.ACTION_OVERWRITE, context); } } catch (QueryException ex) { throw new PackageException(XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Cannot retrieve the list of documents to export", ex); } } public void deleteAllWikiDocuments(XWikiContext context) throws XWikiException { XWiki wiki = context.getWiki(); List<String> spaces = wiki.getSpaces(context); for (int i = 0; i < spaces.size(); i++) { List<String> docNameList = wiki.getSpaceDocsName(spaces.get(i), context); for (String docName : docNameList) { String docFullName = spaces.get(i) + "." + docName; XWikiDocument doc = wiki.getDocument(docFullName, context); wiki.deleteAllDocuments(doc, context); } } } /** * Load document files from provided directory and sub-directories into packager. * * @param dir the directory from where to load documents. * @param context the XWiki context. * @param description the package descriptor. * @return the number of loaded documents. * @throws IOException error when loading documents. * @throws XWikiException error when loading documents. */ public int readFromDir(File dir, XWikiContext context, Document description) throws IOException, XWikiException { File[] files = dir.listFiles(); SAXReader reader = new SAXReader(); int count = 0; for (File file : files) { if (file.isDirectory()) { count += readFromDir(file, context, description); } else { boolean validWikiDoc = false; Document domdoc = null; try { domdoc = reader.read(new FileInputStream(file)); validWikiDoc = XWikiDocument.containsXMLWikiDocument(domdoc); } catch (DocumentException e1) { } if (validWikiDoc) { XWikiDocument doc = readFromXML(domdoc); try { filter(doc, context); if (documentExistInPackageFile(doc.getFullName(), doc.getLanguage(), description)) { add(doc, context); ++count; } else { throw new PackageException(XWikiException.ERROR_XWIKI_UNKNOWN, "document " + doc.getDocumentReference() + " does not exist in package definition"); } } catch (ExcludeDocumentException e) { LOGGER.info("Skip the document '" + doc.getDocumentReference() + "'"); } } else if (!file.getName().equals(DefaultPackageFileName)) { LOGGER.info(file.getAbsolutePath() + " is not a valid wiki document"); } } } return count; } /** * Load document files from provided directory and sub-directories into packager. * * @param dir the directory from where to load documents. * @param context the XWiki context. * @return * @throws IOException error when loading documents. * @throws XWikiException error when loading documents. */ public String readFromDir(File dir, XWikiContext context) throws IOException, XWikiException { if (!dir.isDirectory()) { throw new PackageException(PackageException.ERROR_PACKAGE_UNKNOWN, dir.getAbsolutePath() + " is not a directory"); } int count = 0; try { File infofile = new File(dir, DefaultPackageFileName); Document description = fromXml(new FileInputStream(infofile)); count = readFromDir(dir, context, description); updateFileInfos(description); } catch (DocumentException e) { throw new PackageException(PackageException.ERROR_PACKAGE_UNKNOWN, "Error when reading the XML"); } LOGGER.info("Package read " + count + " documents"); return ""; } /** * Outputs the content of this package in the JSON format * * @param wikiContext the XWiki context * @return a representation of this package under the JSON format * @since 2.2M1 */ public JSONObject toJSON(XWikiContext wikiContext) { Map<String, Object> json = new HashMap<String, Object>(); Map<String, Object> infos = new HashMap<String, Object>(); infos.put("name", this.name); infos.put("description", this.description); infos.put("licence", this.licence); infos.put("author", this.authorName); infos.put("version", this.version); infos.put("backup", this.isBackupPack()); Map<String, Map<String, List<Map<String, String>>>> files = new HashMap<String, Map<String, List<Map<String, String>>>>(); for (DocumentInfo docInfo : this.files) { Map<String, String> fileInfos = new HashMap<String, String>(); fileInfos.put("defaultAction", String.valueOf(docInfo.getAction())); fileInfos.put("language", String.valueOf(docInfo.getLanguage())); fileInfos.put("fullName", docInfo.getFullName()); // If the space does not exist in the map of spaces, we create it. if (files.get(docInfo.getDoc().getSpace()) == null) { files.put(docInfo.getDoc().getSpace(), new HashMap<String, List<Map<String, String>>>()); } // If the document name does not exists in the space map of docs, we create it. if (files.get(docInfo.getDoc().getSpace()).get(docInfo.getDoc().getName()) == null) { files.get(docInfo.getDoc().getSpace()).put(docInfo.getDoc().getName(), new ArrayList<Map<String, String>>()); } // Finally we add the file infos (language, fullname and action) to the list of translations // for that document. files.get(docInfo.getDoc().getSpace()).get(docInfo.getDoc().getName()).add(fileInfos); } json.put("infos", infos); json.put("files", files); JSONObject jsonObject = JSONObject.fromObject(json); return jsonObject; } }
package com.cmput301.cia.intent; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import android.util.Pair; import android.view.View; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import com.cmput301.cia.R; import com.cmput301.cia.TestProfile; import com.cmput301.cia.activities.events.CreateHabitEventActivity; import com.cmput301.cia.activities.HomePageActivity; import com.cmput301.cia.activities.users.UserProfileActivity; import com.cmput301.cia.activities.users.ViewFollowedUsersActivity; import com.cmput301.cia.models.CompletedEventDisplay; import com.cmput301.cia.models.Follow; import com.cmput301.cia.models.Habit; import com.cmput301.cia.models.HabitEvent; import com.cmput301.cia.models.Profile; import com.cmput301.cia.utilities.ElasticSearchUtilities; import com.robotium.solo.Solo; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; public class ViewFollowedUsersIntentTests extends ActivityInstrumentationTestCase2<ViewFollowedUsersActivity> { private Solo solo; // the profile that is following all the other profiles private static Profile profile = null; public ViewFollowedUsersIntentTests() { super(ViewFollowedUsersActivity.class); } /** * initialize all necessary profiles if they have not been yet * @return the profile that is following all the other profiles * @throws InterruptedException */ private Profile init() throws InterruptedException { if (profile != null) return profile; // initialize all profiles that will be following another user List<Profile> profiles = new ArrayList<>(); // whether the database needs to be reset and have these profiles be recreated boolean needToReset = false; for (int i = 0; i < 15; ++i){ Profile profile = new Profile("vfutest" + i); Map<String, String> map = new HashMap<>(); map.put("name", profile.getName()); Pair<Profile, Boolean> result = ElasticSearchUtilities.getObject(Profile.TYPE_ID, Profile.class, map); assertTrue("database error", result.second); if (result.first != null) { profile = result.first; if (i == 2){ profiles.get(1).addFollowRequest(profiles.get(0)); Thread.sleep(200); profiles.get(1).acceptFollowRequest(profiles.get(0)); } } else { assertTrue("database error", profile.save()); needToReset = true; } profiles.add(profile); } if (needToReset) { Thread.sleep(1000); // remove existing follows from previous runs for (int i = 0; i < profiles.size(); ++i) { Map<String, String> map = new HashMap<>(); map.put("followerId", profiles.get(i).getId()); ElasticSearchUtilities.delete(Follow.TYPE_ID, Follow.class, map); map.clear(); map.put("followeeId", profiles.get(i).getId()); ElasticSearchUtilities.delete(Follow.TYPE_ID, Follow.class, map); } // for all profiles, generate 3 habits for the test for (int i = 0; i < profiles.size(); ++i) { for (int x = 0; x < 3; ++x) { String habitName = new StringBuilder(profiles.get(i).getId()).reverse().toString(); profiles.get(i).addHabit(new Habit(habitName, "", new Date(), new ArrayList<Integer>(), "xyz")); if (x == 1) { profiles.get(i).getHabits().get(x).addHabitEvent(new HabitEvent("xyz")); } } } // make all profiles follow the first one for (int i = 1; i < profiles.size(); ++i) { profiles.get(i).addFollowRequest(profiles.get(0)); Thread.sleep(200); profiles.get(i).acceptFollowRequest(profiles.get(0)); } // save all profiles due to how follow information is stored for (int i = 0; i < profiles.size(); ++i) assertTrue("database error", profiles.get(i).save()); Thread.sleep(1000); } profile = profiles.get(0); return profile; } public void setUp() throws Exception { Intent intent = new Intent(); intent.putExtra(ViewFollowedUsersActivity.ID_VIEWED, init()); setActivityIntent(intent); solo = new Solo(getInstrumentation(), getActivity()); Log.d("SETUP", "setUp()"); } /** * test the visibility of the views in the activity as certain buttons as pressed */ public void testVisibility() { assertTrue(solo.getView(R.id.vfuHabitsList).getVisibility() == View.INVISIBLE); assertTrue(solo.getView(R.id.vfuEventsList).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuUsersIcon).getVisibility() == View.INVISIBLE); assertTrue(solo.getView(R.id.vfuHistoryIcon).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuHistoryEventsSwitch).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuMapView).getVisibility() == View.VISIBLE); // switch to history view solo.clickOnView(solo.getView(R.id.vfuHistoryIcon)); solo.sleep(600); // habits list should still be invisible assertTrue(solo.getView(R.id.vfuHabitsList).getVisibility() == View.INVISIBLE); assertTrue(solo.getView(R.id.vfuEventsList).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuUsersIcon).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuHistoryIcon).getVisibility() == View.INVISIBLE); assertTrue(solo.getView(R.id.vfuHistoryEventsSwitch).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuMapView).getVisibility() == View.VISIBLE); // habits list should now be visible solo.clickOnView(solo.getView(R.id.vfuHistoryEventsSwitch)); solo.sleep(600); assertTrue(solo.getView(R.id.vfuHabitsList).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuEventsList).getVisibility() == View.INVISIBLE); assertTrue(solo.getView(R.id.vfuUsersIcon).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuHistoryIcon).getVisibility() == View.INVISIBLE); assertTrue(solo.getView(R.id.vfuHistoryEventsSwitch).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuMapView).getVisibility() == View.VISIBLE); // switch back to profile view solo.clickOnView(solo.getView(R.id.vfuUsersIcon)); solo.sleep(600); assertTrue(solo.getView(R.id.vfuUsersIcon).getVisibility() == View.INVISIBLE); assertTrue(solo.getView(R.id.vfuHistoryIcon).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuHistoryEventsSwitch).getVisibility() == View.VISIBLE); assertTrue(solo.getView(R.id.vfuMapView).getVisibility() == View.VISIBLE); } /** * test to make sure all followed profiles show up in the list */ public void testFollowingList(){ ListAdapter adapter = ((ListView)solo.getView(R.id.vfuProfilesList)).getAdapter(); for (Profile followed : profile.getFollowing()){ boolean found = false; for (int i = 0; i < adapter.getCount(); ++i){ if (adapter.getItem(i).equals(followed)){ found = true; break; } } assertTrue("profile not found in followed users listview", found); } } /** * test to make sure all followed profile's habits show up in the list */ public void testFollowingHabits(){ // switch to history view solo.clickOnView(solo.getView(R.id.vfuHistoryIcon)); solo.sleep(600); // habits list should now be visible solo.clickOnView(solo.getView(R.id.vfuHistoryEventsSwitch)); solo.sleep(600); // TODO change to string equals ListAdapter adapter = ((ListView)solo.getView(R.id.vfuHabitsList)).getAdapter(); for (Profile followed : profile.getFollowing()){ for (Habit habit : followed.getHabits()) { boolean found = false; for (int i = 0; i < adapter.getCount(); ++i) { if (adapter.getItem(i).equals(habit)) { found = true; break; } } assertTrue("habit not found in followed user habits listview", found); } } } /** * test to make sure all followed profile's habit events show up in the list, and are in sorted order */ public void testFollowingEvents(){ // switch to history view solo.clickOnView(solo.getView(R.id.vfuHistoryIcon)); solo.sleep(600); ListAdapter adapter = ((ListView)solo.getView(R.id.vfuEventsList)).getAdapter(); for (CompletedEventDisplay event : profile.getFollowedHabitHistory()){ boolean found = false; for (int i = 0; i < adapter.getCount(); ++i) { if (adapter.getItem(i).equals(event)) { found = true; break; } } assertTrue("habit not found in followed user habits listview", found); } } /** * test to make sure all views update when a user is unfollowed from this activity */ public void testUnfollowUpdate(){ int count = ((ListView)solo.getView(R.id.vfuProfilesList)).getAdapter().getCount(); solo.clickOnView(((ListView)solo.getView(R.id.vfuProfilesList)).getAdapter().getView(0, null, null)); solo.sleep(3000); solo.assertCurrentActivity("wrong activity", UserProfileActivity.class); solo.clickOnButton("Unfollow"); solo.sleep(1000); solo.goBack(); solo.sleep(3000); assertTrue("profile was not removed from list", ((ListView)solo.getView(R.id.vfuProfilesList)).getAdapter().getCount() == count - 1); } @Override public void tearDown() throws Exception{ solo.finishOpenedActivities(); } }
package cg.stevendende.deliciousrecipes.data; import android.annotation.TargetApi; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.ContentObserver; import android.database.Cursor; import android.database.sqlite.SQLiteConstraintException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.support.annotation.Nullable; import android.util.Log; public class RecipesContentProvider extends ContentProvider { // The URI Matcher used by this content provider. private static final UriMatcher sUriMatcher = buildUriMatcher(); private RecipesDBHelper mOpenHelper; static final int RECIPES = 100; static final int RECIPE = 101; static final int INGREDIENTS = 200; static final int RECIPE_STEPS = 300; static final int RECIPE_STEP = 301; /** * Implement this to initialize your content provider on startup. * This method is called for all registered content providers on the * application main thread at application launch time. It must not perform * lengthy operations, or application startup will be delayed. * <p> * <p>You should defer nontrivial initialization (such as opening, * upgrading, and scanning databases) until the content provider is used * (via {@link #query}, {@link #insert}, etc). Deferred initialization * keeps application startup fast, avoids unnecessary work if the provider * turns out not to be needed, and stops database errors (such as a full * disk) from halting application launch. * <p> * <p>If you use SQLite, {@link SQLiteOpenHelper} * is a helpful utility class that makes it easy to manage databases, * and will automatically defer opening until first use. If you do use * SQLiteOpenHelper, make sure to avoid calling * {@link SQLiteOpenHelper#getReadableDatabase} or * {@link SQLiteOpenHelper#getWritableDatabase} * from this method. (Instead, override * {@link SQLiteOpenHelper#onOpen} to initialize the * database when it is first opened.) * * @return true if the provider was successfully loaded, false otherwise */ @Override public boolean onCreate() { mOpenHelper = new RecipesDBHelper(getContext()); return true; } /* Students: Here is where you need to create the UriMatcher. This UriMatcher will match each URI to the WEATHER, WEATHER_WITH_LOCATION, WEATHER_WITH_LOCATION_AND_DATE, and LOCATION integer constants defined above. You can test this by uncommenting the testUriMatcher test within TestUriMatcher. */ static UriMatcher buildUriMatcher() { // All paths added to the UriMatcher have a corresponding code to return when a match is // found. The code passed into the constructor represents the code to return for the root // URI. It's common to use NO_MATCH as the code for this case. final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = RecipesContract.CONTENT_AUTHORITY; // All RECIPES matcher.addURI(authority, RecipesContract.PATH_RECIPES, RECIPES); // RECIPES by ID matcher.addURI(authority, RecipesContract.PATH_RECIPES + "/#", RECIPE); //INGREDIENTS matcher.addURI(authority, RecipesContract.PATH_RECIPE_INGREDIENTS, INGREDIENTS); //RECIPE STEPS matcher.addURI(authority, RecipesContract.PATH_RECIPE_STEPS, RECIPE_STEPS); matcher.addURI(authority, RecipesContract.PATH_RECIPE_STEPS + "/#", RECIPE_STEP); return matcher; } /** * Implement this to handle query requests from clients. * This method can be called from multiple threads, as described in * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes * and Threads</a>. * <p> * Example client call:<p> * <pre>// Request a specific record. * Cursor managedCursor = managedQuery( * ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2), * projection, // Which columns to return. * null, // WHERE clause. * null, // WHERE clause value substitution * People.NAME + " ASC"); // Sort order.</pre> * Example implementation:<p> * <pre>// SQLiteQueryBuilder is a helper class that creates the * // proper SQL syntax for us. * SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder(); * * // Set the table we're querying. * qBuilder.setTables(DATABASE_TABLE_NAME); * * // If the query ends in a specific record number, we're * // being asked for a specific record, so set the * // WHERE clause in our query. * if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){ * qBuilder.appendWhere("_id=" + uri.getPathLeafId()); * } * * // Make the query. * Cursor c = qBuilder.query(mDb, * projection, * selection, * selectionArgs, * groupBy, * having, * sortOrder); * c.setNotificationUri(getContext().getContentResolver(), uri); * return c;</pre> * * @param uri The URI to query. This will be the full URI sent by the client; * if the client is requesting a specific record, the URI will end in a record number * that the implementation should parse and add to a WHERE or HAVING clause, specifying * that _id value. * @param projection The list of columns to put into the cursor. If * {@code null} all columns are included. * @param selection A selection criteria to apply when filtering rows. * If {@code null} then all rows are included. * @param selectionArgs You may include ?s in selection, which will be replaced by * the values from selectionArgs, in order that they appear in the selection. * The values will be bound as Strings. * @param sortOrder How the rows in the cursor should be sorted. * If {@code null} then the provider is free to define the sort order. * @return a Cursor or {@code null}. */ @Nullable @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Cursor returnCursor = null; switch (sUriMatcher.match(uri)) { case RECIPES: { returnCursor = mOpenHelper.getReadableDatabase().query( RecipesContract.RecipeEntry.TABLE_NAME, RecipesContract.RecipeEntry.COLUMNS_RECIPES, selection, selectionArgs, null, null, RecipesContract.RecipeEntry.TABLE_NAME+"."+RecipesContract.RecipeEntry._ID+" DESC" ); } break; case INGREDIENTS: { returnCursor = mOpenHelper.getReadableDatabase().query( RecipesContract.IngredientEntry.TABLE_NAME, RecipesContract.IngredientEntry.COLUMNS_INGREDIENTS, selection, selectionArgs, null, null, RecipesContract.RecipeEntry.TABLE_NAME+"."+RecipesContract.RecipeEntry._ID ); } break; case RECIPE_STEPS: { returnCursor = mOpenHelper.getReadableDatabase().query( RecipesContract.RecipeStepEntry.TABLE_NAME, RecipesContract.RecipeStepEntry.COLUMNS_STEPS, selection, selectionArgs, null, null, RecipesContract.RecipeStepEntry.TABLE_NAME+"."+RecipesContract.RecipeStepEntry._ID ); } break; } return returnCursor; } @Nullable @Override public String getType(Uri uri) { // we use the Uri Matcher to determine what kind of URI it is. final int uriType = sUriMatcher.match(uri); switch (uriType) { case RECIPES: return RecipesContract.RecipeEntry.CONTENT_TYPE; case RECIPE: return RecipesContract.RecipeEntry.CONTENT_TYPE; case INGREDIENTS: return RecipesContract.IngredientEntry.CONTENT_TYPE; case RECIPE_STEPS: return RecipesContract.RecipeStepEntry.CONTENT_TYPE; case RECIPE_STEP: return RecipesContract.RecipeStepEntry.CONTENT_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** * Implement this to handle requests to insert a new row. * As a courtesy, call {@link android.content.ContentResolver#notifyChange(Uri, ContentObserver) notifyChange()} * after inserting. * This method can be called from multiple threads, as described in * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes * and Threads</a>. * * @param uri The content:// URI of the insertion request. This must not be {@code null}. * @param values A set of column_name/value pairs to add to the database. * This must not be {@code null}. * @return The URI for the newly inserted item. */ @Nullable @Override public Uri insert(Uri uri, ContentValues values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); Uri returnUri = uri; switch (match) { case RECIPES: { long _id = 0; try { _id = db.insertOrThrow(RecipesContract.RecipeEntry.TABLE_NAME, null, values); } catch (SQLiteConstraintException ex) { ex.printStackTrace(); } if (_id > 0) returnUri = RecipesContract.RecipeEntry.buildRecipeUri(values.getAsLong(RecipesContract.RecipeEntry._ID)); break; } case INGREDIENTS: { long _id = 0; try { _id = db.insertOrThrow(RecipesContract.IngredientEntry.TABLE_NAME, null, values); } catch (SQLiteConstraintException ex) { ex.printStackTrace(); } if (_id > 0) returnUri = RecipesContract.IngredientEntry.buildIngedientUri(values.getAsLong(RecipesContract.IngredientEntry._ID)); break; } case RECIPE_STEPS: { long _id = 0; try { _id = db.insertOrThrow(RecipesContract.RecipeStepEntry.TABLE_NAME, null, values); } catch (SQLiteConstraintException ex) { ex.printStackTrace(); } if (_id > 0) returnUri = RecipesContract.RecipeStepEntry.buildStepUri(values.getAsLong(RecipesContract.RecipeStepEntry._ID)); break; } } return returnUri; } /** * Implement this to handle requests to delete one or more rows. * The implementation should apply the selection clause when performing * deletion, allowing the operation to affect multiple rows in a directory. * As a courtesy, call {@link android.content.ContentResolver#notifyChange(Uri, ContentObserver) notifyChange()} * after deleting. * This method can be called from multiple threads, as described in * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes * and Threads</a>. * <p> * <p>The implementation is responsible for parsing out a row ID at the end * of the URI, if a specific row is being deleted. That is, the client would * pass in <code>content://contacts/people/22</code> and the implementation is * responsible for parsing the record number (22) when creating a SQL statement. * * @param uri The full URI to query, including a row ID (if a specific record is requested). * @param selection An optional restriction to apply to rows when deleting. * @param selectionArgs * @return The number of rows affected. */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int rowsDeleted = 0; String deleteId; // this makes delete all rows return the number of rows deleted //if (null == selection) selection = "1"; switch (match) { case RECIPES: deleteId = uri.getLastPathSegment(); selectionArgs = new String[]{deleteId}; rowsDeleted = db.delete( RecipesContract.RecipeEntry.TABLE_NAME, RecipesContract.RecipeEntry._ID+"=?", selectionArgs); break; case INGREDIENTS: deleteId = uri.getLastPathSegment(); selectionArgs = new String[]{deleteId}; rowsDeleted = db.delete( RecipesContract.IngredientEntry.TABLE_NAME, RecipesContract.IngredientEntry._ID+"=?", selectionArgs); break; case RECIPE_STEPS: deleteId = uri.getLastPathSegment(); selectionArgs = new String[]{deleteId}; rowsDeleted = db.delete( RecipesContract.RecipeStepEntry.TABLE_NAME, RecipesContract.RecipeStepEntry._ID+"=?", selectionArgs); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } //Because a null deletes all rows if (rowsDeleted != 0) { getContext().getContentResolver().notifyChange(uri, null); } return rowsDeleted; } /** * Implement this to handle requests to update one or more rows. * The implementation should update all rows matching the selection * to set the columns according to the provided values map. * As a courtesy, call {@link android.content.ContentResolver#notifyChange(Uri, ContentObserver) notifyChange()} * after updating. * This method can be called from multiple threads, as described in * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes * and Threads</a>. * * @param uri The URI to query. This can potentially have a record ID if this * is an update request for a specific record. * @param values A set of column_name/value pairs to update in the database. * This must not be {@code null}. * @param selection An optional filter to match rows to update. * @param selectionArgs * @return the number of rows affected. */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int rowsUpdated = 0; switch (match){ case RECIPES: if(selectionArgs == null) { selectionArgs = new String[]{RecipesContract.RecipeEntry.getRecipeIdFromUri(uri)+""}; } rowsUpdated = db.update( RecipesContract.RecipeEntry.TABLE_NAME, values, RecipesContract.RecipeEntry.TABLE_NAME + "." + RecipesContract.RecipeEntry._ID + "=?", selectionArgs); break; case INGREDIENTS: if(selectionArgs == null) { selectionArgs = new String[]{uri.getLastPathSegment()}; } rowsUpdated = db.update( RecipesContract.IngredientEntry.TABLE_NAME, values, RecipesContract.IngredientEntry.TABLE_NAME + "." + RecipesContract.IngredientEntry._ID + "=?", selectionArgs); break; case RECIPE_STEPS: if(selectionArgs == null) { selectionArgs = new String[]{uri.getLastPathSegment()}; } rowsUpdated = db.update( RecipesContract.RecipeStepEntry.TABLE_NAME, values, RecipesContract.RecipeStepEntry.TABLE_NAME + "." + RecipesContract.RecipeStepEntry._ID + "=?", selectionArgs); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } if (rowsUpdated != 0) { getContext().getContentResolver().notifyChange(uri, null); Log.i("change notified", "change has notified update for " + uri); } return rowsUpdated; } @Override public int bulkInsert(Uri uri, ContentValues[] values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int returnCount = 0; switch (match) { case RECIPES: db.beginTransaction(); try { for (ContentValues value : values) { try { long _id = db.insertOrThrow(RecipesContract.RecipeEntry.TABLE_NAME, null, value); if (_id != -1) { returnCount++; } } catch (SQLiteConstraintException ex) { ex.printStackTrace(); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } break; case INGREDIENTS: db.beginTransaction(); try { for (ContentValues value : values) { try { long _id = db.insertOrThrow(RecipesContract.IngredientEntry.TABLE_NAME, null, value); if (_id != -1) { returnCount++; } } catch (SQLiteConstraintException ex) { ex.printStackTrace(); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } break; case RECIPE_STEPS: db.beginTransaction(); try { for (ContentValues value : values) { try { long _id = db.insertOrThrow(RecipesContract.RecipeStepEntry.TABLE_NAME, null, value); if (_id != -1) { returnCount++; } } catch (SQLiteConstraintException ex) { ex.printStackTrace(); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } break; default: return super.bulkInsert(uri, values); } if(returnCount>0) { getContext().getContentResolver().notifyChange(uri, null); } return returnCount; } // This is a method specifically to assist the testing framework in running smoothly. // avoids a conflict by providing a way to terminate the ContentProvider while in andoidTest // more at: // http://developer.android.com/reference/android/content/ContentProvider.html#shutdown() @Override @TargetApi(11) public void shutdown() { mOpenHelper.close(); super.shutdown(); } }
package com.mantralabsglobal.cashin.ui.fragment.tabs; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.mantralabsglobal.cashin.R; import com.mantralabsglobal.cashin.service.IncomeService; import com.mantralabsglobal.cashin.ui.Application; import com.mantralabsglobal.cashin.ui.activity.app.MainActivity; import com.mantralabsglobal.cashin.ui.view.CustomEditText; import com.mantralabsglobal.cashin.ui.view.MonthIncomeView; import com.mobsandgeeks.saripaar.annotation.Digits; import com.mobsandgeeks.saripaar.annotation.NotEmpty; import com.mobsandgeeks.saripaar.annotation.ValidateUsing; import java.text.DateFormatSymbols; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import butterknife.InjectView; import retrofit.Callback; public class IncomeFragment extends BaseBindableListFragment<IncomeService.Income> { @NotEmpty @Digits(integer = 6) @InjectView(R.id.cc_month_one) public MonthIncomeView monthIncomeViewOne; @Digits(integer = 6) @NotEmpty @InjectView(R.id.cc_month_two) public MonthIncomeView monthIncomeViewTwo; @Digits (integer = 6) @NotEmpty @InjectView(R.id.cc_month_three) public MonthIncomeView monthIncomeViewThree; @InjectView(R.id.vg_form) ViewGroup vg_form; IncomeService incomeService; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Get the view from fragmenttab1.xml View view = inflater.inflate(R.layout.fragment_income, container, false); return view; } @Override protected View getFormView() { return vg_form; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); incomeService = ((Application)getActivity().getApplication()).getRestClient().getIncomeService(); reset(false); } @Override protected void onUpdate(List<IncomeService.Income> updatedData, Callback<List<IncomeService.Income>> saveCallback) { onCreate(updatedData, saveCallback); } @Override protected void onCreate(List<IncomeService.Income> updatedData, Callback<List<IncomeService.Income>> saveCallback) { incomeService.createIncome(updatedData, saveCallback); } @Override protected void loadDataFromServer(Callback<List<IncomeService.Income>> dataCallback) { incomeService.getIncomeDetail(dataCallback); } @Override protected void handleDataNotPresentOnServer() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -1); monthIncomeViewOne.setMonth(cal.get(Calendar.MONTH)); monthIncomeViewOne.setYear(cal.get(Calendar.YEAR)); monthIncomeViewOne.setAmount(""); cal.add(Calendar.MONTH, -1); monthIncomeViewTwo.setMonth(cal.get(Calendar.MONTH)); monthIncomeViewTwo.setYear(cal.get(Calendar.YEAR)); monthIncomeViewTwo.setAmount(""); cal.add(Calendar.MONTH, -1); monthIncomeViewThree.setMonth(cal.get(Calendar.MONTH)); monthIncomeViewThree.setYear(cal.get(Calendar.YEAR)); monthIncomeViewThree.setAmount(""); } @Override public void bindDataToForm(List<IncomeService.Income> value) { if(value.size()>0) { monthIncomeViewOne.setYear(value.get(0).getYear()); monthIncomeViewOne.setMonth(value.get(0).getMonth()-1); monthIncomeViewOne.setAmount(String.valueOf(value.get(0).getAmount())); } if(value.size()>1) { monthIncomeViewTwo.setYear(value.get(1).getYear()); monthIncomeViewTwo.setMonth(value.get(1).getMonth()-1); monthIncomeViewTwo.setAmount(String.valueOf(value.get(1).getAmount())); } if(value.size()>2) { monthIncomeViewThree.setYear(value.get(2).getYear()); monthIncomeViewThree.setMonth(value.get(2).getMonth()-1); monthIncomeViewThree.setAmount(String.valueOf(value.get(2).getAmount())); } } @Override public List<IncomeService.Income> getDataFromForm(List<IncomeService.Income> base) { if(base == null) { base = new ArrayList<>(); } while(base.size()<3) { base.add(new IncomeService.Income()); } base.get(0).setYear(monthIncomeViewOne.getYear()); base.get(0).setMonth(monthIncomeViewOne.getMonth() + 1); if(monthIncomeViewOne.getAmount() != null && monthIncomeViewOne.getAmount().toString().length() > 0) base.get(0).setAmount(Double.parseDouble(monthIncomeViewOne.getAmount().toString())); base.get(1).setYear(monthIncomeViewTwo.getYear()); base.get(1).setMonth(monthIncomeViewTwo.getMonth() + 1); if(monthIncomeViewTwo.getAmount() != null && monthIncomeViewTwo.getAmount().toString().length() > 0) base.get(1).setAmount(Double.parseDouble(monthIncomeViewTwo.getAmount().toString())); base.get(2).setYear(monthIncomeViewThree.getYear()); base.get(2).setMonth(monthIncomeViewThree.getMonth() + 1); if(monthIncomeViewThree.getAmount() != null && monthIncomeViewThree.getAmount().toString().length() > 0) base.get(2).setAmount( Double.parseDouble(monthIncomeViewThree.getAmount().toString())); return base; } @Override public boolean isFormValid() { List<IncomeService.Income> incomeList = getDataFromForm(null); for(IncomeService.Income income:incomeList) { if(income.getAmount()<=0) return false; } return true; } }
package ve.com.abicelis.remindy.app.dialogs; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import ve.com.abicelis.remindy.R; public class EditPlaceDialogFragment extends DialogFragment implements View.OnClickListener { private EditPlaceDialogDismissListener mListener; private EditText mAlias; private EditText mAddress; private Button mCancel; private Button mOk; public EditPlaceDialogFragment() { // Empty constructor is required for DialogFragment // Make sure not to add arguments to the constructor // Use `newInstance` instead as shown below } public static EditPlaceDialogFragment newInstance(String alias, String address) { EditPlaceDialogFragment frag = new EditPlaceDialogFragment(); Bundle args = new Bundle(); args.putString("alias", alias); args.putString("address", address); frag.setArguments(args); return frag; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final String alias = getArguments().getString("alias"); final String address = getArguments().getString("address"); View dialogView = inflater.inflate(R.layout.dialog_edit_place, container); mAlias = (EditText) dialogView.findViewById(R.id.dialog_edit_place_alias); mAlias.setText(alias); mAddress = (EditText) dialogView.findViewById(R.id.dialog_edit_place_address); mAddress.setText(address); mOk = (Button) dialogView.findViewById(R.id.dialog_edit_place_ok); mOk.setOnClickListener(this); mCancel = (Button) dialogView.findViewById(R.id.dialog_edit_place_cancel); mCancel.setOnClickListener(this); getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); return dialogView; } @Override public void onClick(View v) { int id = v.getId(); switch(id) { case R.id.dialog_edit_place_cancel: dismiss(); break; case R.id.dialog_edit_place_ok: mListener.onFinishEditPlaceDialog(mAlias.getText().toString().trim(), mAddress.getText().toString().trim()); dismiss(); break; } } public void setListener(EditPlaceDialogDismissListener listener) { mListener = listener; } public interface EditPlaceDialogDismissListener { void onFinishEditPlaceDialog(String alias, String address); } }
package org.aracrown.commons.security; import org.apache.shiro.authc.AuthenticationToken; public class UsernamePasswordToken implements AuthenticationToken{ private static final long serialVersionUID = 1L; /** * The username */ private final String username; /** * The password, in char[] format */ private final char[] password; private final String remoteAddress; public UsernamePasswordToken(final String username, final String password, String remoteAddress) { this.username = username; this.password = password != null ? password.toCharArray() : null; this.remoteAddress = remoteAddress; } public String getRemoteAddress() { return remoteAddress; } /** * @return the username */ public String getUsername() { return username; } /** * @return the password */ public char[] getPassword() { return password; } @Override public Object getPrincipal() { return username; } @Override public Object getCredentials() { return password; } }
package com.hubspot.jinjava.benchmarks.jinja2; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.interpret.JinjavaInterpreter; import com.hubspot.jinjava.loader.FileLocator; import com.hubspot.jinjava.loader.ResourceLocator; @State(Scope.Benchmark) public class Jinja2Benchmark { public String complexTemplate; public Map<String, ?> complexBindings; public Jinjava jinjava; @SuppressWarnings("unchecked") @Setup public void setup() throws IOException, NoSuchAlgorithmException { ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); logger.setLevel(Level.WARN); jinjava = new Jinjava(); JinjavaInterpreter interpreter = new JinjavaInterpreter(jinjava, jinjava.getGlobalContext(), jinjava.getGlobalConfig()); FileLocator locator = new FileLocator(new File("jinja2/examples/rwbench/jinja")); final String helpersTemplate = locator.getString("helpers.html", Charsets.UTF_8, interpreter); final String indexTemplate = locator.getString("index.html", Charsets.UTF_8, interpreter); final String layoutTemplate = locator.getString("layout.html", Charsets.UTF_8, interpreter); jinjava.setResourceLocator(new ResourceLocator() { @Override public String getString(String fullName, Charset encoding, JinjavaInterpreter interpreter) throws IOException { switch(fullName) { case "helpers.html": return helpersTemplate; case "layout.html": return layoutTemplate; case "index.html": return indexTemplate; } return null; } }); complexTemplate = indexTemplate; // for tag doesn't support postfix conditional filtering complexTemplate = complexTemplate.replaceAll(" if article.published", ""); List<User> users = Lists.newArrayList(new User("John Doe"), new User("Jane Doe"), new User("Peter Somewhat")); SecureRandom rnd = SecureRandom.getInstanceStrong(); List<Article> articles = new ArrayList<>(); for(int i = 0; i < 20; i++) { articles.add(new Article(i, users.get(rnd.nextInt(users.size())))); } List<ArrayList<String>> navigation = Lists.newArrayList( Lists.newArrayList("index", "Index"), Lists.newArrayList("about", "About"), Lists.newArrayList("foo?bar=1", "Foo with Bar"), Lists.newArrayList("foo?bar=2&s=x", "Foo with X"), Lists.newArrayList("blah", "Blub Blah"), Lists.newArrayList("hehe", "Haha") ); complexBindings = ImmutableMap.of("users", users, "articles", articles, "navigation", navigation); } @Benchmark public String realWorldishBenchmark() { return jinjava.render(complexTemplate, complexBindings); } public static void main(String[] args) throws Exception { Jinja2Benchmark b = new Jinja2Benchmark(); b.setup(); System.out.println(b.realWorldishBenchmark()); } }
package com.itranswarp.bitcoin.serializer; import java.io.IOException; import org.bouncycastle.util.Arrays; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.itranswarp.bitcoin.util.HashUtils; /** * Serialize byte[] to hash string (byte[] reversed). * * @author Michael Liao */ public class HashSerializer extends JsonSerializer<byte[]> { @Override public void serialize(byte[] value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { String s = HashUtils.toHexString(Arrays.reverse(value)); gen.writeString(s); } }
package com.box.androidsdk.share.vm; import androidx.annotation.VisibleForTesting; import androidx.lifecycle.LiveData; import androidx.lifecycle.Transformations; import com.box.androidsdk.content.BoxException; import com.box.androidsdk.content.models.BoxCollaboration; import com.box.androidsdk.content.models.BoxCollaborationItem; import com.box.androidsdk.content.models.BoxUser; import com.box.androidsdk.content.requests.BoxRequestsShare; import com.box.androidsdk.content.requests.BoxResponse; import com.box.androidsdk.content.requests.BoxResponseBatch; import com.box.androidsdk.content.utils.SdkUtils; import com.box.androidsdk.share.R; import com.box.androidsdk.share.internal.models.BoxIteratorInvitees; import com.box.androidsdk.share.sharerepo.BaseShareRepo; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * A ViewModel for holding data needed for InviteCollaborators Screen */ public class InviteCollaboratorsVM extends BaseVM { private LiveData<DataWrapper<BoxCollaborationItem>> mFetchRoleItem; private LiveData<InviteCollaboratorsDataWrapper> mAddCollabs; private LiveData<DataWrapper<BoxIteratorInvitees>> mInvitees; public InviteCollaboratorsVM(BaseShareRepo shareRepo, BoxCollaborationItem shareItem) { super(shareRepo, shareItem); mFetchRoleItem = Transformations.map(shareRepo.getFetchRoleItem(), response -> createFetchRoleItemData(response)); mAddCollabs = Transformations.map(shareRepo.getInviteCollabBatch(), response -> createAddCollabsItemData(response)); mInvitees = Transformations.map(shareRepo.getInvitees(), response -> createGetInviteesItemData(response)); } /** * Makes a backend call through share repo for fetching roles. * @param item the item to fetch roles on */ public void fetchRolesApi(BoxCollaborationItem item) { mShareRepo.fetchRolesApi(item); } /** * Makes a backend call through share repo for adding new collaborators. * @param boxCollaborationItem the item to add collaborators on * @param selectedRole the role for the new collaborators * @param emails a list of collaborators represented in emails */ public void addCollabsApi(BoxCollaborationItem boxCollaborationItem, BoxCollaboration.Role selectedRole, String[] emails) { mShareRepo.addCollabsApi(boxCollaborationItem, selectedRole, emails); } /** * Makes a backend call through share repo for getting invitees. * @param boxCollaborationItem the item to get invitees on * @param filter the term used for filtering invitees */ public void getInviteesApi(BoxCollaborationItem boxCollaborationItem, String filter) { mShareRepo.getInviteesApi(boxCollaborationItem, filter); } /** * Returns a LiveData which holds a data wrapper that contains a box item that has allowed roles for invitees and a string resource code. * @return a LiveData which holds a data wrapper that contains box item that has allowed roles for invitees and a string resource code */ public LiveData<DataWrapper<BoxCollaborationItem>> getFetchRoleItem() { return mFetchRoleItem; } /** * Returns a LiveData which holds a data wrapper that contains the status message from the response for adding new collaborators. * @return a LiveData which holds a data wrapper that contains */ public LiveData<InviteCollaboratorsDataWrapper> getAddCollabs() { return mAddCollabs; } /** * Returns a LiveData which holds a data wrapper that contains a list of invitees that can be invited and a string resource code. * @return a LiveData which holds a data wrapper that contains a list of invitees that can be invited and a string resource code */ public LiveData<DataWrapper<BoxIteratorInvitees>> getInvitees() { return mInvitees; } /** * Helper method for transforming BoxResponse to UI Model for fetchRoleApi * @param response the response to transform on * @return the transformed data */ private DataWrapper<BoxCollaborationItem> createFetchRoleItemData(BoxResponse<BoxCollaborationItem> response) { final DataWrapper<BoxCollaborationItem> data = new DataWrapper<BoxCollaborationItem>(); if (response.isSuccess()) { BoxCollaborationItem collaborationItem = response.getResult(); data.success(collaborationItem); } else { data.failure(R.string.box_sharesdk_network_error); } return data; } /** * Helper method for transforming BoxResponse to UI Model for getInviteesApi * @param response the response to transform * @return the transformed model */ private DataWrapper<BoxIteratorInvitees> createGetInviteesItemData(BoxResponse<BoxIteratorInvitees> response) { final DataWrapper<BoxIteratorInvitees> data = new DataWrapper<BoxIteratorInvitees>(); if (response.isSuccess()) { final BoxIteratorInvitees invitees = response.getResult(); data.success(invitees); } else { BoxException boxException = (BoxException) response.getException(); int responseCode = boxException.getResponseCode(); int strCode = -1; if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { strCode = R.string.box_sharesdk_insufficient_permissions; } else if (boxException.getErrorType() == BoxException.ErrorType.NETWORK_ERROR) { strCode = R.string.box_sharesdk_network_error; } data.failure(strCode); } return data; } /** * Helper method for transforming BoxResponse to UI Model for addCollabsApi * @param response the response to transform * @return the transformed model */ private InviteCollaboratorsDataWrapper createAddCollabsItemData(BoxResponse<BoxResponseBatch> response) { return handleCollaboratorsInvited(response.getResult()); } /** * Helper method for helping with transformation of BoxBatchResponse to UI Model * @param responses the batch response to transform * @return the transformed model */ @VisibleForTesting private InviteCollaboratorsDataWrapper handleCollaboratorsInvited(BoxResponseBatch responses) { int strCode = R.string.box_sharesdk_generic_error; //default generic error boolean mInvitationFailed; String subMssg = null; int alreadyAddedCount = 0; boolean didRequestFail = false; String name = ""; HashSet<Integer> failureCodes = generateFailureCodes(); List<String> failedCollaboratorsList = new ArrayList<>(); for (BoxResponse<BoxCollaboration> r : responses.getResponses()) { if (!r.isSuccess()) { if (checkIfKnownFailure(r, failureCodes)) { name = updateFailureStats(r, failedCollaboratorsList); alreadyAddedCount += name != null ? 1 : 0; } didRequestFail = true; } } if (didRequestFail) { String[] result = processRequestFailure(failedCollaboratorsList, name, alreadyAddedCount); strCode = Integer.parseInt(result[0]); subMssg = result[1]; } else { String[] result = processRequestSuccess(responses); strCode = Integer.parseInt(result[0]); subMssg = result[1]; } mInvitationFailed = (didRequestFail && !failedCollaboratorsList.isEmpty()); return new InviteCollaboratorsDataWrapper(subMssg, strCode, mInvitationFailed); } /** * A helper method for updating attributes used for keeping track of stats for failure * @param r the response to get request infos from * @param failedCollaboratorsList list of failed collabs to be updated * @return the name of collaborator that is already added */ @VisibleForTesting String updateFailureStats(BoxResponse<BoxCollaboration> r, List<String> failedCollaboratorsList) { String code = ((BoxException) r.getException()).getAsBoxError().getCode(); BoxUser user = (BoxUser) ((BoxRequestsShare.AddCollaboration) r.getRequest()).getAccessibleBy(); if (alreadyAddedFailure(code)) { return user == null ? "" : user.getLogin(); } else { failedCollaboratorsList.add(user == null ? "" : user.getLogin()); return null; } } /** * Helper method for processing request if all requests were successful * @param responses the responses that was successful * @return index 0 is string resource code, index 1 is the string formatted part of the message. */ @VisibleForTesting String[] processRequestSuccess(BoxResponseBatch responses) { String[] res = new String[2]; if (responses.getResponses().size() == 1) { BoxCollaboration collaboration = (BoxCollaboration) responses.getResponses().get(0).getResult(); if (collaboration.getAccessibleBy() == null) { res[0] = Integer.toString(R.string.box_sharesdk_collaborators_invited); } else { String login = ((BoxUser)(collaboration).getAccessibleBy()).getLogin(); res[0] = Integer.toString(R.string.box_sharesdk_collaborator_invited); res[1] = login; } } else { res[0] = Integer.toString(R.string.box_sharesdk_collaborators_invited); } return res; } /** * Helper method for processing request if any requests were successful * @param failedCollaboratorsList the list of collaborators for whom requests were not successful * @param name the name of a collaborator that is already added * @param alreadyAddedCount how many collaborators were already added * @return index 0 is string resource code, index 1 is the string formatted part of the message. */ @VisibleForTesting String[] processRequestFailure(List<String> failedCollaboratorsList, String name, int alreadyAddedCount) { String[] res = new String[2]; if (!failedCollaboratorsList.isEmpty()) { StringBuilder collaborators = new StringBuilder(); for (int i = 0; i < failedCollaboratorsList.size(); i++) { collaborators.append(failedCollaboratorsList.get(i)); if (i < failedCollaboratorsList.size() - 1) { collaborators.append(' '); } } res[0] = Integer.toString(R.string.box_sharesdk_following_collaborators_error); res[1] = collaborators.toString(); } else if (alreadyAddedCount == 1) { res[0] = Integer.toString(R.string.box_sharesdk_has_already_been_invited); res[1] = name; } else if (alreadyAddedCount > 1) { res[0] = Integer.toString(R.string.box_sharesdk_num_has_already_been_invited); res[1] = Integer.toString(alreadyAddedCount); } else { res[0] = Integer.toString(R.string.box_sharesdk_unable_to_invite); } return res; } private boolean alreadyAddedFailure(String code) { return !SdkUtils.isBlank(code) && code.equals(BoxRequestsShare.AddCollaboration.ERROR_CODE_USER_ALREADY_COLLABORATOR); } private boolean checkIfKnownFailure(BoxResponse<BoxCollaboration> r, HashSet<Integer> failureCodes) { return r.getException() instanceof BoxException && failureCodes.contains(((BoxException) r.getException()).getResponseCode()); } /** * Generates failure codes for checking known errors * @return a HashSet of known errors */ private HashSet<Integer> generateFailureCodes() { HashSet<Integer> failureCodes = new HashSet<>(); failureCodes.add(HttpURLConnection.HTTP_BAD_REQUEST ); failureCodes.add(HttpURLConnection.HTTP_FORBIDDEN); return failureCodes; } }
package io.loaders.json; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; import algorithms.utils.Coverage; import algorithms.utils.Match; import db.CoveragesDB; import db.DB; import db.FamilyDB; import db.ResiduesDB; import model.ChemicalObject; import model.Monomer; import model.Residue; import model.graph.ContractedGraph; import model.graph.MonomerGraph; import model.graph.MonomerGraph.MonomerLinks; public class CoveragesJsonLoader extends AbstractJsonLoader<CoveragesDB, Coverage> { private DB<? extends ChemicalObject> db; private FamilyDB families; private ResiduesDB residues; public CoveragesJsonLoader(DB<? extends ChemicalObject> db, FamilyDB families) { this.db = db; this.families = families; this.residues = families.getResidues(); } @Override protected CoveragesDB createDB() { return new CoveragesDB(); } @Override protected Coverage objectFromJson(JSONObject obj) { ChemicalObject co = null; try { co = this.db.getObject("" + ((Number)obj.get("peptide")).intValue()); } catch (NullPointerException e) { System.err.println(e.getMessage()); System.err.println("Maybe coverage json and molecule json don't match"); System.exit(2); } Coverage cov = new Coverage(co); JSONArray array = (JSONArray) obj.get("matches"); for (Object o : array) { JSONObject jso = (JSONObject)o; Residue res = null; try { res = this.residues.getObject("" + ((Number)jso.get("residue")).intValue()); } catch (NullPointerException e) { e.printStackTrace(); } JSONObject jMatch = (JSONObject)jso.get("match"); Match match = new Match(res); JSONArray atoms = (JSONArray) jMatch.get("atoms"); for (Object atObj : atoms) { JSONObject atom = (JSONObject) atObj; int idx = ((Number)atom.get("a")).intValue(); match.addAtom(idx); match.addHydrogens(idx, ((Number)atom.get("h")).intValue()); } JSONArray bonds = (JSONArray) jMatch.get("bonds"); for (Object boObj : bonds) { int bond = ((Number) boObj).intValue(); match.addBond(bond); } cov.addMatch(match); } cov.calculateGreedyCoverage(); return cov; } @Override protected String getObjectId(Coverage tObj) { return tObj.getId(); } @SuppressWarnings("unchecked") @Override protected JSONArray getArrayOfElements(Coverage cov) { JSONArray array = new JSONArray(); JSONObject obj = new JSONObject(); obj.put("id", cov.getId()); //obj.put("pepId", cov.getChemicalObject()) obj.put("peptide", new Integer(cov.getChemicalObject().getId())); obj.put("peptideName", cov.getChemicalObject().getName()); obj.put("atomic_graph", this.getJSONMatches(cov)); obj.put("monomeric_graph", this.getJSONGraph(cov)); obj.put("coverage", cov.getCoverageRatio()); array.add(obj); return array; } @SuppressWarnings("unchecked") private JSONObject getJSONMatches(Coverage cov) { JSONObject graph = new JSONObject(); JSONArray atoms = new JSONArray(); graph.put("atoms", atoms); JSONArray bonds = new JSONArray(); graph.put("bonds", bonds); for (Match match : cov.getUsedMatches()) { // Atoms for (int a : match.getAtoms()) { JSONObject atom = new JSONObject(); // CDK informations atom.put("cdk_idx", a); // Atom informations IAtom ia = cov.getChemicalObject().getMolecule().getAtom(a); atom.put("name", ia.getSymbol()); atom.put("hdrogens", match.getHydrogensFrom(a)); // Residue informations atom.put("res", match.getResidue().getId()); atoms.add(atom); } // Bonds for (int b : match.getBonds()) { IBond ib = cov.getChemicalObject().getMolecule().getBond(b); JSONObject bond = new JSONObject(); // CDK informations bond.put("cdk_idx", b); // atoms linked JSONArray linkedAtoms = new JSONArray(); for (IAtom a : ib.atoms()) { linkedAtoms.add(cov.getChemicalObject().getMolecule().getAtomNumber(a)); } bond.put("arity", ib.getOrder().numeric()); bond.put("atoms", linkedAtoms); bond.put("res", match.getResidue().getId()); bonds.add(bond); } } return graph; } @SuppressWarnings("unchecked") private JSONObject getJSONGraph(Coverage cov) { ContractedGraph cg = new ContractedGraph(cov); MonomerGraph mg = cg.toMonomerGraph(families); JSONObject graph = new JSONObject(); // Monomers JSONArray monos = new JSONArray(); for (Monomer mono : mg.nodes) if (mono != null) monos.add(mono.getName()); else monos.add("?"); graph.put("monos", monos); // Residues (equivalent to monomers) JSONArray residues = new JSONArray(); for (Residue res : mg.residues) if (res != null) residues.add(res.getId()); else residues.add("?"); graph.put("residues", residues); // Links JSONArray links = new JSONArray(); for (MonomerLinks ml : mg.links) { JSONObject link = new JSONObject(); JSONArray idxs = new JSONArray(); idxs.add(ml.mono1); idxs.add(ml.mono2); link.put("idxs", idxs); links.add(link); } graph.put("links", links); return graph; } }
/* created 26 Oct 2008 for new cDVSTest chip * adapted apr 2011 for cDVStest30 chip by tobi * adapted 25 oct 2011 for SeeBetter10/11 chips by tobi * */ package eu.seebetter.ini.chips.sbret10; import ch.unizh.ini.jaer.config.cpld.CPLDInt; import java.awt.Font; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.media.opengl.GL; import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.swing.JFrame; import net.sf.jaer.Description; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.biasgen.BiasgenHardwareInterface; import net.sf.jaer.chip.RetinaExtractor; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.OutputEventIterator; import net.sf.jaer.event.TypedEvent; import net.sf.jaer.eventprocessing.filter.ApsDvsEventFilter; import net.sf.jaer.eventprocessing.filter.Info; import net.sf.jaer.eventprocessing.filter.RefractoryFilter; import net.sf.jaer.graphics.AEFrameChipRenderer; import net.sf.jaer.graphics.ChipRendererDisplayMethodRGBA; import net.sf.jaer.graphics.DisplayMethod; import net.sf.jaer.hardwareinterface.HardwareInterface; import net.sf.jaer.hardwareinterface.HardwareInterfaceException; import com.jogamp.opengl.util.awt.TextRenderer; import eu.seebetter.ini.chips.ApsDvsChip; import eu.seebetter.ini.chips.sbret10.IMUSample.IncompleteIMUSampleException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeSupport; import java.util.Observable; import java.util.Observer; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import net.sf.jaer.hardwareinterface.usb.cypressfx2.ApsDvsHardwareInterface; import net.sf.jaer.util.HasPropertyTooltips; import net.sf.jaer.util.HexString; import net.sf.jaer.util.PropertyTooltipSupport; import net.sf.jaer.util.RemoteControlCommand; import net.sf.jaer.util.RemoteControlled; import net.sf.jaer.util.histogram.AbstractHistogram; import net.sf.jaer.util.histogram.SimpleHistogram; /** * <p> * SBRet10/20 have 240x180 pixels and are built in 180nm technology. SBRet10 has * a rolling shutter APS readout and SBRet20 has global shutter readout (but * rolling shutter also possible with SBRet20 with different CPLD logic). Both * do APS CDS in digital domain off-chip, on host side, using difference between * reset and signal reads. * <p> * * Describes retina and its event extractor and bias generator. Two constructors * ara available, the vanilla constructor is used for event playback and the one * with a HardwareInterface parameter is useful for live capture. * {@link #setHardwareInterface} is used when the hardware interface is * constructed after the retina object. The constructor that takes a hardware * interface also constructs the biasgen interface. * * @author tobi, christian */ @Description("SBRet10/20 240x180 pixel APS-DVS DAVIS sensor") public class SBret10 extends ApsDvsChip implements RemoteControlled, Observer { private JMenu chipMenu = null; private JMenuItem syncEnabledMenuItem = null; private final int ADC_NUMBER_OF_TRAILING_ZEROS = Integer.numberOfTrailingZeros(ADC_READCYCLE_MASK); // speedup in loop // following define bit masks for various hardware data types. // The hardware interface translateEvents method packs the raw device data into 32 bit 'addresses' and timestamps. // timestamps are unwrapped and timestamp resets are handled in translateEvents. Addresses are filled with either AE or ADC data. // AEs are filled in according the XMASK, YMASK, XSHIFT, YSHIFT below. /** * bit masks/shifts for cDVS AE data */ private SBret10DisplayMethod sbretDisplayMethod = null; private AEFrameChipRenderer apsDVSrenderer; private int exposure; // internal measured variable, set during rendering private int frameTime; // internal measured variable, set during rendering /** * holds measured variable in Hz for GUI rendering of rate */ protected float frameRateHz; /** * holds measured variable in ms for GUI rendering */ protected float exposureMs; /** * Holds count of frames obtained by end of frame events */ private int frameCount = 0; private boolean snapshot = false; private boolean resetOnReadout = false; private SBret10config config; JFrame controlFrame = null; public static final short WIDTH = 240; public static final short HEIGHT = 180; int sx1 = getSizeX() - 1, sy1 = getSizeY() - 1; private int autoshotThresholdEvents = getPrefs().getInt("SBRet10.autoshotThresholdEvents", 0); private IMUSample imuSample; // latest IMUSample from sensor private final String CMD_EXPOSURE = "exposure"; private final String CMD_EXPOSURE_CC = "exposureCC"; private final String CMD_RS_SETTLE_CC = "resetSettleCC"; private AutoExposureController autoExposureController = new AutoExposureController(); /** * Creates a new instance of cDVSTest20. */ public SBret10() { setName("SBret10"); setDefaultPreferencesFile("../../biasgenSettings/sbret10/SBRet10.xml"); setEventClass(ApsDvsEvent.class); setSizeX(WIDTH); setSizeY(HEIGHT); setNumCellTypes(3); // two are polarity and last is intensity setPixelHeightUm(18.5f); setPixelWidthUm(18.5f); setEventExtractor(new SBret10Extractor(this)); setBiasgen(config = new SBret10config(this)); // hardware interface is ApsDvsHardwareInterface apsDVSrenderer = new AEFrameChipRenderer(this); apsDVSrenderer.setMaxADC(MAX_ADC); setRenderer(apsDVSrenderer); sbretDisplayMethod = new SBret10DisplayMethod(this); getCanvas().addDisplayMethod(sbretDisplayMethod); getCanvas().setDisplayMethod(sbretDisplayMethod); addDefaultEventFilter(ApsDvsEventFilter.class); addDefaultEventFilter(HotPixelFilter.class); addDefaultEventFilter(RefractoryFilter.class); addDefaultEventFilter(Info.class); if (getRemoteControl() != null) { getRemoteControl().addCommandListener(this, CMD_EXPOSURE, CMD_EXPOSURE + " val - sets exposure. val in ms."); getRemoteControl().addCommandListener(this, CMD_EXPOSURE_CC, CMD_EXPOSURE_CC + " val - sets exposure. val in clock cycles"); getRemoteControl().addCommandListener(this, CMD_RS_SETTLE_CC, CMD_RS_SETTLE_CC + " val - sets reset settling time. val in clock cycles"); } addObserver(this); // we observe ourselves so that if hardware interface for example calls notifyListeners we get informed } @Override public String processRemoteControlCommand(RemoteControlCommand command, String input) { log.info("processing RemoteControlCommand " + command + " with input=" + input); if (command == null) { return null; } String[] tokens = input.split(" "); if (tokens.length < 2) { return input + ": unknown command - did you forget the argument?"; } if (tokens[1] == null || tokens[1].length() == 0) { return input + ": argument too short - need a number"; } float v = 0; try { v = Float.parseFloat(tokens[1]); } catch (NumberFormatException e) { return input + ": bad argument? Caught " + e.toString(); } String c = command.getCmdName(); if (c.equals(CMD_EXPOSURE)) { config.setExposureDelayMs((int) v); } else if (c.equals(CMD_EXPOSURE_CC)) { config.exposure.set((int) v); } else if (c.equals(CMD_RS_SETTLE_CC)) { config.resSettle.set((int) v); } else { return input + ": unknown command"; } return "successfully processed command " + input; } @Override public void setPowerDown(boolean powerDown) { config.powerDown.set(powerDown); try { config.sendOnChipConfigChain(); } catch (HardwareInterfaceException ex) { Logger.getLogger(SBret10.class.getName()).log(Level.SEVERE, null, ex); } } /** * Creates a new instance of SBRet10 * * @param hardwareInterface an existing hardware interface. This constructor * is preferred. It makes a new cDVSTest10Biasgen object to talk to the * on-chip biasgen. */ public SBret10(HardwareInterface hardwareInterface) { this(); setHardwareInterface(hardwareInterface); } @Override public void controlExposure() { getAutoExposureController().controlExposure(); } /** * @return the autoExposureController */ public AutoExposureController getAutoExposureController() { return autoExposureController; } // int pixcnt=0; // TODO debug /** * The event extractor. Each pixel has two polarities 0 and 1. * * <p> * The bits in the raw data coming from the device are as follows. * <p> * Bit 0 is polarity, on=1, off=0<br> * Bits 1-9 are x address (max value 320)<br> * Bits 10-17 are y address (max value 240) <br> * <p> */ public class SBret10Extractor extends RetinaExtractor { private int firstFrameTs = 0; private int autoshotEventsSinceLastShot = 0; // autoshot counter private int warningCount = 0; private static final int WARNING_COUNT_DIVIDER = 10000; public SBret10Extractor(SBret10 chip) { super(chip); } private void lastADCevent() { //releases the reset after the readout of a frame if the DVS is suppressed during the DVS readout if (resetOnReadout) { config.nChipReset.set(true); } } private IncompleteIMUSampleException incompleteIMUSampleException = null; private static final int IMU_WARNING_INTERVAL = 1000; private int missedImuSampleCounter = 0; private int badImuDataCounter = 0; /** * extracts the meaning of the raw events. * * @param in the raw events, can be null * @return out the processed events. these are partially processed * in-place. empty packet is returned if null is supplied as in. */ @Override synchronized public EventPacket extractPacket(AEPacketRaw in) { if (!(chip instanceof ApsDvsChip)) { return null; } if (out == null) { out = new ApsDvsEventPacket(chip.getEventClass()); } else { out.clear(); } out.setRawPacket(in); if (in == null) { return out; } int n = in.getNumEvents(); //addresses.length; sx1 = chip.getSizeX() - 1; sy1 = chip.getSizeY() - 1; int[] datas = in.getAddresses(); int[] timestamps = in.getTimestamps(); OutputEventIterator outItr = out.outputIterator(); // NOTE we must make sure we write ApsDvsEvents when we want them, not reuse the IMUSamples // at this point the raw data from the USB IN packet has already been digested to extract timestamps, including timestamp wrap events and timestamp resets. // The datas array holds the data, which consists of a mixture of AEs and ADC values. // Here we extract the datas and leave the timestamps alone. // TODO entire rendering / processing approach is not very efficient now // System.out.println("Extracting new packet "+out); for (int i = 0; i < n; i++) { // TODO implement skipBy/subsampling, but without missing the frame start/end events and still delivering frames int data = datas[i]; if (incompleteIMUSampleException != null || (ApsDvsChip.ADDRESS_TYPE_IMU & data) == ApsDvsChip.ADDRESS_TYPE_IMU) { if (IMUSample.extractSampleTypeCode(data) == 0) { /// only start getting an IMUSample at code 0, the first sample type try { IMUSample possibleSample = IMUSample.constructFromAEPacketRaw(in, i, incompleteIMUSampleException); i += IMUSample.SIZE_EVENTS - 1; incompleteIMUSampleException = null; imuSample = possibleSample; // asking for sample from AEChip now gives this value, but no access to intermediate IMU samples imuSample.imuSampleEvent = true; outItr.writeToNextOutput(imuSample); // also write the event out to the next output event slot // System.out.println("at position "+(out.size-1)+" put "+imuSample); continue; } catch (IMUSample.IncompleteIMUSampleException ex) { incompleteIMUSampleException = ex; if (missedImuSampleCounter++ % IMU_WARNING_INTERVAL == 0) { log.warning(String.format("%s (obtained %d partial samples so far)", ex.toString(), missedImuSampleCounter)); } break; // break out of loop because this packet only contained part of an IMUSample and formed the end of the packet anyhow. Next time we come back here we will complete the IMUSample } catch (IMUSample.BadIMUDataException ex2) { if (badImuDataCounter++ % IMU_WARNING_INTERVAL == 0) { log.warning(String.format("%s (%d bad samples so far)", ex2.toString(), badImuDataCounter)); } incompleteIMUSampleException = null; continue; // continue because there may be other data } } } else if ((data & ApsDvsChip.ADDRESS_TYPE_MASK) == ApsDvsChip.ADDRESS_TYPE_DVS) { //DVS event ApsDvsEvent e = nextApsDvsEvent(outItr); if ((data & ApsDvsChip.EVENT_TYPE_MASK) == ApsDvsChip.EXTERNAL_INPUT_EVENT_ADDR) { e.adcSample = -1; // TODO hack to mark as not an ADC sample e.special = true; // TODO special is set here when capturing frames which will mess us up if this is an IMUSample used as a plain ApsDvsEvent e.address = data; e.timestamp = (timestamps[i]); e.setIsDVS(true); } else { e.adcSample = -1; // TODO hack to mark as not an ADC sample e.special = false; e.address = data; e.timestamp = (timestamps[i]); e.polarity = (data & POLMASK) == POLMASK ? ApsDvsEvent.Polarity.On : ApsDvsEvent.Polarity.Off; e.type = (byte) ((data & POLMASK) == POLMASK ? 1 : 0); e.x = (short) (sx1 - ((data & XMASK) >>> XSHIFT)); e.y = (short) ((data & YMASK) >>> YSHIFT); e.setIsDVS(true); //System.out.println(data); // autoshot triggering autoshotEventsSinceLastShot++; // number DVS events captured here } } else if ((data & ApsDvsChip.ADDRESS_TYPE_MASK) == ApsDvsChip.ADDRESS_TYPE_APS) { //APS event ApsDvsEvent e = nextApsDvsEvent(outItr); e.adcSample = data & ADC_DATA_MASK; int sampleType = (data & ADC_READCYCLE_MASK) >> ADC_NUMBER_OF_TRAILING_ZEROS; switch (sampleType) { case 0: e.readoutType = ApsDvsEvent.ReadoutType.ResetRead; break; case 1: e.readoutType = ApsDvsEvent.ReadoutType.SignalRead; //log.info("got SignalRead event"); break; case 3: log.warning("Event with readout cycle null was sent out!"); break; default: if ((warningCount < 10) || ((warningCount % WARNING_COUNT_DIVIDER) == 0)) { log.warning("Event with unknown readout cycle was sent out! You might be reading a file that had the deprecated C readout mode enabled."); } warningCount++; } e.special = false; e.timestamp = (timestamps[i]); e.address = data; e.x = (short) (((data & XMASK) >>> XSHIFT)); e.y = (short) ((data & YMASK) >>> YSHIFT); e.type = (byte) (2); boolean pixZero = (e.x == sx1) && (e.y == sy1);//first event of frame (addresses get flipped) if ((e.readoutType == ApsDvsEvent.ReadoutType.ResetRead) && pixZero) { createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.SOF, timestamps[i]); if (!config.chipConfigChain.configBits[6].isSet()) { //rolling shutter start of exposure (SOE) createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.SOE, timestamps[i]); frameTime = e.timestamp - firstFrameTs; firstFrameTs = e.timestamp; } } if (config.chipConfigChain.configBits[6].isSet() && e.isResetRead() && (e.x == 0) && (e.y == sy1)) { //global shutter start of exposure (SOE) createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.SOE, timestamps[i]); frameTime = e.timestamp - firstFrameTs; firstFrameTs = e.timestamp; } //end of exposure if (pixZero && e.isSignalRead()) { createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.EOE, timestamps[i]); exposure = e.timestamp - firstFrameTs; } if (e.isSignalRead() && (e.x == 0) && (e.y == 0)) { // if we use ResetRead+SignalRead+C readout, OR, if we use ResetRead-SignalRead readout and we are at last APS pixel, then write EOF event lastADCevent(); //insert a new "end of frame" event not present in original data createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.EOF, timestamps[i]); if (snapshot) { snapshot = false; config.apsReadoutControl.setAdcEnabled(false); } setFrameCount(getFrameCount() + 1); } } } if ((getAutoshotThresholdEvents() > 0) && (autoshotEventsSinceLastShot > getAutoshotThresholdEvents())) { takeSnapshot(); autoshotEventsSinceLastShot = 0; } // int imuEventCount=0, realImuEventCount=0; // for(Object e:out){ // if(e instanceof IMUSample){ // imuEventCount++; // IMUSample i=(IMUSample)e; // if(i.imuSampleEvent) realImuEventCount++; // System.out.println(String.format("packet has \ttotal %d, \timu type=%d, \treal imu data=%d events", out.getSize(), imuEventCount, realImuEventCount)); return out; } // extractPacket // TODO hack to reuse IMUSample events as ApsDvsEvents holding only APS or DVS data by using the special flags private ApsDvsEvent nextApsDvsEvent(OutputEventIterator outItr) { ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput(); e.special = false; if (e instanceof IMUSample) { ((IMUSample) e).imuSampleEvent = false; } return e; } /** * creates a special ApsDvsEvent in output packet just for flagging APS * frame markers such as start of frame, reset, end of frame. * * @param outItr * @param flag * @param timestamp * @return */ private ApsDvsEvent createApsFlagEvent(OutputEventIterator outItr, ApsDvsEvent.ReadoutType flag, int timestamp) { ApsDvsEvent a = nextApsDvsEvent(outItr); a.adcSample = 0; // set this effectively as ADC sample even though fake a.timestamp = timestamp; a.x = -1; a.y = -1; a.readoutType = flag; return a; } @Override public AEPacketRaw reconstructRawPacket(EventPacket packet) { if (raw == null) { raw = new AEPacketRaw(); } if (!(packet instanceof ApsDvsEventPacket)) { return null; } ApsDvsEventPacket apsDVSpacket = (ApsDvsEventPacket) packet; raw.ensureCapacity(packet.getSize()); raw.setNumEvents(0); int[] a = raw.addresses; int[] ts = raw.timestamps; int n = apsDVSpacket.getSize(); Iterator evItr = apsDVSpacket.fullIterator(); int k = 0; while (evItr.hasNext()) { ApsDvsEvent e = (ApsDvsEvent) evItr.next(); // not writing out these EOF events (which were synthesized on extraction) results in reconstructed packets with giant time gaps, reason unknown if (e.isEndOfFrame()) { continue; // these EOF events were synthesized from data in first place } ts[k] = e.timestamp; a[k++] = reconstructRawAddressFromEvent(e); } raw.setNumEvents(k); return raw; } /** * To handle filtered ApsDvsEvents, this method rewrites the fields of * the raw address encoding x and y addresses to reflect the event's x * and y fields. * * @param e the ApsDvsEvent * @return the raw address */ @Override public int reconstructRawAddressFromEvent(TypedEvent e) { int address = e.address; // if(e.x==0 && e.y==0){ // log.info("start of frame event "+e); // if(e.x==-1 && e.y==-1){ // log.info("end of frame event "+e); // e.x came from e.x = (short) (chip.getSizeX()-1-((data & XMASK) >>> XSHIFT)); // for DVS event, no x flip if APS event if (((ApsDvsEvent) e).adcSample >= 0) { address = (address & ~XMASK) | ((e.x) << XSHIFT); } else { address = (address & ~XMASK) | ((sx1 - e.x) << XSHIFT); } // e.y came from e.y = (short) ((data & YMASK) >>> YSHIFT); address = (address & ~YMASK) | (e.y << YSHIFT); return address; } } // extractor /** * overrides the Chip setHardware interface to construct a biasgen if one * doesn't exist already. Sets the hardware interface and the bias * generators hardware interface * * @param hardwareInterface the interface */ @Override public void setHardwareInterface(final HardwareInterface hardwareInterface) { this.hardwareInterface = hardwareInterface; SBret10config config; try { if (getBiasgen() == null) { setBiasgen(config = new SBret10config(this)); // now we can addConfigValue the control panel } else { getBiasgen().setHardwareInterface((BiasgenHardwareInterface) hardwareInterface); } } catch (ClassCastException e) { log.warning(e.getMessage() + ": probably this chip object has a biasgen but the hardware interface doesn't, ignoring"); } } /** * Displays data from SeeBetter test chip SeeBetter10/11. * * @author Tobi */ public class SBret10DisplayMethod extends ChipRendererDisplayMethodRGBA { private static final int FONTSIZE = 10; private static final int FRAME_COUNTER_BAR_LENGTH_FRAMES = 10; private TextRenderer exposureRenderer = null; public SBret10DisplayMethod(SBret10 chip) { super(chip.getCanvas()); } @Override public void display(GLAutoDrawable drawable) { if (exposureRenderer == null) { exposureRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, FONTSIZE), true, true); exposureRenderer.setColor(1, 1, 1, 1); } super.display(drawable); if (config.syncTimestampMasterEnabled.isSet() == false) { exposureRenderer.begin3DRendering(); // TODO make string rendering more efficient here using String.format or StringBuilder exposureRenderer.draw3D("Slave camera", 0, -(FONTSIZE / 2), 0, .5f); // x,y,z, scale factor exposureRenderer.end3DRendering(); } if ((config.videoControl != null) && config.videoControl.displayFrames) { GL2 gl = drawable.getGL().getGL2(); exposureRender(gl); } // draw sample histogram if (showImageHistogram && (renderer instanceof AEFrameChipRenderer)) { // System.out.println("drawing hist"); final int size = 100; AbstractHistogram hist = ((AEFrameChipRenderer) renderer).getAdcSampleValueHistogram(); hist.draw(drawable, exposureRenderer, (sizeX / 2) - (size / 2), (sizeY / 2) + (size / 2), size, size); } if (isShowIMU() && (chip instanceof SBret10)) { IMUSample imuSample = ((SBret10) chip).getImuSample(); if (imuSample != null) { imuRender(drawable, imuSample); } } } TextRenderer imuTextRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 36)); GLU glu = null; GLUquadric accelCircle = null; private void imuRender(GLAutoDrawable drawable, IMUSample imuSample) { // System.out.println("on rendering: "+imuSample.toString()); GL2 gl = drawable.getGL().getGL2(); gl.glPushMatrix(); gl.glTranslatef(chip.getSizeX() / 2, chip.getSizeY() / 2, 0); gl.glLineWidth(3); final float vectorScale = 1.5f; final float textScale = .2f; final float trans = .7f; float x, y; //acceleration x,y x = (vectorScale * imuSample.getAccelX() * HEIGHT) / IMUSample.FULL_SCALE_ACCEL_G / 2; y = (vectorScale * imuSample.getAccelY() * HEIGHT) / IMUSample.FULL_SCALE_ACCEL_G / 2; gl.glColor3f(0, 1, 0); gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, 0); gl.glVertex2f(x, y); gl.glEnd(); imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(0, 1, 0, trans); imuTextRenderer.draw3D(String.format("%.2f,%.2f g", imuSample.getAccelX(), imuSample.getAccelY()), x, y, 0, textScale); // x,y,z, scale factor imuTextRenderer.end3DRendering(); // acceleration z, drawn as circle if (glu == null) { glu = new GLU(); } if (accelCircle == null) { accelCircle = glu.gluNewQuadric(); } final float az = (vectorScale * imuSample.getAccelZ() * HEIGHT / 2) / IMUSample.FULL_SCALE_ACCEL_G / 2; final float rim = .5f; glu.gluQuadricDrawStyle(accelCircle, GLU.GLU_FILL); glu.gluDisk(accelCircle, az - rim, az + rim, 16, 1); imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(0, 1, 0, trans); final String saz = String.format("%.2f g", imuSample.getAccelZ()); Rectangle2D rect = imuTextRenderer.getBounds(saz); imuTextRenderer.draw3D(saz, az, -(float) rect.getHeight() * textScale * 0.5f, 0, textScale); // x,y,z, scale factor imuTextRenderer.end3DRendering(); // gyro pan/tilt gl.glColor3f(.3f, 0, 1); gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, 0); x = (vectorScale * imuSample.getGyroYawY() * HEIGHT) / IMUSample.FULL_SCALE_GYRO_DEG_PER_SEC; y = (vectorScale * imuSample.getGyroTiltX() * HEIGHT) / IMUSample.FULL_SCALE_GYRO_DEG_PER_SEC; gl.glVertex2f(x, y); gl.glEnd(); imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(.3f, 0, 1, trans); imuTextRenderer.draw3D(String.format("%.2f,%.2f dps", imuSample.getGyroYawY() + 5, imuSample.getGyroTiltX()), x, y, 0, textScale); // x,y,z, scale factor imuTextRenderer.end3DRendering(); // gyro roll x = (vectorScale * imuSample.getGyroRollZ() * HEIGHT) / IMUSample.FULL_SCALE_GYRO_DEG_PER_SEC; y = chip.getSizeY() * .25f; gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, y); gl.glVertex2f(x, y); gl.glEnd(); imuTextRenderer.begin3DRendering(); imuTextRenderer.draw3D(String.format("%.2f dps", imuSample.getGyroRollZ()), x, y, 0, textScale); // x,y,z, scale factor imuTextRenderer.end3DRendering(); // color annotation to show what is being rendered imuTextRenderer.begin3DRendering(); // imuTextRenderer.setColor(1,0,0, trans); // imuTextRenderer.draw3D("G", -6, -6,0, textScale); // x,y,z, scale factor // imuTextRenderer.setColor(0,1,0, trans); // imuTextRenderer.draw3D("A", +6, -6,0, textScale); // x,y,z, scale factor imuTextRenderer.setColor(1, 1, 1, trans); final String ratestr = String.format("IMU: timestamp=%-+9.3fs last dtMs=%-6.1fms avg dtMs=%-6.1fms", 1e-6f * imuSample.getTimestampUs(), imuSample.getDeltaTimeUs() * .001f, IMUSample.getAverageSampleIntervalUs() / 1000); Rectangle2D raterect = imuTextRenderer.getBounds(ratestr); imuTextRenderer.draw3D(ratestr, -(float) raterect.getWidth() * textScale * 0.5f * .7f, -12, 0, textScale * .7f); // x,y,z, scale factor imuTextRenderer.end3DRendering(); gl.glPopMatrix(); } private void exposureRender(GL2 gl) { gl.glPushMatrix(); exposureRenderer.begin3DRendering(); // TODO make string rendering more efficient here using String.format or StringBuilder if (frameTime > 0) { setFrameRateHz((float) 1000000 / frameTime); } setExposureMs((float) exposure / 1000); String s = String.format("Frame: %d; Exposure %.2f ms; Frame rate: %.2f Hz", getFrameCount(), exposureMs, frameRateHz); exposureRenderer.draw3D(s, 0, HEIGHT + (FONTSIZE / 2), 0, .5f); // x,y,z, scale factor exposureRenderer.end3DRendering(); int nframes = frameCount % FRAME_COUNTER_BAR_LENGTH_FRAMES; int rectw = WIDTH / FRAME_COUNTER_BAR_LENGTH_FRAMES; gl.glColor4f(1, 1, 1, .5f); for (int i = 0; i < nframes; i++) { gl.glRectf(nframes * rectw, HEIGHT + 1, ((nframes + 1) * rectw) - 3, (HEIGHT + (FONTSIZE / 2)) - 1); } gl.glPopMatrix(); } } /** * Returns the preferred DisplayMethod, or ChipRendererDisplayMethod if null * preference. * * @return the method, or null. * @see #setPreferredDisplayMethod */ @Override public DisplayMethod getPreferredDisplayMethod() { return new ChipRendererDisplayMethodRGBA(getCanvas()); } @Override public int getMaxADC() { return MAX_ADC; } /** * Sets the measured frame rate. Does not change parameters, only used for * recording measured quantity and informing GUI listeners. * * @param frameRateHz the frameRateHz to set */ private void setFrameRateHz(float frameRateHz) { float old = this.frameRateHz; this.frameRateHz = frameRateHz; getSupport().firePropertyChange(PROPERTY_FRAME_RATE_HZ, old, this.frameRateHz); } /** * Sets the measured exposure. Does not change parameters, only used for * recording measured quantity. * * @param exposureMs the exposureMs to set */ private void setExposureMs(float exposureMs) { float old = this.exposureMs; this.exposureMs = exposureMs; getSupport().firePropertyChange(PROPERTY_EXPOSURE_MS, old, this.exposureMs); } @Override public float getFrameRateHz() { return frameRateHz; } @Override public float getExposureMs() { return exposureMs; } /** * Returns the frame counter. This value is set on each end-of-frame sample. * * @return the frameCount */ public int getFrameCount() { return frameCount; } /** * Sets the frame counter. * * @param frameCount the frameCount to set */ public void setFrameCount(int frameCount) { this.frameCount = frameCount; } /** * Triggers shot of one APS frame */ @Override public void takeSnapshot() { snapshot = true; config.apsReadoutControl.setAdcEnabled(true); } /** * Sets threshold for shooting a frame automatically * * @param thresholdEvents the number of events to trigger shot on. Less than * or equal to zero disables auto-shot. */ @Override public void setAutoshotThresholdEvents(int thresholdEvents) { if (thresholdEvents < 0) { thresholdEvents = 0; } autoshotThresholdEvents = thresholdEvents; getPrefs().putInt("SBret10.autoshotThresholdEvents", thresholdEvents); if (autoshotThresholdEvents == 0) { config.runAdc.set(true); } } /** * Returns threshold for auto-shot. * * @return events to shoot frame */ @Override public int getAutoshotThresholdEvents() { return autoshotThresholdEvents; } @Override public void setAutoExposureEnabled(boolean yes) { getAutoExposureController().setAutoExposureEnabled(yes); } @Override public boolean isAutoExposureEnabled() { return getAutoExposureController().isAutoExposureEnabled(); } private boolean showImageHistogram = getPrefs().getBoolean("SBRet10.showImageHistogram", false); @Override public boolean isShowImageHistogram() { return showImageHistogram; } @Override public void setShowImageHistogram(boolean yes) { showImageHistogram = yes; getPrefs().putBoolean("SBRet10.showImageHistogram", yes); } /** * Controls exposure automatically to try to optimize captured gray levels * */ public class AutoExposureController implements HasPropertyTooltips { // TODO not implemented yet private boolean autoExposureEnabled = getPrefs().getBoolean("autoExposureEnabled", false); private float expDelta = .05f; // exposure change if incorrectly exposed private float underOverFractionThreshold = 0.2f; // threshold for fraction of total pixels that are underexposed or overexposed private PropertyTooltipSupport tooltipSupport = new PropertyTooltipSupport(); private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); SimpleHistogram hist = null; SimpleHistogram.Statistics stats = null; private float lowBoundary = getPrefs().getFloat("AutoExposureController.lowBoundary", 0.1f); private float highBoundary = getPrefs().getFloat("AutoExposureController.highBoundary", 0.9f); public AutoExposureController() { tooltipSupport.setPropertyTooltip("expDelta", "fractional change of exposure when under or overexposed"); tooltipSupport.setPropertyTooltip("underOverFractionThreshold", "fraction of pixel values under xor over exposed to trigger exposure change"); tooltipSupport.setPropertyTooltip("lowBoundary", "Upper edge of histogram range considered as low values"); tooltipSupport.setPropertyTooltip("highBoundary", "Lower edge of histogram range considered as high values"); tooltipSupport.setPropertyTooltip("autoExposureEnabled", "Exposure time is automatically controlled when this flag is true"); } @Override public String getPropertyTooltip(String propertyName) { return tooltipSupport.getPropertyTooltip(propertyName); } public void setAutoExposureEnabled(boolean yes) { boolean old = this.autoExposureEnabled; this.autoExposureEnabled = yes; propertyChangeSupport.firePropertyChange("autoExposureEnabled", old, yes); getPrefs().putBoolean("autoExposureEnabled", yes); // if (old != yes) { // setChanged(); // notifyObservers(); } public boolean isAutoExposureEnabled() { return this.autoExposureEnabled; } public void controlExposure() { if (!autoExposureEnabled) { return; } hist = apsDVSrenderer.getAdcSampleValueHistogram(); if (hist == null) { return; } stats = hist.getStatistics(); if (stats == null) { return; } stats.setLowBoundary(lowBoundary); stats.setHighBoundary(highBoundary); hist.computeStatistics(); CPLDInt exposure = config.exposure; int currentExposure = exposure.get(), newExposure = 0; if (stats.fracLow >= underOverFractionThreshold && stats.fracHigh < underOverFractionThreshold) { newExposure = Math.round(currentExposure * (1 + expDelta)); if (newExposure == currentExposure) { newExposure++; // ensure increase } if (newExposure > exposure.getMax()) { newExposure = exposure.getMax(); } if (newExposure != currentExposure) { exposure.set(newExposure); } log.log(Level.INFO, "Underexposed: {0}\n{1}", new Object[]{stats.toString(), String.format("oldExposure=%8d newExposure=%8d", currentExposure, newExposure)}); } else if (stats.fracLow < underOverFractionThreshold && stats.fracHigh >= underOverFractionThreshold) { newExposure = Math.round(currentExposure * (1 - expDelta)); if (newExposure == currentExposure) { newExposure--; // ensure decrease even with rounding. } if (newExposure < exposure.getMin()) { newExposure = exposure.getMin(); } if (newExposure != currentExposure) { exposure.set(newExposure); } log.log(Level.INFO, "Overexposed: {0}\n{1}", new Object[]{stats.toString(), String.format("oldExposure=%8d newExposure=%8d", currentExposure, newExposure)}); } else { // log.info(stats.toString()); } } /** * Gets by what relative amount the exposure is changed on each frame if * under or over exposed. * * @return the expDelta */ public float getExpDelta() { return expDelta; } /** * Sets by what relative amount the exposure is changed on each frame if * under or over exposed. * * @param expDelta the expDelta to set */ public void setExpDelta(float expDelta) { this.expDelta = expDelta; getPrefs().putFloat("expDelta", expDelta); } /** * Gets the fraction of pixel values that must be under xor over exposed * to change exposure automatically. * * @return the underOverFractionThreshold */ public float getUnderOverFractionThreshold() { return underOverFractionThreshold; } /** * Gets the fraction of pixel values that must be under xor over exposed * to change exposure automatically. * * @param underOverFractionThreshold the underOverFractionThreshold to * set */ public void setUnderOverFractionThreshold(float underOverFractionThreshold) { this.underOverFractionThreshold = underOverFractionThreshold; getPrefs().putFloat("underOverFractionThreshold", underOverFractionThreshold); } public float getLowBoundary() { return lowBoundary; } public void setLowBoundary(float lowBoundary) { this.lowBoundary = lowBoundary; getPrefs().putFloat("AutoExposureController.lowBoundary", lowBoundary); } public float getHighBoundary() { return highBoundary; } public void setHighBoundary(float highBoundary) { this.highBoundary = highBoundary; getPrefs().putFloat("AutoExposureController.highBoundary", highBoundary); } /** * @return the propertyChangeSupport */ public PropertyChangeSupport getPropertyChangeSupport() { return propertyChangeSupport; } } /** * Returns the current Inertial Measurement Unit sample. * * @return the imuSample, or null if there is no sample */ public IMUSample getImuSample() { return imuSample; } private boolean showIMU = getPrefs().getBoolean("SBRet10.showIMU", false); @Override public void setShowIMU(boolean yes) { showIMU = yes; final byte POWER_MGMT_1 = (byte) 0x6b; // register 107 decimel getPrefs().putBoolean("SBRet10.showIMU", showIMU); if (hardwareInterface != null && hardwareInterface instanceof ApsDvsHardwareInterface && hardwareInterface.isOpen()) { ApsDvsHardwareInterface apsDvsHardwareInterface = (ApsDvsHardwareInterface) hardwareInterface; try { // disable or enable IMU on device if (yes) { apsDvsHardwareInterface.writeImuRegister(POWER_MGMT_1, (byte) (0x02)); // deactivate sleep } else { apsDvsHardwareInterface.writeImuRegister(POWER_MGMT_1, (byte) (0x42)); // activate full sleep } } catch (HardwareInterfaceException e) { log.warning("tried to set IMU register but got exception " + e.toString()); } } } @Override public boolean isShowIMU() { return showIMU; } /** * Updates AEViewer specialized menu items according to capabilities of * HardwareInterface. * * @param o the observable, i.e. this Chip. * @param arg the argument (e.g. the HardwareInterface). */ @Override public void update(Observable o, Object arg) { if (o == config.syncTimestampMasterEnabled) { if (syncEnabledMenuItem != null) { syncEnabledMenuItem.setSelected(config.syncTimestampMasterEnabled.isSet()); } } } /** * Enables or disable DVS128 menu in AEViewer * * @param yes true to enable it */ private void enableChipMenu(boolean yes) { if (yes) { if (chipMenu == null) { chipMenu = new JMenu(this.getClass().getSimpleName()); chipMenu.getPopupMenu().setLightWeightPopupEnabled(false); // to paint on GLCanvas chipMenu.setToolTipText("Specialized menu for chip"); } if (syncEnabledMenuItem == null) { syncEnabledMenuItem = new JCheckBoxMenuItem("Timestamp master / Enable sync event output"); syncEnabledMenuItem.setToolTipText("<html>Sets this device as timestamp master and enables sync event generation on external IN pin falling edges (disables slave clock input).<br>Falling edges inject special sync events with bitmask " + HexString.toString(ApsDvsHardwareInterface.SYNC_EVENT_BITMASK) + " set<br>These events are not rendered but are logged and can be used to synchronize an external signal to the recorded data.<br>If you are only using one camera, enable this option.<br>If you want to synchronize two DVS128, disable this option in one of the cameras and connect the OUT pin of the master to the IN pin of the slave and also connect the two GND pins."); syncEnabledMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { log.info("setting sync/timestamp master to " + syncEnabledMenuItem.isSelected()); config.syncTimestampMasterEnabled.set(syncEnabledMenuItem.isSelected()); } }); syncEnabledMenuItem.setSelected(config.syncTimestampMasterEnabled.isSet()); chipMenu.add(syncEnabledMenuItem); config.syncTimestampMasterEnabled.addObserver(this); } if (getAeViewer() != null) { getAeViewer().setMenu(chipMenu); } } else { // disable menu if (chipMenu != null) { getAeViewer().removeMenu(chipMenu); } } } @Override public void onDeregistration() { super.onDeregistration(); if (getAeViewer() == null) { return; } enableChipMenu(false); } @Override public void onRegistration() { super.onRegistration(); if (getAeViewer() == null) { return; } enableChipMenu(true); } }
package eu.visualize.ini.convnet; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.Point; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.TreeMap; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.awt.GLCanvas; import com.jogamp.opengl.glu.GLU; import com.jogamp.opengl.glu.GLUquadric; import com.jogamp.opengl.util.awt.TextRenderer; import eu.seebetter.ini.chips.DavisChip; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventio.AEFileInputStream; import net.sf.jaer.eventio.AEInputStream; import net.sf.jaer.eventprocessing.EventFilter2DMouseAdaptor; import net.sf.jaer.graphics.AEViewer; import net.sf.jaer.graphics.MultilineAnnotationTextRenderer; /** * Labels location of target using mouse GUI in recorded data for later * supervised learning. * * @author tobi */ @DevelopmentStatus(DevelopmentStatus.Status.Stable) @Description("Labels location of target using mouse GUI in recorded data for later supervised learning.") public class TargetLabeler extends EventFilter2DMouseAdaptor implements PropertyChangeListener, KeyListener { private boolean mousePressed = false; private boolean shiftPressed = false; private boolean ctlPressed = false; private Point mousePoint = null; final float labelRadius = 5f; private GLUquadric mouseQuad = null; private TreeMap<Integer, SimultaneouTargetLocations> targetLocations = new TreeMap(); private TargetLocation targetLocation = null; private DavisChip apsDvsChip = null; private int lastFrameNumber = -1; private int lastTimestamp = Integer.MIN_VALUE; private int currentFrameNumber = -1; private final String LAST_FOLDER_KEY = "lastFolder"; TextRenderer textRenderer = null; private int minTargetPointIntervalUs = getInt("minTargetPointIntervalUs", 2000); private int targetRadius = getInt("targetRadius", 10); private int maxTimeLastTargetLocationValidUs = getInt("maxTimeLastTargetLocationValidUs", 50000); private int minSampleTimestamp = Integer.MAX_VALUE, maxSampleTimestamp = Integer.MIN_VALUE; private final int N_FRACTIONS = 1000; private boolean[] labeledFractions = new boolean[N_FRACTIONS]; // to annotate graphically what has been labeled so far in event stream private boolean[] targetPresentInFractions = new boolean[N_FRACTIONS]; // to annotate graphically what has been labeled so far in event stream private boolean showLabeledFraction = getBoolean("showLabeledFraction", true); private boolean showHelpText = getBoolean("showHelpText", true); // protected int maxTargets = getInt("maxTargets", 8); protected int currentTargetTypeID = getInt("currentTargetTypeID", 0); private ArrayList<TargetLocation> currentTargets = new ArrayList(10); // currently valid targets protected boolean eraseSamplesEnabled = false; private HashMap<String, String> mapDataFilenameToTargetFilename = new HashMap(); private boolean propertyChangeListenerAdded = false; private String DEFAULT_FILENAME = "locations.txt"; private String lastFileName = getString("lastFileName", DEFAULT_FILENAME); protected boolean showStatistics = getBoolean("showStatistics", true); private String lastDataFilename = null; private boolean locationsLoadedFromFile = false; // file statistics private long firstInputStreamTimestamp = 0, lastInputStreamTimestamp = 0, inputStreamDuration = 0; private long filePositionEvents = 0, fileLengthEvents = 0; private int filePositionTimestamp = 0; private boolean warnSave = true; public TargetLabeler(AEChip chip) { super(chip); if (chip instanceof DavisChip) { apsDvsChip = ((DavisChip) chip); } setPropertyTooltip("minTargetPointIntervalUs", "minimum interval between target positions in the database in us"); setPropertyTooltip("targetRadius", "drawn radius of target in pixels"); setPropertyTooltip("maxTimeLastTargetLocationValidUs", "this time after last sample, the data is shown as not yet been labeled. This time specifies how long a specified target location is valid after its last specified location."); setPropertyTooltip("saveLocations", "saves target locations"); setPropertyTooltip("saveLocationsAs", "show file dialog to save target locations to a new file"); setPropertyTooltip("loadLocations", "loads locations from a file"); setPropertyTooltip("clearLocations", "clears all existing targets"); setPropertyTooltip("resampleLabeling", "resamples the existing labeling to fill in null locations for unlabeled parts and fills in copies of latest location between samples, to specified minTargetPointIntervalUs"); setPropertyTooltip("showLabeledFraction", "shows labeled part of input by a bar with red=unlabeled, green=labeled, blue=current position"); setPropertyTooltip("showHelpText", "shows help text on screen. Uncheck to hide"); setPropertyTooltip("showStatistics", "shows statistics"); // setPropertyTooltip("maxTargets", "maximum number of simultaneous targets to label"); setPropertyTooltip("currentTargetTypeID", "ID code of current target to be labeled, e.g., 0=dog, 1=cat, etc. User must keep track of the mapping from ID codes to target classes."); setPropertyTooltip("eraseSamplesEnabled", "Use this mode erase all samples up to minTargetPointIntervalUs before current time."); Arrays.fill(labeledFractions, false); Arrays.fill(targetPresentInFractions, false); try { byte[] bytes = getPrefs().getByteArray("TargetLabeler.hashmap", null); if (bytes != null) { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); mapDataFilenameToTargetFilename = (HashMap<String, String>) in.readObject(); in.close(); log.info("loaded mapDataFilenameToTargetFilename: " + mapDataFilenameToTargetFilename.size() + " entries"); } else { } } catch (Exception e) { e.printStackTrace(); } } @Override public void mouseDragged(MouseEvent e) { Point p = (getMousePixel(e)); if (p != null) { if (mousePoint != null) { mousePoint.setLocation(p); } else { mousePoint = new Point(p); } } else { mousePoint = null; } } @Override public void mouseReleased(MouseEvent e) { mousePressed = false; } @Override public void mousePressed(MouseEvent e) { mouseMoved(e); } @Override public void mouseMoved(MouseEvent e) { Point p = (getMousePixel(e)); if (p != null) { if (mousePoint != null) { mousePoint.setLocation(p); } else { mousePoint = new Point(p); } } else { mousePoint = null; } } @Override synchronized public void annotate(GLAutoDrawable drawable) { if (!isFilterEnabled()) { return; } if (chip.getAeViewer().getPlayMode() != AEViewer.PlayMode.PLAYBACK) { return; } GL2 gl = drawable.getGL().getGL2(); chipCanvas = chip.getCanvas(); if (chipCanvas == null) { return; } glCanvas = (GLCanvas) chipCanvas.getCanvas(); if (glCanvas == null) { return; } glu = GLU.createGLU(gl); // TODO check if this solves problem of bad GL context in file preview if (isSelected()) { Point mp = glCanvas.getMousePosition(); Point p = chipCanvas.getPixelFromPoint(mp); if (p == null) { return; } checkBlend(gl); float[] compArray = new float[4]; gl.glColor3fv(targetTypeColors[currentTargetTypeID % targetTypeColors.length].getColorComponents(compArray), 0); gl.glLineWidth(3f); gl.glPushMatrix(); gl.glTranslatef(p.x, p.y, 0); gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glEnd(); gl.glTranslatef(.5f, -.5f, 0); gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glEnd(); // if (quad == null) { // quad = glu.gluNewQuadric(); // glu.gluQuadricDrawStyle(quad, GLU.GLU_FILL); // glu.gluDisk(quad, 0, 3, 32, 1); gl.glPopMatrix(); } if (textRenderer == null) { textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 36)); textRenderer.setColor(1, 1, 1, 1); } MultilineAnnotationTextRenderer.setColor(Color.CYAN); MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .9f); MultilineAnnotationTextRenderer.setScale(.3f); StringBuilder sb = new StringBuilder(); if (showHelpText) { sb.append("Shift + !Ctrl + mouse position: Specify no target present\n i.e. mark data as looked at\nClt + Shift + mouse position: Specify currentTargetTypeID is present at mouse location\n"); MultilineAnnotationTextRenderer.renderMultilineString(sb.toString()); } if (showStatistics) { MultilineAnnotationTextRenderer.renderMultilineString(String.format("%d TargetLocation labels specified\nFirst label time: %.1fs, Last label time: %.1fs\nCurrent frame number: %d\nCurrent # labels within maxTimeLastTargetLocationValidUs: %d", targetLocations.size(), minSampleTimestamp * 1e-6f, maxSampleTimestamp * 1e-6f, getCurrentFrameNumber(), currentTargets.size())); if (shiftPressed && !ctlPressed) { MultilineAnnotationTextRenderer.renderMultilineString("Specifying no target"); } else if (shiftPressed && ctlPressed) { MultilineAnnotationTextRenderer.renderMultilineString("Specifying target location"); } else { MultilineAnnotationTextRenderer.renderMultilineString("Playing recorded target locations"); } } for (TargetLocation t : currentTargets) { if (t.location != null) { t.draw(drawable, gl); } } // show labeled parts if (showLabeledFraction && (inputStreamDuration > 0)) { float dx = chip.getSizeX() / (float) N_FRACTIONS; float y = chip.getSizeY() / 5; float dy = chip.getSizeY() / 50; float x = 0; for (int i = 0; i < N_FRACTIONS; i++) { boolean b = labeledFractions[i]; if (b) { gl.glColor3f(0, 1, 0); } else { gl.glColor3f(1, 0, 0); } gl.glRectf(x - (dx / 2), y, x + (dx / 2), y + (dy * (1 + (targetPresentInFractions[i] ? 1 : 0)))); // gl.glRectf(x-dx/2, y, x + dx/2, y + dy * (1 + (currentTargets.size()))); x += dx; } float curPosFrac = ((float) (filePositionTimestamp - firstInputStreamTimestamp) / inputStreamDuration); x = curPosFrac * chip.getSizeX(); y = y + dy; gl.glColor3f(1, 1, 1); gl.glRectf(x - (dx / 2), y - (dy * 2), x + (dx / 2), y + dy); } } synchronized public void doClearLocations() { targetLocations.clear(); minSampleTimestamp = Integer.MAX_VALUE; maxSampleTimestamp = Integer.MIN_VALUE; Arrays.fill(labeledFractions, false); Arrays.fill(targetPresentInFractions, false); currentTargets.clear(); locationsLoadedFromFile = false; } synchronized public void doSaveLocationsAs() { String fn = mapDataFilenameToTargetFilename.get(lastDataFilename); if (fn == null) { fn = lastFileName == null ? DEFAULT_FILENAME : lastFileName; } JFileChooser c = new JFileChooser(fn); c.setSelectedFile(new File(fn)); int ret = c.showSaveDialog(glCanvas); if (ret != JFileChooser.APPROVE_OPTION) { return; } lastFileName = c.getSelectedFile().toString(); // end filename with -targets.txt File f = c.getSelectedFile(); String s = f.getPath(); if (!s.endsWith("-targets.txt")) { int idxdot = s.lastIndexOf('.'); if (idxdot > 0) { s = s.substring(0, idxdot); } s = s + "-targets.txt"; f = new File(s); } if (f.exists()) { int r = JOptionPane.showConfirmDialog(glCanvas, "File " + f.toString() + " already exists, overwrite it?"); if (r != JOptionPane.OK_OPTION) { return; } } lastFileName = f.toString(); putString("lastFileName", lastFileName); saveLocations(f); warnSave = false; } public void doResampleLabeling() { if (targetLocations == null) { log.warning("null targetLocations - nothing to resample"); return; } if (chip.getAeViewer().getAePlayer().getAEInputStream() == null) { log.warning("cannot label unless a file is being played back"); return; } if (targetLocations.size() == 0) { log.warning("no locations labeled - will label entire recording with no visible targets"); } Map.Entry<Integer, SimultaneouTargetLocations> prevTargets = targetLocations.firstEntry(); TreeMap<Integer, SimultaneouTargetLocations> newTargets = new TreeMap(); if (prevTargets != null) { for (Map.Entry<Integer, SimultaneouTargetLocations> nextTargets : targetLocations.entrySet()) { // for each existing set of targets by timestamp key list // if no label at all for minTargetPointIntervalUs, then add copy of last labels up to maxTimeLastTargetLocationValidUs, // then add null labels after that if ((nextTargets.getKey() - prevTargets.getKey()) > minTargetPointIntervalUs) { int n = (nextTargets.getKey() - prevTargets.getKey()) / minTargetPointIntervalUs; // add this many total int tCopy = prevTargets.getKey() + maxTimeLastTargetLocationValidUs; // add this many total for (int i = 0; i < n; i++) { int ts = prevTargets.getKey() + ((i + 1) * minTargetPointIntervalUs); newTargets.put(ts, copyLocationsToNewTs(prevTargets.getValue(), ts, ts <= tCopy)); } } prevTargets = nextTargets; } } // handle time after last label AEFileInputStream fileInputStream = chip.getAeViewer().getAePlayer().getAEInputStream(); int tFirstLabel = prevTargets != null ? prevTargets.getKey() : fileInputStream.getFirstTimestamp(); int tLastLabel = fileInputStream.getLastTimestamp(); // TODO handle wrapped timestamp during recording int frameNumber = prevTargets != null ? prevTargets.getValue().get(0).frameNumber : -1; int n = (tLastLabel - tFirstLabel) / minTargetPointIntervalUs; // add this many total for (int i = 0; i < n; i++) { SimultaneouTargetLocations s = new SimultaneouTargetLocations(); int ts = tFirstLabel + ((i + 1) * minTargetPointIntervalUs); TargetLocation addedNullLabel = new TargetLocation(frameNumber, ts, null, targetRadius, -1, -1); s.add(addedNullLabel); newTargets.put(ts, s); } targetLocations.putAll(newTargets); fixLabeledFraction(); } private SimultaneouTargetLocations copyLocationsToNewTs(SimultaneouTargetLocations src, int ts, boolean useOriginalLocation) { SimultaneouTargetLocations s = new SimultaneouTargetLocations(); for (TargetLocation t : src) { TargetLocation tNew = new TargetLocation(t.frameNumber, ts, useOriginalLocation ? t.location : null, targetRadius, t.dimx, t.dimy); s.add(tNew); } return s; } synchronized public void doSaveLocations() { if (warnSave) { int ret = JOptionPane.showConfirmDialog(chip.getAeViewer().getFilterFrame(), "Really overwrite " + lastFileName + " ?", "Overwrite warning", JOptionPane.WARNING_MESSAGE); if (ret != JOptionPane.YES_OPTION) { log.info("save canceled"); return; } } File f = new File(lastFileName); saveLocations(new File(lastFileName)); } synchronized public void doLoadLocations() { if (lastFileName == null) { lastFileName = mapDataFilenameToTargetFilename.get(lastDataFilename); } if (lastFileName == null) { lastFileName = DEFAULT_FILENAME; } if ((lastFileName != null) && lastFileName.equals(DEFAULT_FILENAME)) { File f = chip.getAeViewer().getRecentFiles().getMostRecentFile(); if (f == null) { lastFileName = DEFAULT_FILENAME; } else { lastFileName = f.getPath(); } } JFileChooser c = new JFileChooser(lastFileName); c.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt"); } @Override public String getDescription() { return "Text target label files"; } }); c.setMultiSelectionEnabled(false); c.setSelectedFile(new File(lastFileName)); int ret = c.showOpenDialog(glCanvas); if (ret != JFileChooser.APPROVE_OPTION) { return; } lastFileName = c.getSelectedFile().toString(); putString("lastFileName", lastFileName); loadLocations(new File(lastFileName)); } private TargetLocation lastNewTargetLocation = null; @Override synchronized public EventPacket<?> filterPacket(EventPacket<?> in) { if (chip.getAeViewer().getPlayMode() != AEViewer.PlayMode.PLAYBACK) { return in; } if (!propertyChangeListenerAdded) { if (chip.getAeViewer() != null) { chip.getAeViewer().addPropertyChangeListener(this); propertyChangeListenerAdded = true; } } // currentTargets.clear(); for (BasicEvent e : in) { if (e.isSpecial()) { continue; } if (apsDvsChip != null) { // update actual frame number, starting from 0 at start of recording (for playback or after rewind) // this can be messed up by jumping in the file using slider int newFrameNumber = apsDvsChip.getFrameCount(); if (newFrameNumber != lastFrameNumber) { if (newFrameNumber > lastFrameNumber) { currentFrameNumber++; } else if (newFrameNumber < lastFrameNumber) { currentFrameNumber } lastFrameNumber = newFrameNumber; } if (((long) e.timestamp - (long) lastTimestamp) >= minTargetPointIntervalUs) { // show the nearest TargetLocation if at least minTargetPointIntervalUs has passed by, // or "No target" if the location was previously Map.Entry<Integer, SimultaneouTargetLocations> mostRecentTargetsBeforeThisEvent = targetLocations.lowerEntry(e.timestamp); if (mostRecentTargetsBeforeThisEvent != null) { for (TargetLocation t : mostRecentTargetsBeforeThisEvent.getValue()) { if ((t == null) || ((t != null) && ((e.timestamp - t.timestamp) > maxTimeLastTargetLocationValidUs))) { targetLocation = null; } else if (targetLocation != t) { targetLocation = t; currentTargets.add(targetLocation); markDataHasTarget(targetLocation.timestamp, targetLocation.location != null); } } } lastTimestamp = e.timestamp; // find next saved target location that is just before this time (lowerEntry) TargetLocation newTargetLocation = null; if (shiftPressed && ctlPressed && (mousePoint != null)) { // specify (additional) target present // add a labeled location sample maybeEraseSamples(mostRecentTargetsBeforeThisEvent); newTargetLocation = new TargetLocation(getCurrentFrameNumber(), e.timestamp, mousePoint, currentTargetTypeID, targetRadius, targetRadius); addSample(e.timestamp, newTargetLocation); currentTargets.add(newTargetLocation); } else if (shiftPressed && !ctlPressed) { // specify no target present now but mark recording as reviewed maybeEraseSamples(mostRecentTargetsBeforeThisEvent); newTargetLocation = new TargetLocation(getCurrentFrameNumber(), e.timestamp, null, currentTargetTypeID, targetRadius, targetRadius); addSample(e.timestamp, newTargetLocation); // markDataReviewedButNoTargetPresent(e.timestamp); } if (newTargetLocation != null) { if (newTargetLocation.timestamp > maxSampleTimestamp) { maxSampleTimestamp = newTargetLocation.timestamp; } if (newTargetLocation.timestamp < minSampleTimestamp) { minSampleTimestamp = newTargetLocation.timestamp; } } lastNewTargetLocation = newTargetLocation; } if (e.timestamp < lastTimestamp) { lastTimestamp = e.timestamp; } } } //prune list of current targets to their valid lifetime, and remove leftover targets in the future ArrayList<TargetLocation> removeList = new ArrayList(); for (TargetLocation t : currentTargets) { if (((t.timestamp + maxTimeLastTargetLocationValidUs) < in.getLastTimestamp()) || (t.timestamp > in.getLastTimestamp())) { removeList.add(t); } } currentTargets.removeAll(removeList); return in; } private void maybeEraseSamples(Map.Entry<Integer, SimultaneouTargetLocations> entry) { if (!isEraseSamplesEnabled() || (entry == null)) { return; } targetLocations.remove(entry.getKey()); fixLabeledFraction(); } @Override public void setSelected(boolean yes) { super.setSelected(yes); // register/deregister mouse listeners if (yes) { glCanvas.removeKeyListener(this); // only add ourselves once in case we were added on startup glCanvas.addKeyListener(this); } else { glCanvas.removeKeyListener(this); } } @Override public void resetFilter() { } @Override public void initFilter() { } /** * @return the minTargetPointIntervalUs */ public int getMinTargetPointIntervalUs() { return minTargetPointIntervalUs; } /** * @param minTargetPointIntervalUs the minTargetPointIntervalUs to set */ public void setMinTargetPointIntervalUs(int minTargetPointIntervalUs) { this.minTargetPointIntervalUs = minTargetPointIntervalUs; putInt("minTargetPointIntervalUs", minTargetPointIntervalUs); } @Override public void keyTyped(KeyEvent ke) { // forward space and b (toggle direction of playback) to AEPlayer int k = ke.getKeyChar(); // log.info("keyChar=" + k + " keyEvent=" + ke.toString()); if (shiftPressed || ctlPressed) { // only forward to AEViewer if we are blocking ordinary input to AEViewer by labeling switch (k) { case KeyEvent.VK_SPACE: chip.getAeViewer().setPaused(!chip.getAeViewer().isPaused()); break; case KeyEvent.VK_B: case 2: chip.getAeViewer().getAePlayer().toggleDirection(); break; case 'F': case 6: chip.getAeViewer().getAePlayer().speedUp(); break; case 'S': case 19: chip.getAeViewer().getAePlayer().slowDown(); break; } } } @Override public void keyPressed(KeyEvent ke) { int k = ke.getKeyCode(); if (k == KeyEvent.VK_SHIFT) { shiftPressed = true; } else if (k == KeyEvent.VK_CONTROL) { ctlPressed = true; } else if (k == KeyEvent.VK_E) { setEraseSamplesEnabled(true); } } @Override public void keyReleased(KeyEvent ke) { int k = ke.getKeyCode(); if (k == KeyEvent.VK_SHIFT) { shiftPressed = false; } else if (k == KeyEvent.VK_CONTROL) { ctlPressed = false; } else if (k == KeyEvent.VK_E) { setEraseSamplesEnabled(false); } } /** * @return the targetRadius */ public int getTargetRadius() { return targetRadius; } /** * @param targetRadius the targetRadius to set */ public void setTargetRadius(int targetRadius) { this.targetRadius = targetRadius; putInt("targetRadius", targetRadius); } /** * @return the maxTimeLastTargetLocationValidUs */ public int getMaxTimeLastTargetLocationValidUs() { return maxTimeLastTargetLocationValidUs; } /** * @param maxTimeLastTargetLocationValidUs the * maxTimeLastTargetLocationValidUs to set */ public void setMaxTimeLastTargetLocationValidUs(int maxTimeLastTargetLocationValidUs) { if (maxTimeLastTargetLocationValidUs < minTargetPointIntervalUs) { maxTimeLastTargetLocationValidUs = minTargetPointIntervalUs; } this.maxTimeLastTargetLocationValidUs = maxTimeLastTargetLocationValidUs; putInt("maxTimeLastTargetLocationValidUs", maxTimeLastTargetLocationValidUs); } /** * Returns true if any locations are specified already. However if there are * no targets at all visible then also returns false. * * * @return true if there are locations specified * @see #isLocationsLoadedFromFile() */ public boolean hasLocations() { return !targetLocations.isEmpty(); } /** * Returns the last target location * * @return the targetLocation */ public TargetLocation getTargetLocation() { return targetLocation; } private void addSample(int timestamp, TargetLocation newTargetLocation) { SimultaneouTargetLocations s = targetLocations.get(timestamp); if (s == null) { s = new SimultaneouTargetLocations(); targetLocations.put(timestamp, s); } s.add(newTargetLocation); } private int getFractionOfFileDuration(int timestamp) { if (inputStreamDuration == 0) { return 0; } return (int) Math.floor((N_FRACTIONS * ((float) (timestamp - firstInputStreamTimestamp))) / inputStreamDuration); } private class TargetLocationComparator implements Comparator<TargetLocation> { @Override public int compare(TargetLocation o1, TargetLocation o2) { return Integer.valueOf(o1.frameNumber).compareTo(Integer.valueOf(o2.frameNumber)); } } private final Color[] targetTypeColors = {Color.BLUE, Color.CYAN, Color.GREEN, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED}; /** * List of targets simultaneously present at a particular timestamp */ private class SimultaneouTargetLocations extends ArrayList<TargetLocation> { boolean hasTargetWithLocation() { for (TargetLocation t : this) { if (t.location != null) { return true; } } return false; } } class TargetLocation { int timestamp; int frameNumber; Point location; // center of target location int targetClassID; // class of target, i.e. car, person int dimx; // dimension of target x int dimy; public TargetLocation(int frameNumber, int timestamp, Point location, int targetTypeID, int dimx, int dimy) { this.frameNumber = frameNumber; this.timestamp = timestamp; this.location = location != null ? new Point(location) : null; this.targetClassID = targetTypeID; this.dimx = dimx; this.dimy = dimy; } private void draw(GLAutoDrawable drawable, GL2 gl) { // if (getTargetLocation() != null && getTargetLocation().location == null) { // textRenderer.beginRendering(drawable.getSurfaceWidth(), drawable.getSurfaceHeight()); // textRenderer.draw("Target not visible", chip.getSizeX() / 2, chip.getSizeY() / 2); // textRenderer.endRendering(); // return; gl.glPushMatrix(); gl.glTranslatef(location.x, location.y, 0f); float[] compArray = new float[4]; gl.glColor3fv(targetTypeColors[targetClassID % targetTypeColors.length].getColorComponents(compArray), 0); // gl.glColor4f(0, 1, 0, .5f); if (mouseQuad == null) { mouseQuad = glu.gluNewQuadric(); } glu.gluQuadricDrawStyle(mouseQuad, GLU.GLU_LINE); //glu.gluDisk(mouseQuad, getTargetRadius(), getTargetRadius(), 32, 1); int maxDim = Math.max(dimx, dimy); glu.gluDisk(mouseQuad, maxDim / 2, (maxDim / 2) + 0.1, 32, 1); //getTargetRadius(), getTargetRadius() + 1, 32, 1); gl.glPopMatrix(); } @Override public String toString() { return String.format("TargetLocation frameNumber=%d timestamp=%d location=%s", frameNumber, timestamp, location == null ? "null" : location.toString()); } } private void saveLocations(File f) { try { FileWriter writer = new FileWriter(f); writer.write(String.format("# target locations\n")); writer.write(String.format("# written %s\n", new Date().toString())); // writer.write("# maxTargets=" + maxTargets+"\n"); writer.write(String.format("# frameNumber timestamp x y targetTypeID\n")); for (Map.Entry<Integer, SimultaneouTargetLocations> entry : targetLocations.entrySet()) { for (TargetLocation l : entry.getValue()) { if (l.location != null) { writer.write(String.format("%d %d %d %d %d\n", l.frameNumber, l.timestamp, l.location.x, l.location.y, l.targetClassID, l.dimx, l.dimy)); } else { writer.write(String.format("%d %d -1 -1 -1\n", l.frameNumber, l.timestamp)); } } } writer.close(); log.info("wrote locations to file " + f.getAbsolutePath()); if (f.getPath() != null) { mapDataFilenameToTargetFilename.put(lastDataFilename, f.getPath()); } try { // Serialize to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput oos = new ObjectOutputStream(bos); oos.writeObject(mapDataFilenameToTargetFilename); oos.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); getPrefs().putByteArray("TargetLabeler.hashmap", buf); } catch (Exception e) { e.printStackTrace(); } } catch (IOException ex) { JOptionPane.showMessageDialog(glCanvas, ex.toString(), "Couldn't save locations", JOptionPane.WARNING_MESSAGE, null); return; } } /** * Loads last locations. Note that this is a lengthy operation */ synchronized public void loadLastLocations() { if (lastFileName == null) { return; } File f = new File(lastFileName); if (!f.exists() || !f.isFile()) { return; } loadLocations(f); } synchronized private void loadLocations(File f) { long startMs = System.currentTimeMillis(); log.info("loading " + f); doClearLocations(); TargetLocation tmpTargetLocation = null; try { setCursor(new Cursor(Cursor.WAIT_CURSOR)); targetLocations.clear(); minSampleTimestamp = Integer.MAX_VALUE; maxSampleTimestamp = Integer.MIN_VALUE; try { BufferedReader reader = new BufferedReader(new FileReader(f)); String s = reader.readLine(); StringBuilder sb = new StringBuilder(); while ((s != null) && s.startsWith(" sb.append(s + "\n"); s = reader.readLine(); } log.info("header lines on " + f.getAbsolutePath() + " are\n" + sb.toString()); Scanner scanner = new Scanner(reader); while (scanner.hasNext()) { try { int frame = scanner.nextInt(); int ts = scanner.nextInt(); int x = scanner.nextInt(); int y = scanner.nextInt(); int targetTypeID = 0; int targetdimx = targetRadius; int targetdimy = targetRadius; // see if more tokens in this line String mt = scanner.findInLine("\\d+"); if (mt != null) { targetTypeID = Integer.parseInt(scanner.match().group()); } mt = scanner.findInLine("\\d+"); if (mt != null) { targetdimx = Integer.parseInt(scanner.match().group()); } mt = scanner.findInLine("\\d+"); if (mt != null) { targetdimy = Integer.parseInt(scanner.match().group()); } tmpTargetLocation = new TargetLocation(frame, ts, new Point(x, y), targetTypeID, targetdimx, targetdimy); // read target location } catch (NoSuchElementException ex2) { throw new IOException(("couldn't parse file " + f) == null ? "null" : f.toString() + ", got InputMismatchException on line: " + s); } if ((tmpTargetLocation.location.x == -1) && (tmpTargetLocation.location.y == -1)) { tmpTargetLocation.location = null; } addSample(tmpTargetLocation.timestamp, tmpTargetLocation); markDataHasTarget(tmpTargetLocation.timestamp, tmpTargetLocation.location != null); if (tmpTargetLocation != null) { if (tmpTargetLocation.timestamp > maxSampleTimestamp) { maxSampleTimestamp = tmpTargetLocation.timestamp; } if (tmpTargetLocation.timestamp < minSampleTimestamp) { minSampleTimestamp = tmpTargetLocation.timestamp; } } } long endMs = System.currentTimeMillis(); log.info("Took " + (endMs - startMs) + " ms to load " + f + " with " + targetLocations.size() + " SimultaneouTargetLocations entries"); if (lastDataFilename != null) { mapDataFilenameToTargetFilename.put(lastDataFilename, f.getPath()); } this.targetLocation = null; // null out current location locationsLoadedFromFile = true; } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(glCanvas, ("couldn't find file " + f) == null ? "null" : f.toString() + ": got exception " + ex.toString(), "Couldn't load locations", JOptionPane.WARNING_MESSAGE, null); } catch (IOException ex) { JOptionPane.showMessageDialog(glCanvas, ("IOException with file " + f) == null ? "null" : f.toString() + ": got exception " + ex.toString(), "Couldn't load locations", JOptionPane.WARNING_MESSAGE, null); } } finally { setCursor(Cursor.getDefaultCursor()); } fixLabeledFraction(); } int maxDataHasTargetWarningCount = 10; /** * marks this point in time as reviewed already * * @param timestamp */ private void markDataReviewedButNoTargetPresent(int timestamp) { if (inputStreamDuration == 0) { return; } int frac = getFractionOfFileDuration(timestamp); labeledFractions[frac] = true; targetPresentInFractions[frac] = false; } private void markDataHasTarget(int timestamp, boolean visible) { if (inputStreamDuration == 0) { return; } int frac = getFractionOfFileDuration(timestamp); if ((frac < 0) || (frac >= labeledFractions.length)) { if (maxDataHasTargetWarningCount log.warning("fraction " + frac + " is out of range " + labeledFractions.length + ", something is wrong"); } if (maxDataHasTargetWarningCount == 0) { log.warning("suppressing futher warnings"); } return; } labeledFractions[frac] = true; targetPresentInFractions[frac] = visible; } private void fixLabeledFraction() { if (chip.getAeInputStream() != null) { firstInputStreamTimestamp = chip.getAeInputStream().getFirstTimestamp(); lastTimestamp = chip.getAeInputStream().getLastTimestamp(); inputStreamDuration = chip.getAeInputStream().getDurationUs(); fileLengthEvents = chip.getAeInputStream().size(); if (inputStreamDuration > 0) { if ((targetLocations == null) || targetLocations.isEmpty()) { Arrays.fill(labeledFractions, false); return; } for (Map.Entry<Integer, SimultaneouTargetLocations> t : targetLocations.entrySet()) { markDataHasTarget(t.getKey(), t.getValue().hasTargetWithLocation()); } } } } /** * @return the showLabeledFraction */ public boolean isShowLabeledFraction() { return showLabeledFraction; } /** * @param showLabeledFraction the showLabeledFraction to set */ public void setShowLabeledFraction(boolean showLabeledFraction) { this.showLabeledFraction = showLabeledFraction; putBoolean("showLabeledFraction", showLabeledFraction); } /** * @return the showHelpText */ public boolean isShowHelpText() { return showHelpText; } /** * @param showHelpText the showHelpText to set */ public void setShowHelpText(boolean showHelpText) { this.showHelpText = showHelpText; putBoolean("showHelpText", showHelpText); } @Override public synchronized void setFilterEnabled(boolean yes) { super.setFilterEnabled(yes); //To change body of generated methods, choose Tools | Templates. fixLabeledFraction(); } // /** // * @return the maxTargets // */ // public int getMaxTargets() { // return maxTargets; // /** // * @param maxTargets the maxTargets to set // */ // public void setMaxTargets(int maxTargets) { // this.maxTargets = maxTargets; /** * @return the currentTargetTypeID */ public int getCurrentTargetTypeID() { return currentTargetTypeID; } /** * @param currentTargetTypeID the currentTargetTypeID to set */ public void setCurrentTargetTypeID(int currentTargetTypeID) { // if (currentTargetTypeID >= maxTargets) { // currentTargetTypeID = maxTargets; this.currentTargetTypeID = currentTargetTypeID; putInt("currentTargetTypeID", currentTargetTypeID); } /** * @return the eraseSamplesEnabled */ public boolean isEraseSamplesEnabled() { return eraseSamplesEnabled; } /** * @param eraseSamplesEnabled the eraseSamplesEnabled to set */ public void setEraseSamplesEnabled(boolean eraseSamplesEnabled) { boolean old = this.eraseSamplesEnabled; this.eraseSamplesEnabled = eraseSamplesEnabled; getSupport().firePropertyChange("eraseSamplesEnabled", old, this.eraseSamplesEnabled); } @Override public void propertyChange(PropertyChangeEvent evt) { switch (evt.getPropertyName()) { case AEInputStream.EVENT_POSITION: filePositionEvents = (long) evt.getNewValue(); if ((chip.getAeViewer().getAePlayer() == null) || (chip.getAeViewer().getAePlayer().getAEInputStream() == null)) { log.warning("null input stream, cannot get most recent timestamp"); return; } filePositionTimestamp = chip.getAeViewer().getAePlayer().getAEInputStream().getMostRecentTimestamp(); break; case AEInputStream.EVENT_REWIND: case AEInputStream.EVENT_REPOSITIONED: // log.info("rewind to start or mark position or reposition event " + evt.toString()); if (evt.getNewValue() instanceof Long) { long position = (long) evt.getNewValue(); if (chip.getAeInputStream() == null) { log.warning("AE input stream is null, cannot determine timestamp after rewind"); return; } int timestamp = chip.getAeInputStream().getMostRecentTimestamp(); Map.Entry<Integer, SimultaneouTargetLocations> targetsBeforeRewind = targetLocations.lowerEntry(timestamp); if (targetsBeforeRewind != null) { currentFrameNumber = targetsBeforeRewind.getValue().get(0).frameNumber; lastFrameNumber = getCurrentFrameNumber() - 1; lastTimestamp = targetsBeforeRewind.getValue().get(0).timestamp; } else { currentFrameNumber = 0; lastFrameNumber = getCurrentFrameNumber() - 1; lastInputStreamTimestamp = Integer.MIN_VALUE; } } else { log.warning("couldn't determine stream position after rewind from PropertyChangeEvent " + evt.toString()); } shiftPressed = false; ctlPressed = false; // disable labeling on rewind to prevent bad labels at start if (evt.getPropertyName() == AEInputStream.EVENT_REWIND) { try { Thread.currentThread().sleep(1000);// time for preparing label } catch (InterruptedException e) { } } break; case AEInputStream.EVENT_INIT: fixLabeledFraction(); warnSave = true; if (evt.getNewValue() instanceof AEFileInputStream) { File f = ((AEFileInputStream) evt.getNewValue()).getFile(); lastDataFilename = f.getPath(); } break; } } /** * @return the showStatistics */ public boolean isShowStatistics() { return showStatistics; } /** * @param showStatistics the showStatistics to set */ public void setShowStatistics(boolean showStatistics) { this.showStatistics = showStatistics; putBoolean("showStatistics", showStatistics); } /** * @return the currentFrameNumber */ public int getCurrentFrameNumber() { return currentFrameNumber; } /** * False until locations are loaded from a file. Reset by clearLocations. * * @return the locationsLoadedFromFile true if data was loaded from a file * successfully */ public boolean isLocationsLoadedFromFile() { return locationsLoadedFromFile; } }
package com.amazon.aiv.sulfur; import com.amazon.aiv.sulfur.factories.PageFactory; import com.amazon.aiv.sulfur.utils.DataProviderUtils; import com.google.common.collect.ImmutableList; import org.testng.annotations.DataProvider; import java.util.*; /** * @author Ivan De Marino <demarino@amazon.com> */ public class BaseTest { // One factory for all the Tests, even across multiple threads private static final PageFactory mPageFactory = PageFactory.getInstance(); /** * @DataProvider of all the Pages found by the PageConfigFactory. * Name of the @DataProvider is "pageProvider" * * @return @DataProvider bi-dimensional array with list of all Pages for which a PageConfig was found */ @DataProvider(name = "pageProvider") public Object[][] provideConfiguredPages() { List<Object[]> pages = new ArrayList<Object[]>(); for (String configuredPageName : mPageFactory.getAvailablePageConfigs()) { pages.add(new Object[]{ configuredPageName }); } return pages.toArray(new Object[pages.size()][]); } /** * @DataProvider of Drivers (based on Sulfur Configuration). * Name of the @DataProvider is "driverProvider". * * @return @DataProvider bi-dimensional array with list of Drivers to use for the test */ @DataProvider(name = "driverProvider") public Object[][] provideConfiguredDrivers() { List<Object[]> drivers = new ArrayList<Object[]>(); for (String configuredDriver : mPageFactory.getConfig().getDrivers()) { drivers.add(new Object[]{ configuredDriver }); } return drivers.toArray(new Object[drivers.size()][]); } /** * Comodity method that delegates DataProviderUtils to create Cartesian Products of @DataProvider * * @see DataProviderUtils#cartesianProvider(Object[][]...) * @param providersData vararg of @DataProvider results * @return A @DataProvider iterator, ready to use */ public Iterator<Object[]> makeCartesianProvider(Object[][]...providersData) { return DataProviderUtils.cartesianProvider(providersData); } /** * Comodity method that delegates DataProviderUtils to create Cartesian Products of @DataProvider * * @see DataProviderUtils#cartesianProvider(java.util.List) * @param providersData List of @DataProvider results * @return A @DataProvider iterator, ready to use */ public Iterator<Object[]> makeCartesianProvider(List<Object[][]> providersData) { return DataProviderUtils.cartesianProvider(providersData); } /** * The PageFactory. * NOTE: There is ONE PageFactory for all the tests (synchronized) * * @return The PageFactory */ protected static PageFactory getPageFactory() { return mPageFactory; } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.util; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URLEncoder; import java.net.URLDecoder; import java.text.NumberFormat; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.Locale; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * String related utility functions. */ public class StringUtil { /** * Used to format objects in {@link #listToString(Object,StringUtil.Formatter)}. */ public static class Formatter { /** Formats the supplied object into a string. */ public String toString (Object object) { return object == null ? "null" : object.toString(); } /** Returns the string that will be prepended to a formatted list. */ public String getOpenBox () { return "("; } /** Returns the string that will be appended to a formatted list. */ public String getCloseBox () { return ")"; } } /** * @return true if the string is null or empty, false otherwise. * * @deprecated use isBlank instead. */ @Deprecated public static boolean blank (String value) { return isBlank(value); } /** * @return true if the string is null or empty, false otherwise. */ public static boolean isBlank (String value) { for (int ii = 0, ll = (value == null) ? 0 : value.length(); ii < ll; ii++) { if (!Character.isWhitespace(value.charAt(ii))) { return false; } } return true; } /** * Calls {@link String#trim} on non-null values, returns null for null values. */ public static String trim (String value) { return (value == null) ? null : value.trim(); } /** * @return the supplied string if it is non-null, "" if it is null. */ public static String deNull (String value) { return (value == null) ? "" : value; } /** * Truncate the specified String if it is longer than maxLength. */ public static String truncate (String s, int maxLength) { return truncate(s, maxLength, ""); } /** * Returns the string if it is non-blank (see {@link #isBlank}), the default value otherwise. */ public static String getOr (String value, String defval) { return isBlank(value) ? defval : value; } /** * Truncate the specified String if it is longer than maxLength. The string will be truncated * at a position such that it is maxLength chars long after the addition of the 'append' * String. * * @param append a String to add to the truncated String only after truncation. */ public static String truncate (String s, int maxLength, String append) { if ((s == null) || (s.length() <= maxLength)) { return s; } else { return s.substring(0, maxLength - append.length()) + append; } } /** * Returns a version of the supplied string with the first letter capitalized. */ public static String capitalize (String s) { if (isBlank(s)) { return s; } char c = s.charAt(0); if (Character.isUpperCase(c)) { return s; } else { return String.valueOf(Character.toUpperCase(c)) + s.substring(1); } } /** * Returns a US locale lower case string. Useful when manipulating filenames and resource * keys which would not have locale specific characters. */ public static String toUSLowerCase (String s) { return isBlank(s) ? s : s.toLowerCase(Locale.US); } /** * Returns a US locale upper case string. Useful when manipulating filenames and resource * keys which would not have locale specific characters. */ public static String toUSUpperCase (String s) { return isBlank(s) ? s : s.toUpperCase(Locale.US); } /** * Validates a character. */ public static interface CharacterValidator { public boolean isValid (char c); } /** * Sanitize the specified String so that only valid characters are in it. */ public static String sanitize (String source, CharacterValidator validator) { if (source == null) { return null; } int nn = source.length(); StringBuilder buf = new StringBuilder(nn); for (int ii=0; ii < nn; ii++) { char c = source.charAt(ii); if (validator.isValid(c)) { buf.append(c); } } return buf.toString(); } /** * Sanitize the specified String such that each character must match against the regex * specified. */ public static String sanitize (String source, String charRegex) { final StringBuilder buf = new StringBuilder(" "); final Matcher matcher = Pattern.compile(charRegex).matcher(buf); return sanitize(source, new CharacterValidator() { public boolean isValid (char c) { buf.setCharAt(0, c); return matcher.matches(); } }); } /** * Returns a new string based on <code>source</code> with all instances of <code>before</code> * replaced with <code>after</code>. */ public static String replace (String source, String before, String after) { int pos = source.indexOf(before); if (pos == -1) { return source; } StringBuilder sb = new StringBuilder(source.length() + 32); int blength = before.length(); int start = 0; while (pos != -1) { sb.append(source.substring(start, pos)); sb.append(after); start = pos + blength; pos = source.indexOf(before, start); } sb.append(source.substring(start)); return sb.toString(); } /** * Pads the supplied string to the requested string width by appending spaces to the end of the * returned string. If the original string is wider than the requested width, it is returned * unmodified. */ public static String pad (String value, int width) { // sanity check if (width <= 0) { throw new IllegalArgumentException("Pad width must be greater than zero."); } else if (value.length() >= width) { return value; } else { return value + spaces(width-value.length()); } } /** * Pads the supplied string to the requested string width by prepending spaces to the end of * the returned string. If the original string is wider than the requested width, it is * returned unmodified. */ public static String prepad (String value, int width) { // sanity check if (width <= 0) { throw new IllegalArgumentException("Pad width must be greater than zero."); } else if (value.length() >= width) { return value; } else { return spaces(width-value.length()) + value; } } /** * Returns a string containing the requested number of spaces. */ public static String spaces (int count) { return fill(' ', count); } /** * Returns a string containing the specified character repeated the specified number of times. */ public static String fill (char c, int count) { char[] sameChars = new char[count]; Arrays.fill(sameChars, c); return new String(sameChars); } /** * Returns whether the supplied string represents an integer value by attempting to parse it * with {@link Integer#parseInt}. */ public static boolean isInteger (String value) { try { Integer.parseInt(value); return true; } catch (NumberFormatException nfe) { // fall through } return false; } /** * Formats a floating point value with useful default rules; ie. always display a digit to the * left of the decimal and display only two digits to the right of the decimal (rounding as * necessary). */ public static String format (float value) { return _ffmt.format(value); } /** * Formats a floating point value with useful default rules; ie. always display a digit to the * left of the decimal and display only two digits to the right of the decimal (rounding as * necessary). */ public static String format (double value) { return _ffmt.format(value); } /** * Converts the supplied object to a string. Normally this is accomplished via the object's * built in <code>toString()</code> method, but in the case of arrays, <code>toString()</code> * is called on each element and the contents are listed like so: * * <pre> * (value, value, value) * </pre> * * Arrays of ints, longs, floats and doubles are also handled for convenience. * * <p> Additionally, <code>Enumeration</code> or <code>Iterator</code> objects can be passed * and they will be enumerated and output in a similar manner to arrays. Bear in mind that this * uses up the enumeration or iterator in question. * * <p> Also note that passing null will result in the string "null" being returned. */ public static String toString (Object val) { StringBuilder buf = new StringBuilder(); toString(buf, val); return buf.toString(); } /** * Like the single argument {@link #toString(Object)} with the additional function of * specifying the characters that are used to box in list and array types. For example, if "[" * and "]" were supplied, an int array might be formatted like so: <code>[1, 3, 5]</code>. */ public static String toString ( Object val, String openBox, String closeBox) { StringBuilder buf = new StringBuilder(); toString(buf, val, openBox, closeBox); return buf.toString(); } /** * Converts the supplied value to a string and appends it to the supplied string buffer. See * the single argument version for more information. * * @param buf the string buffer to which we will append the string. * @param val the value from which to generate the string. */ public static void toString (StringBuilder buf, Object val) { toString(buf, val, "(", ")"); } /** * Converts the supplied value to a string and appends it to the supplied string buffer. The * specified boxing characters are used to enclose list and array types. For example, if "[" * and "]" were supplied, an int array might be formatted like so: <code>[1, 3, 5]</code>. * * @param buf the string buffer to which we will append the string. * @param val the value from which to generate the string. * @param openBox the opening box character. * @param closeBox the closing box character. */ public static void toString (StringBuilder buf, Object val, String openBox, String closeBox) { toString(buf, val, openBox, closeBox, ", "); } /** * Converts the supplied value to a string and appends it to the supplied string buffer. The * specified boxing characters are used to enclose list and array types. For example, if "[" * and "]" were supplied, an int array might be formatted like so: <code>[1, 3, 5]</code>. * * @param buf the string buffer to which we will append the string. * @param val the value from which to generate the string. * @param openBox the opening box character. * @param closeBox the closing box character. * @param sep the separator string. */ public static void toString ( StringBuilder buf, Object val, String openBox, String closeBox, String sep) { if (val instanceof byte[]) { buf.append(openBox); byte[] v = (byte[])val; for (int i = 0; i < v.length; i++) { if (i > 0) { buf.append(sep); } buf.append(v[i]); } buf.append(closeBox); } else if (val instanceof short[]) { buf.append(openBox); short[] v = (short[])val; for (short i = 0; i < v.length; i++) { if (i > 0) { buf.append(sep); } buf.append(v[i]); } buf.append(closeBox); } else if (val instanceof int[]) { buf.append(openBox); int[] v = (int[])val; for (int i = 0; i < v.length; i++) { if (i > 0) { buf.append(sep); } buf.append(v[i]); } buf.append(closeBox); } else if (val instanceof long[]) { buf.append(openBox); long[] v = (long[])val; for (int i = 0; i < v.length; i++) { if (i > 0) { buf.append(sep); } buf.append(v[i]); } buf.append(closeBox); } else if (val instanceof float[]) { buf.append(openBox); float[] v = (float[])val; for (int i = 0; i < v.length; i++) { if (i > 0) { buf.append(sep); } buf.append(v[i]); } buf.append(closeBox); } else if (val instanceof double[]) { buf.append(openBox); double[] v = (double[])val; for (int i = 0; i < v.length; i++) { if (i > 0) { buf.append(sep); } buf.append(v[i]); } buf.append(closeBox); } else if (val instanceof Object[]) { buf.append(openBox); Object[] v = (Object[])val; for (int i = 0; i < v.length; i++) { if (i > 0) { buf.append(sep); } buf.append(toString(v[i])); } buf.append(closeBox); } else if (val instanceof boolean[]) { buf.append(openBox); boolean[] v = (boolean[])val; for (int i = 0; i < v.length; i++) { if (i > 0) { buf.append(sep); } buf.append(v[i] ? "t" : "f"); } buf.append(closeBox); } else if (val instanceof Iterable) { toString(buf, ((Iterable<?>)val).iterator(), openBox, closeBox); } else if (val instanceof Iterator) { buf.append(openBox); Iterator<?> iter = (Iterator<?>)val; for (int i = 0; iter.hasNext(); i++) { if (i > 0) { buf.append(sep); } buf.append(toString(iter.next())); } buf.append(closeBox); } else if (val instanceof Enumeration) { buf.append(openBox); Enumeration<?> enm = (Enumeration<?>)val; for (int i = 0; enm.hasMoreElements(); i++) { if (i > 0) { buf.append(sep); } buf.append(toString(enm.nextElement())); } buf.append(closeBox); } else if (val instanceof Point2D) { Point2D p = (Point2D)val; buf.append(openBox); coordsToString(buf, (int)p.getX(), (int)p.getY()); buf.append(closeBox); } else if (val instanceof Dimension2D) { Dimension2D d = (Dimension2D)val; buf.append(openBox); buf.append(d.getWidth()).append("x").append(d.getHeight()); buf.append(closeBox); } else if (val instanceof Rectangle2D) { Rectangle2D r = (Rectangle2D)val; buf.append(openBox); buf.append(r.getWidth()).append("x").append(r.getHeight()); coordsToString(buf, (int)r.getX(), (int)r.getY()); buf.append(closeBox); } else { buf.append(val); } } /** * Formats a collection of elements (either an array of objects, an {@link Iterator}, an {@link * Enumeration} or a {@link Collection}) using the supplied formatter on each element. Note * that if you simply wish to format a collection of elements by calling {@link * Object#toString} on each element, you can just pass the list to the {@link * #toString(Object)} method which will do just that. */ public static String listToString (Object val, Formatter formatter) { StringBuilder buf = new StringBuilder(); listToString(buf, val, formatter); return buf.toString(); } /** * Formats the supplied collection into the supplied string buffer using the supplied * formatter. See {@link #listToString(Object,StringUtil.Formatter)} for more details. */ public static void listToString (StringBuilder buf, Object val, Formatter formatter) { // get an iterator if this is a collection if (val instanceof Iterable) { val = ((Iterable<?>)val).iterator(); } String openBox = formatter.getOpenBox(); String closeBox = formatter.getCloseBox(); if (val instanceof Object[]) { buf.append(openBox); Object[] v = (Object[])val; for (int i = 0; i < v.length; i++) { if (i > 0) { buf.append(", "); } buf.append(formatter.toString(v[i])); } buf.append(closeBox); } else if (val instanceof Iterator) { buf.append(openBox); Iterator<?> iter = (Iterator<?>)val; for (int i = 0; iter.hasNext(); i++) { if (i > 0) { buf.append(", "); } buf.append(formatter.toString(iter.next())); } buf.append(closeBox); } else if (val instanceof Enumeration) { buf.append(openBox); Enumeration<?> enm = (Enumeration<?>)val; for (int i = 0; enm.hasMoreElements(); i++) { if (i > 0) { buf.append(", "); } buf.append(formatter.toString(enm.nextElement())); } buf.append(closeBox); } else { // fall back on the general purpose toString(buf, val); } } /** * Generates a string representation of the supplied object by calling {@link #toString} on the * contents of its public fields and prefixing that by the name of the fields. For example: * * <p><code>[itemId=25, itemName=Elvis, itemCoords=(14, 25)]</code> */ public static String fieldsToString (Object object) { return fieldsToString(object, ", "); } /** * Like {@link #fieldsToString(Object)} except that the supplied separator string will be used * between fields. */ public static String fieldsToString (Object object, String sep) { StringBuilder buf = new StringBuilder("["); fieldsToString(buf, object, sep); return buf.append("]").toString(); } /** * Appends to the supplied string buffer a representation of the supplied object by calling * {@link #toString} on the contents of its public fields and prefixing that by the name of the * fields. For example: * * <p><code>itemId=25, itemName=Elvis, itemCoords=(14, 25)</code> * * <p>Note: unlike the version of this method that returns a string, enclosing brackets are not * included in the output of this method. */ public static void fieldsToString (StringBuilder buf, Object object) { fieldsToString(buf, object, ", "); } /** * Like {@link #fieldsToString(StringBuilder,Object)} except that the supplied separator will * be used between fields. */ public static void fieldsToString ( StringBuilder buf, Object object, String sep) { Class<?> clazz = object.getClass(); Field[] fields = clazz.getFields(); int written = 0; // we only want non-static fields for (int i = 0; i < fields.length; i++) { int mods = fields[i].getModifiers(); if ((mods & Modifier.PUBLIC) == 0 || (mods & Modifier.STATIC) != 0) { continue; } if (written > 0) { buf.append(sep); } // look for a toString() method for this field buf.append(fields[i].getName()).append("="); try { try { Method meth = clazz.getMethod(fields[i].getName() + "ToString", new Class[0]); buf.append(meth.invoke(object, (Object[]) null)); } catch (NoSuchMethodException nsme) { toString(buf, fields[i].get(object)); } } catch (Exception e) { buf.append("<error: " + e + ">"); } written++; } } /** * Formats a pair of coordinates such that positive values are rendered with a plus prefix and * negative values with a minus prefix. Examples would look like: <code>+3+4</code> * <code>-5+7</code>, etc. */ public static String coordsToString (int x, int y) { StringBuilder buf = new StringBuilder(); coordsToString(buf, x, y); return buf.toString(); } /** * Formats a pair of coordinates such that positive values are rendered with a plus prefix and * negative values with a minus prefix. Examples would look like: <code>+3+4</code> * <code>-5+7</code>, etc. */ public static void coordsToString (StringBuilder buf, int x, int y) { if (x >= 0) { buf.append("+"); } buf.append(x); if (y >= 0) { buf.append("+"); } buf.append(y); } /** * Attempts to generate a string representation of the object using {@link Object#toString}, * but catches any exceptions that are thrown and reports them in the returned string * instead. Useful for situations where you can't trust the rat bastards that implemented the * object you're toString()ing. */ public static String safeToString (Object object) { try { return toString(object); } catch (Throwable t) { // We catch any throwable, even Errors. Someone is just trying to debug something, // probably inside another catch block. return "<toString() failure: " + t + ">"; } } /** * URL encodes the specified string using the UTF-8 character encoding. */ public static String encode (String s) { try { return (s != null) ? URLEncoder.encode(s, "UTF-8") : null; } catch (UnsupportedEncodingException uee) { throw new RuntimeException("UTF-8 is unknown in this Java."); } } /** * URL decodes the specified string using the UTF-8 character encoding. */ public static String decode (String s) { try { return (s != null) ? URLDecoder.decode(s, "UTF-8") : null; } catch (UnsupportedEncodingException uee) { throw new RuntimeException("UTF-8 is unknown in this Java."); } } /** * Generates a string from the supplied bytes that is the HEX encoded representation of those * bytes. Returns the empty string for a <code>null</code> or empty byte array. * * @param bytes the bytes for which we want a string representation. * @param count the number of bytes to stop at (which will be coerced into being <= the length * of the array). */ public static String hexlate (byte[] bytes, int count) { if (bytes == null) { return ""; } count = Math.min(count, bytes.length); char[] chars = new char[count*2]; for (int i = 0; i < count; i++) { int val = bytes[i]; if (val < 0) { val += 256; } chars[2*i] = XLATE.charAt(val/16); chars[2*i+1] = XLATE.charAt(val%16); } return new String(chars); } /** * Generates a string from the supplied bytes that is the HEX encoded representation of those * bytes. */ public static String hexlate (byte[] bytes) { return (bytes == null) ? "" : hexlate(bytes, bytes.length); } /** * Turn a hexlated String back into a byte array. */ public static byte[] unhexlate (String hex) { if (hex == null || (hex.length() % 2 != 0)) { return null; } // if for some reason we are given a hex string that wasn't made by hexlate, convert to // lowercase so things work. hex = hex.toLowerCase(); byte[] data = new byte[hex.length()/2]; for (int ii = 0; ii < hex.length(); ii+=2) { int value = (byte)(XLATE.indexOf(hex.charAt(ii)) << 4); value += XLATE.indexOf(hex.charAt(ii+1)); // values over 127 are wrapped around, restoring negative bytes data[ii/2] = (byte)value; } return data; } /** * Encodes the supplied source text into an MD5 hash. */ public static byte[] md5 (String source) { return digest("MD5", source); } /** * Returns a hex string representing the MD5 encoded source. * * @exception RuntimeException thrown if the MD5 codec was not available in this JVM. */ public static String md5hex (String source) { return hexlate(md5(source)); } /** * Returns a hex string representing the SHA-1 encoded source. * * @exception RuntimeException thrown if the SHA-1 codec was not available in this JVM. */ public static String sha1hex (String source) { return hexlate(digest("SHA-1", source)); } /** * Parses an array of signed byte-sized integers from their string representation. The array * should be represented as a bare list of numbers separated by commas, for example: * * <pre>25, 17, 21, 99</pre> * * Any inability to parse the short array will result in the function returning null. */ public static byte[] parseByteArray (String source) { StringTokenizer tok = new StringTokenizer(source, ","); byte[] vals = new byte[tok.countTokens()]; for (int i = 0; tok.hasMoreTokens(); i++) { try { // trim the whitespace from the token vals[i] = Byte.parseByte(tok.nextToken().trim()); } catch (NumberFormatException nfe) { return null; } } return vals; } /** * Parses an array of short integers from their string representation. The array should be * represented as a bare list of numbers separated by commas, for example: * * <pre>25, 17, 21, 99</pre> * * Any inability to parse the short array will result in the function returning null. */ public static short[] parseShortArray (String source) { StringTokenizer tok = new StringTokenizer(source, ","); short[] vals = new short[tok.countTokens()]; for (int i = 0; tok.hasMoreTokens(); i++) { try { // trim the whitespace from the token vals[i] = Short.parseShort(tok.nextToken().trim()); } catch (NumberFormatException nfe) { return null; } } return vals; } /** * Parses an array of integers from it's string representation. The array should be represented * as a bare list of numbers separated by commas, for example: * * <pre>25, 17, 21, 99</pre> * * Any inability to parse the int array will result in the function returning null. */ public static int[] parseIntArray (String source) { StringTokenizer tok = new StringTokenizer(source, ","); int[] vals = new int[tok.countTokens()]; for (int i = 0; tok.hasMoreTokens(); i++) { try { // trim the whitespace from the token vals[i] = Integer.parseInt(tok.nextToken().trim()); } catch (NumberFormatException nfe) { return null; } } return vals; } /** * Parses an array of longs from it's string representation. The array should be represented as * a bare list of numbers separated by commas, for example: * * <pre>25, 17125141422, 21, 99</pre> * * Any inability to parse the long array will result in the function returning null. */ public static long[] parseLongArray (String source) { StringTokenizer tok = new StringTokenizer(source, ","); long[] vals = new long[tok.countTokens()]; for (int i = 0; tok.hasMoreTokens(); i++) { try { // trim the whitespace from the token vals[i] = Long.parseLong(tok.nextToken().trim()); } catch (NumberFormatException nfe) { return null; } } return vals; } /** * Parses an array of floats from it's string representation. The array should be represented * as a bare list of numbers separated by commas, for example: * * <pre>25.0, .5, 1, 0.99</pre> * * Any inability to parse the array will result in the function returning null. */ public static float[] parseFloatArray (String source) { StringTokenizer tok = new StringTokenizer(source, ","); float[] vals = new float[tok.countTokens()]; for (int i = 0; tok.hasMoreTokens(); i++) { try { // trim the whitespace from the token vals[i] = Float.parseFloat(tok.nextToken().trim()); } catch (NumberFormatException nfe) { return null; } } return vals; } /** * Parses an array of doubles from its string representation. The array should be represented * as a bare list of numbers separated by commas, for example: * * <pre>25.0, .5, 1, 0.99</pre> * * Any inability to parse the array will result in the function returning null. */ public static double[] parseDoubleArray (String source) { StringTokenizer tok = new StringTokenizer(source, ","); double[] vals = new double[tok.countTokens()]; for (int i = 0; tok.hasMoreTokens(); i++) { try { // trim the whitespace from the token vals[i] = Double.parseDouble(tok.nextToken().trim()); } catch (NumberFormatException nfe) { return null; } } return vals; } /** * Parses an array of booleans from its string representation. The array should be represented * as a bare list of numbers separated by commas, for example: * * <pre>false, false, true, false</pre> */ public static boolean[] parseBooleanArray (String source) { StringTokenizer tok = new StringTokenizer(source, ","); boolean[] vals = new boolean[tok.countTokens()]; for (int i = 0; tok.hasMoreTokens(); i++) { // accept a lone 't' for true for compatibility with toString(boolean[]) String token = tok.nextToken().trim(); vals[i] = Boolean.parseBoolean(token) || token.equalsIgnoreCase("t"); } return vals; } /** * Parses an array of strings from a single string. The array should be represented as a bare * list of strings separated by commas, for example: * * <pre>mary, had, a, little, lamb, and, an, escaped, comma,,</pre> * * If a comma is desired in one of the strings, it should be escaped by putting two commas in a * row. Any inability to parse the string array will result in the function returning null. */ public static String[] parseStringArray (String source) { return parseStringArray(source, false); } /** * Like {@link #parseStringArray(String)} but can be instructed to invoke {@link String#intern} * on the strings being parsed into the array. */ public static String[] parseStringArray (String source, boolean intern) { int tcount = 0, tpos = -1, tstart = 0; // empty strings result in zero length arrays if (source.length() == 0) { return new String[0]; } // sort out escaped commas source = replace(source, ",,", "%COMMA%"); // count up the number of tokens while ((tpos = source.indexOf(",", tpos+1)) != -1) { tcount++; } String[] tokens = new String[tcount+1]; tpos = -1; tcount = 0; // do the split while ((tpos = source.indexOf(",", tpos+1)) != -1) { tokens[tcount] = source.substring(tstart, tpos); tokens[tcount] = replace(tokens[tcount].trim(), "%COMMA%", ","); if (intern) { tokens[tcount] = tokens[tcount].intern(); } tstart = tpos+1; tcount++; } // grab the last token tokens[tcount] = source.substring(tstart); tokens[tcount] = replace(tokens[tcount].trim(), "%COMMA%", ","); return tokens; } /** * Joins an array of strings (or objects which will be converted to strings) into a single * string separated by commas. */ public static String join (Object[] values) { return join(values, false); } /** * Joins an array of strings into a single string, separated by commas, and optionally escaping * commas that occur in the individual string values such that a subsequent call to {@link * #parseStringArray} would recreate the string array properly. Any elements in the values * array that are null will be treated as an empty string. */ public static String join (Object[] values, boolean escape) { return join(values, ", ", escape); } /** * Joins the supplied array of strings into a single string separated by the supplied * separator. */ public static String join (Object[] values, String separator) { return join(values, separator, false); } /** * Joins an array of strings into a single string, separated by commas, and escaping commas * that occur in the individual string values such that a subsequent call to {@link * #parseStringArray} would recreate the string array properly. Any elements in the values * array that are null will be treated as an empty string. */ public static String joinEscaped (String[] values) { return join(values, true); } /** * Splits the supplied string into components based on the specified separator string. */ public static String[] split (String source, String sep) { // handle the special case of a zero-component source if (isBlank(source)) { return new String[0]; } int tcount = 0, tpos = -1, tstart = 0; // count up the number of tokens while ((tpos = source.indexOf(sep, tpos+1)) != -1) { tcount++; } String[] tokens = new String[tcount+1]; tpos = -1; tcount = 0; // do the split while ((tpos = source.indexOf(sep, tpos+1)) != -1) { tokens[tcount] = source.substring(tstart, tpos); tstart = tpos+1; tcount++; } // grab the last token tokens[tcount] = source.substring(tstart); return tokens; } /** * Returns an array containing the values in the supplied array converted into a table of * values wrapped at the specified column count and fit into the specified field width. For * example, a call like <code>toWrappedString(values, 5, 3)</code> might result in output like * so: * * <pre> * 12 1 9 10 3 * 1 5 7 9 11 * 39 15 12 80 16 * </pre> */ public static String toMatrixString (int[] values, int colCount, int fieldWidth) { StringBuilder buf = new StringBuilder(); StringBuilder valbuf = new StringBuilder(); for (int i = 0; i < values.length; i++) { // format the integer value valbuf.setLength(0); valbuf.append(values[i]); // pad with the necessary spaces int spaces = fieldWidth - valbuf.length(); for (int s = 0; s < spaces; s++) { buf.append(" "); } // append the value itself buf.append(valbuf); // if we're at the end of a row but not the end of the whole integer list, append a // newline if (i % colCount == (colCount-1) && i != values.length-1) { buf.append(LINE_SEPARATOR); } } return buf.toString(); } /** * Used to convert a time interval to a more easily human readable string of the form: <code>1d * 15h 4m 15s 987m</code>. */ public static String intervalToString (long millis) { StringBuilder buf = new StringBuilder(); boolean started = false; long days = millis / (24 * 60 * 60 * 1000); if (days != 0) { buf.append(days).append("d "); started = true; } long hours = (millis / (60 * 60 * 1000)) % 24; if (started || hours != 0) { buf.append(hours).append("h "); } long minutes = (millis / (60 * 1000)) % 60; if (started || minutes != 0) { buf.append(minutes).append("m "); } long seconds = (millis / (1000)) % 60; if (started || seconds != 0) { buf.append(seconds).append("s "); } buf.append(millis % 1000).append("m"); return buf.toString(); } /** * Returns the class name of the supplied object, truncated to one package prior to the actual * class name. For example, <code>com.samskivert.util.StringUtil</code> would be reported as * <code>util.StringUtil</code>. If a null object is passed in, <code>null</code> is returned. */ public static String shortClassName (Object object) { return (object == null) ? "null" : shortClassName(object.getClass()); } /** * Returns the supplied class's name, truncated to one package prior to the actual class * name. For example, <code>com.samskivert.util.StringUtil</code> would be reported as * <code>util.StringUtil</code>. */ public static String shortClassName (Class<?> clazz) { return shortClassName(clazz.getName()); } /** * Returns the supplied class name truncated to one package prior to the actual class name. For * example, <code>com.samskivert.util.StringUtil</code> would be reported as * <code>util.StringUtil</code>. */ public static String shortClassName (String name) { int didx = name.lastIndexOf("."); if (didx == -1) { return name; } didx = name.lastIndexOf(".", didx-1); if (didx == -1) { return name; } return name.substring(didx+1); } /** * Converts a name of the form <code>weAreSoCool</code> to a name of the form * <code>WE_ARE_SO_COOL</code>. */ public static String unStudlyName (String name) { boolean seenLower = false; StringBuilder nname = new StringBuilder(); int nlen = name.length(); for (int i = 0; i < nlen; i++) { char c = name.charAt(i); // if we see an upper case character and we've seen a lower case character since the // last time we did so, slip in an _ if (Character.isUpperCase(c)) { if (seenLower) { nname.append("_"); } seenLower = false; nname.append(c); } else { seenLower = true; nname.append(Character.toUpperCase(c)); } } return nname.toString(); } /** * See {@link #stringCode(String,StringBuilder)}. */ public static int stringCode (String value) { return stringCode(value, null); } /** * Encodes (case-insensitively) a short English language string into a semi-unique * integer. This is done by selecting the first eight characters in the string that fall into * the set of the 16 most frequently used characters in the English language and converting * them to a 4 bit value and storing the result into the returned integer. * * <p> This method is useful for mapping a set of string constants to a set of unique integers * (e.g. mapping an enumerated type to an integer and back without having to require that the * declaration order of the enumerated type remain constant for all time). The caller must, of * course, ensure that no collisions occur. * * @param value the string to be encoded. * @param encoded if non-null, a string buffer into which the characters used for the encoding * will be recorded. */ public static int stringCode (String value, StringBuilder encoded) { int code = 0; for (int ii = 0, uu = 0; ii < value.length(); ii++) { char c = Character.toLowerCase(value.charAt(ii)); Integer cc = _letterToBits.get(c); if (cc == null) { continue; } code += cc.intValue(); if (encoded != null) { encoded.append(c); } if (++uu == 8) { break; } code <<= 4; } return code; } /** * Wordwraps a string. Treats any whitespace character as a single character. * * <p>If you want the text to wrap for a graphical display, use a wordwrapping component * such as {@link com.samskivert.swing.Label} instead. * * @param str String to word-wrap. * @param width Maximum line length. */ public static String wordWrap (String str, int width) { int size = str.length(); StringBuilder buf = new StringBuilder(size + size/width); int lastidx = 0; while (lastidx < size) { if (lastidx + width >= size) { buf.append(str.substring(lastidx)); break; } int lastws = lastidx; for (int ii = lastidx, ll = lastidx + width; ii < ll; ii++) { char c = str.charAt(ii); if (c == '\n') { buf.append(str.substring(lastidx, ii + 1)); lastidx = ii + 1; break; } else if (Character.isWhitespace(c)) { lastws = ii; } } if (lastws == lastidx) { buf.append(str.substring(lastidx, lastidx + width)).append(LINE_SEPARATOR); lastidx += width; } else if (lastws > lastidx) { buf.append(str.substring(lastidx, lastws)).append(LINE_SEPARATOR); lastidx = lastws + 1; } } return buf.toString(); } /** * Helper function for the various <code>join</code> methods. */ protected static String join (Object[] values, String separator, boolean escape) { StringBuilder buf = new StringBuilder(); int vlength = values.length; for (int i = 0; i < vlength; i++) { if (i > 0) { buf.append(separator); } String value = (values[i] == null) ? "" : values[i].toString(); buf.append((escape) ? replace(value, ",", ",,") : value); } return buf.toString(); } /** * Helper function for {@link #md5hex} and {@link #sha1hex}. */ protected static byte[] digest (String codec, String source) { try { MessageDigest digest = MessageDigest.getInstance(codec); return digest.digest(source.getBytes()); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException(codec + " codec not available"); } } /** Used to easily format floats with sensible defaults. */ protected static final NumberFormat _ffmt = NumberFormat.getInstance(); static { _ffmt.setMinimumIntegerDigits(1); _ffmt.setMinimumFractionDigits(1); _ffmt.setMaximumFractionDigits(2); } /** Used by {@link #hexlate} and {@link #unhexlate}. */ protected static final String XLATE = "0123456789abcdef"; /** Maps the 16 most frequent letters in the English language to a number between 0 and * 15. Used by {@link #stringCode}. */ protected static final IntMap<Integer> _letterToBits = IntMaps.newHashIntMap(); static { String mostCommon = "etaoinsrhldcumfp"; for (int ii = mostCommon.length() - 1; ii >= 0; ii _letterToBits.put(mostCommon.charAt(ii), Integer.valueOf(ii)); } // sorry g, w, y, b, v, k, x, j, q, z } /** The line separator for this platform. */ protected static String LINE_SEPARATOR = "\n"; static { try { LINE_SEPARATOR = System.getProperty("line.separator"); } catch (Exception e) { } } }
package com.ebay.build.service.portal; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; /** * return dynamic url according to the params. * @author wecai * */ @Path("portal") public class RaptorPortalService { @GET @Produces(MediaType.TEXT_PLAIN) public String getPortal(@Context UriInfo uriInfo, @QueryParam("raptorVersion") @DefaultValue("2.0.0") String raptor, @QueryParam("rideVersion") String ride, @QueryParam("jvmVersion") String jvm) { if (ride == null || ride.startsWith("5.0")) { return "http://invalid"; } return "https://github.scm.corp.ebay.com/pages/DevExRelease/RIDEWelcome/"; } }
package ch.elexis.core.ui.views.artikel; import java.util.List; import java.util.Optional; import javax.inject.Inject; import javax.inject.Named; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.e4.ui.model.application.ui.basic.MPart; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Table; import org.eclipse.ui.part.ViewPart; import ch.elexis.core.constants.Preferences; import ch.elexis.core.data.service.StockServiceHolder; import ch.elexis.core.data.util.Extensions; import ch.elexis.core.model.IStockEntry; import ch.elexis.core.ui.commands.EditEigenartikelUi; import ch.elexis.core.ui.constants.ExtensionPointConstantsUi; import ch.elexis.core.ui.util.CoreUiUtil; import ch.elexis.core.ui.util.SWTHelper; import ch.elexis.core.ui.util.viewers.CommonViewer; import ch.elexis.core.ui.util.viewers.ViewerConfigurer; import ch.elexis.core.ui.views.codesystems.CodeSystemDescription; import ch.elexis.core.ui.views.provider.StockEntryLabelProvider; import ch.elexis.data.PersistentObject; public class ArtikelSelektor extends ViewPart { public ArtikelSelektor(){} public static final String ID = "ch.elexis.ArtikelSelektor"; //$NON-NLS-1$ CTabFolder ctab; TableViewer tv; @Override public void createPartControl(final Composite parent){ parent.setLayout(new GridLayout()); ctab = new CTabFolder(parent, SWT.NONE); ctab.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); java.util.List<IConfigurationElement> list = Extensions.getExtensions(ExtensionPointConstantsUi.VERRECHNUNGSCODE); //$NON-NLS-1$ ctab.addSelectionListener(new TabSelectionListener()); for (IConfigurationElement ice : list) { if ("Artikel".equals(ice.getName())) { //$NON-NLS-1$ Optional<CodeSystemDescription> description = CodeSystemDescription.of(ice); if (description.isPresent()) { CTabItem ci = new CTabItem(ctab, SWT.NONE); ci.setText(description.get().getCodeSystemName()); ci.setData(description.get()); //$NON-NLS-1$ } } } CTabItem ci = new CTabItem(ctab, SWT.NONE); Composite c = new Composite(ctab, SWT.NONE); c.setLayout(new GridLayout()); ci.setControl(c); ci.setText(Messages.ArtikelSelector_stockArticles); Table table = new Table(c, SWT.SIMPLE | SWT.V_SCROLL); table.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); tv = new TableViewer(table); tv.setContentProvider(ArrayContentProvider.getInstance()); tv.setLabelProvider(new StockEntryLabelProvider() { @Override public String getColumnText(Object element, int columnIndex){ IStockEntry se = (IStockEntry) element; if (se.getArticle() != null) { String ret = se.getArticle().getName(); Long amount = StockServiceHolder.get().getCumulatedStockForArticle(se.getArticle()); if (amount != null) { ret += " (" + Long.toString(amount) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } return ret; } else { return se.getLabel(); } } }); StockEntryLoader loader = new StockEntryLoader(tv); loader.schedule(); } @Override public void setFocus(){ // TODO Automatisch erstellter Methoden-Stub } @Override public void dispose(){ } // class LagerLabelProvider extends DefaultLabelProvider implements ITableLabelProvider { // @Override // public Image getColumnImage(final Object element, final int columnIndex){ // if (element instanceof Artikel) { // return null; // } else { // return Images.IMG_ACHTUNG.getImage(); // @Override // public String getColumnText(final Object element, final int columnIndex){ // if (element instanceof Artikel) { // Artikel art = (Artikel) element; // Availability availability = CoreHub.getStockService().getCumulatedAvailabilityForArticle(art); // String ret = art.getInternalName(); // if (availability!=null) { // ret += " (" + availability.toString() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ // return ret; // return super.getColumnText(element, columnIndex); @org.eclipse.e4.core.di.annotations.Optional @Inject public void setFixLayout(MPart part, @Named(Preferences.USR_FIX_LAYOUT) boolean currentState){ CoreUiUtil.updateFixLayout(part, currentState); } private class TabSelectionListener extends SelectionAdapter { @Override public void widgetSelected(SelectionEvent e){ CTabItem top = ctab.getSelection(); if (top != null) { if (top.getControl() == null) { CommonViewer cv = new CommonViewer(); CodeSystemDescription description = (CodeSystemDescription) top.getData(); //$NON-NLS-1$ ViewerConfigurer vc = description.getCodeSelectorFactory().createViewerConfigurer(cv); Composite c = new Composite(ctab, SWT.NONE); c.setLayout(new GridLayout()); cv.create(vc, c, SWT.V_SCROLL, getViewSite()); top.setControl(c); top.setData(cv); cv.addDoubleClickListener(new CommonViewer.PoDoubleClickListener() { public void doubleClicked(final PersistentObject obj, final CommonViewer cv){ EditEigenartikelUi.executeWithParams(obj); } }); vc.getContentProvider().startListening(); } } } } private static class StockEntryLoader extends Job { private Viewer viewer; private List<ch.elexis.core.model.IStockEntry> loaded; public StockEntryLoader(Viewer viewer){ super("Stock loading ..."); this.viewer = viewer; } @Override protected IStatus run(IProgressMonitor monitor){ monitor.beginTask("Stock loading ...", IProgressMonitor.UNKNOWN); loaded = StockServiceHolder.get().getAllStockEntries(); loaded.sort((l, r) -> { if (l.getArticle() != null && r.getArticle() != null) { return l.getArticle().getLabel().compareTo(r.getArticle().getLabel()); } return 0; }); if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } monitor.done(); Display.getDefault().asyncExec(new Runnable() { @Override public void run(){ viewer.setInput(loaded); } }); return Status.OK_STATUS; } } }
package org.treetank.access; import javax.xml.namespace.QName; import org.treetank.access.conf.SessionConfiguration; import org.treetank.api.IItem; import org.treetank.cache.ICache; import org.treetank.cache.NodePageContainer; import org.treetank.cache.TransactionLogCache; import org.treetank.exception.AbsTTException; import org.treetank.exception.TTIOException; import org.treetank.io.IWriter; import org.treetank.node.AbsNode; import org.treetank.node.AttributeNode; import org.treetank.node.DeletedNode; import org.treetank.node.ElementNode; import org.treetank.node.NamespaceNode; import org.treetank.node.TextNode; import org.treetank.page.AbsPage; import org.treetank.page.IndirectPage; import org.treetank.page.NamePage; import org.treetank.page.NodePage; import org.treetank.page.PageReference; import org.treetank.page.RevisionRootPage; import org.treetank.page.UberPage; import org.treetank.settings.EFixed; import org.treetank.settings.ERevisioning; import org.treetank.utils.IConstants; import org.treetank.utils.ItemList; import org.treetank.utils.NamePageHash; /** * <h1>WriteTransactionState</h1> * * <p> * See {@link ReadTransactionState}. * </p> */ public final class WriteTransactionState extends ReadTransactionState { /** Page writer to serialize. */ private final IWriter mPageWriter; /** Cache to store the changes in this writetransaction. */ private final ICache mLog; /** Last references to the Nodepage, needed for pre/postcondition check. */ private NodePageContainer mNodePageCon; /** Last reference to the actual revRoot. */ private final RevisionRootPage mNewRoot; /** ID for current transaction. */ private final long mTransactionID; /** * Standard constructor. * * * @param paramSessionConfiguration * {@link SessionConfiguration} reference * @param paramUberPage * root of revision * @param paramWriter * writer where this transaction should write to * @param paramParamId * parameter ID * @param paramRepresentRev * revision represent * @param paramStoreRev * revision store * @throws TTIOException * if IO Error */ protected WriteTransactionState(final Session paramSessionState, final UberPage paramUberPage, final IWriter paramWriter, final long paramParamId, final long paramRepresentRev, final long paramStoreRev) throws TTIOException { super(paramSessionState, paramUberPage, paramRepresentRev, new ItemList(), paramWriter); mNewRoot = preparePreviousRevisionRootPage(paramRepresentRev, paramStoreRev); mLog = new TransactionLogCache(paramSessionState.mResourceConfig.mPath, paramStoreRev); mPageWriter = paramWriter; mTransactionID = paramParamId; } /** * Prepare a node for modification. This is getting the node from the * (persistence) layer, storing the page in the cache and setting up the * node for upcoming modification. Note that this only occurs for {@link AbsNode}s. * * @param paramNodeKey * key of the node to be modified * @return an {@link AbsNode} instance * @throws TTIOException * if IO Error */ protected AbsNode prepareNodeForModification(final long paramNodeKey) throws TTIOException { if (paramNodeKey < 0) { throw new IllegalArgumentException("paramNodeKey must be >= 0!"); } if (mNodePageCon != null) { throw new IllegalStateException( "Another node page container is currently in the cache for updates!"); } final long nodePageKey = nodePageKey(paramNodeKey); final int nodePageOffset = nodePageOffset(paramNodeKey); prepareNodePage(nodePageKey); AbsNode node = mNodePageCon.getModified().getNode(nodePageOffset); if (node == null) { final AbsNode oldNode = mNodePageCon.getComplete().getNode(nodePageOffset); if (oldNode == null) { throw new TTIOException("Cannot retrieve node from cache"); } node = oldNode.clone(); mNodePageCon.getModified().setNode(nodePageOffset, node); } return node; } /** * Finishing the node modification. That is storing the node including the * page in the cache. * * @param paramNode * the node to be modified */ protected void finishNodeModification(final IItem paramNode) { final long nodePageKey = nodePageKey(paramNode.getNodeKey()); if (mNodePageCon == null || paramNode == null || mLog.get(nodePageKey) == null) { throw new IllegalStateException(); } mLog.put(nodePageKey, mNodePageCon); this.mNodePageCon = null; } /** * Create fresh node and prepare node nodePageReference for modifications * (COW). * * @param paramNode * node to add * @return Unmodified node from parameter for convenience. * @throws TTIOException * if IO Error */ protected AbsNode createNode(final AbsNode paramNode) throws TTIOException { // Allocate node key and increment node count. mNewRoot.incrementMaxNodeKey(); // Prepare node nodePageReference (COW). final long nodeKey = mNewRoot.getMaxNodeKey(); final long nodePageKey = nodePageKey(nodeKey); final int nodePageOffset = nodePageOffset(nodeKey); prepareNodePage(nodePageKey); final NodePage page = mNodePageCon.getModified(); page.setNode(nodePageOffset, paramNode); finishNodeModification(paramNode); return paramNode; } protected ElementNode createElementNode(final long parentKey, final long mLeftSibKey, final long rightSibKey, final long hash, final QName mName) throws TTIOException { final int nameKey = createNameKey(buildName(mName)); final int namespaceKey = createNameKey(mName.getNamespaceURI()); final int typeKey = createNameKey("xs:untyped"); return (ElementNode)createNode(ElementNode.createData(mNewRoot.getMaxNodeKey() + 1, parentKey, mLeftSibKey, rightSibKey, (Long)EFixed.NULL_NODE_KEY.getStandardProperty(), 0, nameKey, namespaceKey, typeKey, hash)); } protected TextNode createTextNode(final long mParentKey, final long mLeftSibKey, final long rightSibKey, final byte[] mValue) throws TTIOException { final int typeKey = createNameKey("xs:untyped"); return (TextNode)createNode(TextNode.createData(mNewRoot.getMaxNodeKey() + 1, mParentKey, mLeftSibKey, rightSibKey, typeKey, mValue)); } protected AttributeNode createAttributeNode(final long parentKey, final QName mName, final byte[] mValue) throws TTIOException { final int nameKey = createNameKey(buildName(mName)); final int namespaceKey = createNameKey(mName.getNamespaceURI()); final int typeKey = createNameKey("xs:untypedAtomic"); return (AttributeNode)createNode(AttributeNode.createData(mNewRoot.getMaxNodeKey() + 1, parentKey, nameKey, namespaceKey, typeKey, mValue)); } protected NamespaceNode createNamespaceNode(final long parentKey, final int mUriKey, final int prefixKey) throws TTIOException { return (NamespaceNode)createNode(NamespaceNode.createData(mNewRoot.getMaxNodeKey() + 1, parentKey, mUriKey, prefixKey)); } /** * Removing a node from the storage. * * @param paramNode * {@link AbsNode} to be removed * @throws TTIOException * if the removal fails */ protected void removeNode(final AbsNode paramNode) throws TTIOException { assert paramNode != null; final long nodePageKey = nodePageKey(paramNode.getNodeKey()); prepareNodePage(nodePageKey); final AbsNode delNode = DeletedNode.createData(paramNode.getNodeKey(), paramNode.getParentKey()); mNodePageCon.getModified().setNode(nodePageOffset(paramNode.getNodeKey()), delNode); mNodePageCon.getComplete().setNode(nodePageOffset(paramNode.getNodeKey()), delNode); finishNodeModification(paramNode); } /** * {@inheritDoc} */ @Override protected IItem getNode(final long mNodeKey) throws TTIOException { // Calculate page and node part for given nodeKey. final long nodePageKey = nodePageKey(mNodeKey); final int nodePageOffset = nodePageOffset(mNodeKey); final NodePageContainer pageCont = mLog.get(nodePageKey); if (pageCont == null) { return super.getNode(mNodeKey); } else if (pageCont.getModified().getNode(nodePageOffset) == null) { final IItem item = pageCont.getComplete().getNode(nodePageOffset); return checkItemIfDeleted(item); } else { final IItem item = pageCont.getModified().getNode(nodePageOffset); return checkItemIfDeleted(item); } } /** * Getting the name corresponding to the given key. * * @param mNameKey * for the term searched * @return the name */ @Override protected String getName(final int mNameKey) { final NamePage currentNamePage = (NamePage)mNewRoot.getNamePageReference().getPage(); String returnVal; // if currentNamePage == null -> state was commited and no // prepareNodepage was invoked yet if (currentNamePage == null || currentNamePage.getName(mNameKey) == null) { returnVal = super.getName(mNameKey); } else { returnVal = currentNamePage.getName(mNameKey); } return returnVal; } /** * Creating a namekey for a given name. * * @param mName * for which the key should be created. * @return an int, representing the namekey * @throws TTIOException * if something odd happens while storing the new key */ protected int createNameKey(final String mName) throws TTIOException { final String string = (mName == null ? "" : mName); final int nameKey = NamePageHash.generateHashForString(string); final NamePage namePage = (NamePage)mNewRoot.getNamePageReference().getPage(); if (namePage.getName(nameKey) == null) { namePage.setName(nameKey, string); } return nameKey; } /** * Committing a a writetransaction. This method is recursivly invoked by all {@link PageReference}s. * * @param reference * to be commited * @throws AbsTTException * if the write fails */ public void commit(final PageReference reference) throws AbsTTException { AbsPage page = null; // if reference is not null, get one from the persistent storage. if (reference != null) { // first, try to get one from the log final NodePageContainer cont = mLog.get(reference.getNodePageKey()); if (cont != null) { page = cont.getModified(); } // if none is in the log, test if one is instantiated, if so, get the one flexible from the // reference if (page == null) { if (!reference.isInstantiated()) { return; } else { page = reference.getPage(); } } reference.setPage(page); // Recursively commit indirectely referenced pages and then // write self. page.commit(this); mPageWriter.write(reference); reference.setPage(null); // afterwards synchronize all logs since the changes must to be written to the transaction log as // well if (cont != null) { mSession.syncLogs(cont, mTransactionID); } } } protected UberPage commit() throws AbsTTException { mSession.mCommitLock.lock(); final PageReference uberPageReference = new PageReference(); final UberPage uberPage = getUberPage(); uberPageReference.setPage(uberPage); // // // New code starts here // final Stack<PageReference> refs = new Stack<PageReference>(); // refs.push(uberPageReference); // final Stack<Integer> refIndex = new Stack<Integer>(); // refIndex.push(0); // refIndex.push(0); // assert refs.size() + 1 == refIndex.size(); // // Getting the next ref // final PageReference currentRef = refs.peek(); // final int currentIndex = refIndex.pop(); // // Check if referenced page is valid, if not, continue // AbsPage page = mLog.get(currentRef.getNodePageKey()).getModified(); // boolean continueFlag = true; // if (page == null) { // if (currentRef.isInstantiated()) { // page = currentRef.getPage(); // } else { // continueFlag = false; // } else { // currentRef.setPage(page); // if (continueFlag) { // if (currentIndex + 1 <= page.getReferences().length) { // // go down // refIndex.push(currentIndex + 1); // refs.push(page.getReference(currentIndex)); // refIndex.push(0); // } else { // mPageWriter.write(currentRef); // refs.pop(); // } // ref is not designated to be serialized // else { // refs.pop(); // } while (!refs.empty()); // // // New code ends here // Recursively write indirectely referenced pages. uberPage.commit(this); uberPageReference.setPage(uberPage); mPageWriter.writeFirstReference(uberPageReference); uberPageReference.setPage(null); mSession.waitForFinishedSync(mTransactionID); // mPageWriter.close(); mSession.mCommitLock.unlock(); return uberPage; } /** * {@inheritDoc} * * @throws TTIOException * if something weird happened in the storage */ @Override protected void close() throws TTIOException { // super.close(); mLog.clear(); mPageWriter.close(); } protected IndirectPage prepareIndirectPage(final PageReference paramReference) throws TTIOException { IndirectPage page = (IndirectPage)paramReference.getPage(); if (!paramReference.isInstantiated()) { if (paramReference.isCommitted()) { page = new IndirectPage((IndirectPage)dereferenceIndirectPage(paramReference), mNewRoot .getRevision() + 1); } else { page = new IndirectPage(getUberPage().getRevision()); } paramReference.setPage(page); } else { page = (IndirectPage)paramReference.getPage(); } return page; } protected NodePageContainer prepareNodePage(final long paramNodePageKey) throws TTIOException { // Last level points to node nodePageReference. NodePageContainer cont = mLog.get(paramNodePageKey); if (cont == null) { // Indirect reference. final PageReference reference = prepareLeafOfTree(mNewRoot.getIndirectPageReference(), paramNodePageKey); if (!reference.isInstantiated()) { if (reference.isCommitted()) { cont = dereferenceNodePageForModification(paramNodePageKey); } else { cont = new NodePageContainer(new NodePage(paramNodePageKey, IConstants.UBP_ROOT_REVISION_NUMBER)); } } else { // TODO Nodepage is just used as bootstrap-begin. Perhaps this // can be done otherwise final NodePage page = (NodePage)reference.getPage(); cont = new NodePageContainer(page); reference.setPage(null); } reference.setNodePageKey(paramNodePageKey); mLog.put(paramNodePageKey, cont); } mNodePageCon = cont; return cont; } private RevisionRootPage preparePreviousRevisionRootPage(final long mBaseRevision, final long representRevision) throws TTIOException { if (getUberPage().isBootstrap()) { return super.loadRevRoot(mBaseRevision); } else { // Prepare revision root nodePageReference. final RevisionRootPage revisionRootPage = new RevisionRootPage(super.loadRevRoot(mBaseRevision), representRevision + 1); // Prepare indirect tree to hold reference to prepared revision root // nodePageReference. final PageReference revisionRootPageReference = prepareLeafOfTree(getUberPage().getIndirectPageReference(), getUberPage().getRevisionNumber()); // Link the prepared revision root nodePageReference with the // prepared indirect tree. revisionRootPageReference.setPage(revisionRootPage); revisionRootPage.getNamePageReference().setPage( (NamePage)super.getActualRevisionRootPage().getNamePageReference().getPage()); // Return prepared revision root nodePageReference. return revisionRootPage; } } protected PageReference prepareLeafOfTree(final PageReference mStartReference, final long mKey) throws TTIOException { // Initial state pointing to the indirect nodePageReference of level 0. PageReference reference = mStartReference; int offset = 0; long levelKey = mKey; // Iterate through all levels. for (int level = 0, height = IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length; level < height; level++) { offset = (int)(levelKey >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[level]); levelKey -= offset << IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[level]; final IndirectPage page = prepareIndirectPage(reference); reference = page.getReference(offset); } // Return reference to leaf of indirect tree. return reference; } /** * Dereference node page reference. * * @param paramNodePageKey * key of node page * @return dereferenced page * @throws TTIOException * if something happened in the node */ private NodePageContainer dereferenceNodePageForModification(final long paramNodePageKey) throws TTIOException { final NodePage[] revs = getSnapshotPages(paramNodePageKey); final ERevisioning revision = mSession.mResourceConfig.mRevision; final int mileStoneRevision = mSession.mResourceConfig.mRevisionsToRestore; return revision.combinePagesForModification(revs, mileStoneRevision); } /** * Current reference to actual rev-root page. * * @return the current revision root page */ @Override protected RevisionRootPage getActualRevisionRootPage() { return mNewRoot; } /** * Updating a container in this transaction state. * * @param mCont * to be updated */ protected void updateDateContainer(final NodePageContainer mCont) { synchronized (mLog) { // TODO implement for MultiWriteTrans // Refer to issue #203 } } /** * Building name consisting out of prefix and name. NamespaceUri is not used * over here. * * @param paramQname * the {@link QName} of an element * @return a string with [prefix:]localname */ public static String buildName(final QName paramQname) { if (paramQname == null) { throw new NullPointerException("mQName must not be null!"); } String name; if (paramQname.getPrefix().isEmpty()) { name = paramQname.getLocalPart(); } else { name = new StringBuilder(paramQname.getPrefix()).append(":").append(paramQname.getLocalPart()) .toString(); } return name; } }
package se.kth.infosys.smx.ladok3; import java.io.IOException; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.impl.ScheduledPollConsumer; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import com.rometools.rome.feed.synd.SyndContent; import com.rometools.rome.feed.synd.SyndEntry; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.feed.synd.SyndLink; import com.rometools.rome.io.FeedException; import com.rometools.rome.io.SyndFeedInput; import com.rometools.rome.io.XmlReader; import se.kth.infosys.smx.ladok3.internal.Ladok3Message; import se.ladok.schemas.events.BaseEvent; /** * The ladok3 consumer. */ public class Ladok3Consumer extends ScheduledPollConsumer { private static final String SCHEMAS_BASE_PACKAGE = "se.ladok.schemas"; private static final String SCHEMA_BASE_URL = "http://schemas.ladok.se/"; private static final String FIRST_FEED_FORMAT = "https://%s/handelser/feed/first"; private static final String LAST_FEED_FORMAT = "https://%s/handelser/feed/recent"; private final Ladok3Endpoint endpoint; private final Unmarshaller unmarshaller; private final DocumentBuilder builder; public Ladok3Consumer(Ladok3Endpoint endpoint, Processor processor) throws Exception { super(endpoint, processor); this.endpoint = endpoint; DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); builder = builderFactory.newDocumentBuilder(); unmarshaller = JAXBContext.newInstance(SCHEMAS_BASE_PACKAGE).createUnmarshaller(); } @Override protected int poll() throws Exception { int messageCount = 0; Ladok3Feed feed; if ("".equals(endpoint.getLastFeed())) { feed = getLastUnreadFeed(); endpoint.setLastFeedURL(feed.getURL()); } else { feed = new Ladok3Feed(endpoint.getLastFeedURL()); } for (SyndEntry entry : feed.unreadEntries()) { final SyndContent content = entry.getContents().get(0); if ("application/vnd.ladok+xml".equals(content.getType())) { final Document document = builder.parse(new InputSource(new StringReader(content.getValue()))); final Node rootElement = document.getFirstChild(); final JAXBElement<?> root = unmarshaller.unmarshal(rootElement, Class.forName(ladokEventClass(rootElement))); final BaseEvent event = (BaseEvent) root.getValue(); doExchangeForEvent(event, entry.getUri(), feed); messageCount++; } endpoint.setLastEntry(entry.getUri()); } if (messageCount > 0) { log.info("Consumed Ladok ATOM feed {} up to id {}", feed.getURL(), endpoint.getLastEntry()); } if (feed.isLast()) { endpoint.setLastFeedURL(feed.getURL()); } else { endpoint.setLastFeedURL(feed.getLink("next-archive")); } return messageCount; } /* * Derive ladok3 event class name from namespace the same way xcj does, * but hard coded for ladok3 use case. */ private String ladokEventClass(final Node rootElement) { final String eventClass = SCHEMAS_BASE_PACKAGE + "." + rootElement.getNamespaceURI().substring(SCHEMA_BASE_URL.length()).replace("/", ".") + "." + rootElement.getLocalName(); return eventClass; } /* * Generate exchange for Ladok event and dispatch to next processor. */ private void doExchangeForEvent(BaseEvent event, String entryId, Ladok3Feed feed) throws Exception { final Exchange exchange = endpoint.createExchange(); log.debug("Creating message for event: {} {}", event.getHandelseUID(), event.getClass().getName()); final Message message = exchange.getIn(); message.setHeader(Ladok3Message.Header.EntryId, entryId); message.setHeader(Ladok3Message.Header.Feed, feed.getURL().toString()); message.setHeader(Ladok3Message.Header.EventType, event.getClass().getName()); message.setHeader(Ladok3Message.Header.EventId, event.getHandelseUID()); message.setBody(event); try { getProcessor().process(exchange); } finally { if (exchange.getException() != null) { getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException()); } } } /* * Get the latest feed not yet completed. */ private Ladok3Feed getLastUnreadFeed() throws IOException, FeedException { if ("".equals(endpoint.getLastEntry())) { return new Ladok3Feed(new URL(String.format(FIRST_FEED_FORMAT, endpoint.getHost()))); } Ladok3Feed feed = new Ladok3Feed(new URL(String.format(LAST_FEED_FORMAT, endpoint.getHost()))); for (;;) { if (feed.containsEntry(endpoint.getLastEntry())) { return feed; } URL prevArchive = feed.getLink("prev-archive"); if (prevArchive == null) { throw new FeedException("At end of the archive without finding Ladok3 event ID: '" + endpoint.getLastEntry() + "'"); } feed = new Ladok3Feed(prevArchive); } } /* * Inner class to wrap the SyndFeed with it's corresponding URL and convenvience methods. */ private final class Ladok3Feed { private final SyndFeed feed; private final URL url; /* * Create the feed from the URL. */ public Ladok3Feed(final URL url) throws IOException, IllegalArgumentException, FeedException { this.url = url; log.debug("fetching feed: {}", url); final XmlReader reader = new XmlReader(endpoint.get(url)); final SyndFeedInput input = new SyndFeedInput(); feed = input.build(reader); } /* * Return true if the feed contains an entry with given ID. */ public boolean containsEntry(String entryId) { for (final SyndEntry entry : feed.getEntries()) { if (entry.getUri().equals(entryId)) { return true; } } return false; } /* * True if feed is currently the last available. */ private boolean isLast() throws MalformedURLException { return getLink("next-archive") == null; } /* * Return the URL for this feed. */ public URL getURL() { return url; } /* * Get the link with specified rel label "next-archive", "prev-archive", etc, * or null if the link does not exist. */ public URL getLink(String rel) throws MalformedURLException { for (SyndLink link : feed.getLinks()) { if (link.getRel().equals(rel)) { return new URL(link.getHref()); } } return null; } /* * Get unread entries in feed in oldest to latest order. */ private List<SyndEntry> unreadEntries() { final List<SyndEntry> entries = feed.getEntries(); final List<SyndEntry> unmatchedEntries = new ArrayList<SyndEntry>(entries.size()); Collections.reverse(entries); while (! entries.isEmpty()) { final SyndEntry entry = entries.remove(0); if (entry.getUri().equals(endpoint.getLastEntry())) { return entries; } unmatchedEntries.add(entry); } return unmatchedEntries; } } }
package com.dianping.cat.report.page.problem; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.dianping.cat.consumer.problem.model.entity.Duration; import com.dianping.cat.consumer.problem.model.entity.Entry; import com.dianping.cat.consumer.problem.model.entity.JavaThread; import com.dianping.cat.consumer.problem.model.entity.Machine; import com.dianping.cat.consumer.problem.model.entity.ProblemReport; import com.dianping.cat.consumer.problem.model.entity.Segment; import com.dianping.cat.consumer.problem.model.transform.BaseVisitor; import com.dianping.cat.helper.MapUtils; public class ProblemStatistics extends BaseVisitor { private boolean m_allIp = false; private String m_ip = ""; private List<String> m_ips; private int m_sqlThreshold = 100; private Map<String, TypeStatistics> m_status = new TreeMap<String, TypeStatistics>(); private int m_urlThreshold = 1000; private List<Duration> getDurationsByType(String type, Entry entry) { List<Duration> durations = new ArrayList<Duration>(); if ("long-url".equals(type)) { for (java.util.Map.Entry<Integer, Duration> temp : entry.getDurations().entrySet()) { if (temp.getKey() >= m_urlThreshold) { durations.add(temp.getValue()); } } } else if ("long-sql".equals(type)) { for (java.util.Map.Entry<Integer, Duration> temp : entry.getDurations().entrySet()) { if (temp.getKey() >= m_sqlThreshold) { durations.add(temp.getValue()); } } } else { durations.add(entry.getDurations().get(0)); } return durations; } public List<String> getIps() { return m_ips; } public Map<String, TypeStatistics> getStatus() { return m_status; } public ProblemStatistics setAllIp(boolean allIp) { m_allIp = allIp; return this; } public ProblemStatistics setIp(String ip) { m_ip = ip; return this; } public void setIps(List<String> ips) { m_ips = ips; } public ProblemStatistics setSqlThreshold(int sqlThreshold) { m_sqlThreshold = sqlThreshold; return this; } public ProblemStatistics setUrlThreshold(int urlThreshold) { m_urlThreshold = urlThreshold; return this; } private void statisticsDuration(Entry entry) { String type = entry.getType(); String status = entry.getStatus(); List<Duration> durations = getDurationsByType(type, entry); for (Duration duration : durations) { TypeStatistics statusValue = m_status.get(type); if (statusValue == null) { statusValue = new TypeStatistics(type); m_status.put(type, statusValue); } statusValue.statics(status, duration); } } @Override public void visitDuration(Duration duration) { super.visitDuration(duration); } @Override public void visitEntry(Entry entry) { super.visitEntry(entry); } @Override public void visitMachine(Machine machine) { if (m_allIp == true || m_ip.equals(machine.getIp())) { List<Entry> entries = machine.getEntries(); for (Entry entry : entries) { statisticsDuration(entry); } } super.visitMachine(machine); } @Override public void visitProblemReport(ProblemReport problemReport) { super.visitProblemReport(problemReport); } @Override public void visitSegment(Segment segment) { super.visitSegment(segment); } @Override public void visitThread(JavaThread thread) { super.visitThread(thread); } public static class StatusStatistics { private int m_count; private List<String> m_links = new ArrayList<String>(); private String m_status; private StatusStatistics(String status) { m_status = status; } public void addLinks(String link) { m_links.add(link); } public int getCount() { return m_count; } public List<String> getLinks() { return m_links; } public String getStatus() { return m_status; } public StatusStatistics setCount(int count) { m_count = count; return this; } public StatusStatistics setLinks(List<String> links) { m_links = links; return this; } public StatusStatistics setStatus(String status) { m_status = status; return this; } public void statics(Duration duration) { m_count += duration.getCount(); if (m_links.size() < 60) { m_links.addAll(duration.getMessages()); if (m_links.size() > 60) { m_links = m_links.subList(0, 60); } } } } public static class TypeStatistics { private int m_count; private Map<String, StatusStatistics> m_status = new LinkedHashMap<String, StatusStatistics>(); private String m_type; public TypeStatistics(String type) { m_type = type; } public int getCount() { return m_count; } public Map<String, StatusStatistics> getStatus() { Map<String, StatusStatistics> result = MapUtils.sortMap(m_status, new Comparator<java.util.Map.Entry<String, StatusStatistics>>() { @Override public int compare(java.util.Map.Entry<String, StatusStatistics> o1, java.util.Map.Entry<String, StatusStatistics> o2) { return o2.getValue().getCount() - o1.getValue().getCount(); } }); return result; } public String getType() { return m_type; } public TypeStatistics setCount(int count) { m_count = count; return this; } public void setStatus(Map<String, StatusStatistics> status) { m_status = status; } public TypeStatistics setType(String type) { m_type = type; return this; } public void statics(String status, Duration duration) { if (duration != null) { m_count += duration.getCount(); StatusStatistics value = m_status.get(status); if (value == null) { value = new StatusStatistics(status); m_status.put(status, value); } value.statics(duration); } } } }
package gr.ntua.cslab.celar.server.daemon.rest; import gr.ntua.cslab.celar.server.daemon.rest.beans.SlipStreamCredentials; import gr.ntua.cslab.celar.server.daemon.rest.beans.user.AuthenticationRequest; import gr.ntua.cslab.celar.server.daemon.rest.beans.user.AuthenticationResponse; import gr.ntua.cslab.celar.server.daemon.shared.ServerStaticComponents; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import org.eclipse.jetty.server.Response; /** * * @author Giannis Giannakopoulos */ @Path("/user/") public class User { @POST @Path("authenticate/") public AuthenticationResponse authenticateUser(AuthenticationRequest request) { return new AuthenticationResponse("Logged in", "OK", true); } @GET @Path("credentials/") public SlipStreamCredentials getSlipStreamCredentials(@QueryParam("user") String username) { String user =ServerStaticComponents.properties.getProperty("slipstream.username"), pass =ServerStaticComponents.properties.getProperty("slipstream.password"); if(user!=null && username.equals(user)) return new SlipStreamCredentials(user, pass); else throw new WebApplicationException(Response.SC_FORBIDDEN); } }
package org.opencb.cellbase.client.rest; import org.opencb.biodata.models.core.RegulatoryFeature; import org.opencb.biodata.models.core.Xref; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.avro.VariantAnnotation; import org.opencb.cellbase.client.config.ClientConfiguration; import org.opencb.commons.datastore.core.Query; import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.commons.datastore.core.QueryResponse; import java.io.IOException; import java.util.List; import java.util.concurrent.*; public class VariationClient extends FeatureClient<Variant> { public VariationClient(ClientConfiguration configuration) { super(configuration); this.clazz = Variant.class; this.category = "feature"; this.subcategory = "variation"; } public QueryResponse<String> getAllConsequenceTypes(Query query) throws IOException { return execute("consequence_types", query, new QueryOptions(), String.class); } public QueryResponse<String> getConsequenceTypeById(String id, QueryOptions options) throws IOException { return execute(id, "consequence_type", options, String.class); } // check data model returned public QueryResponse<RegulatoryFeature> getRegulatory(String id, QueryOptions options) throws IOException { return execute(id, "regulatory", options, RegulatoryFeature.class); } public QueryResponse<String> getPhenotype(String id, QueryOptions options) throws IOException { return execute(id, "phenotype", options, String.class); } public QueryResponse<String> getSequence(String id, QueryOptions options) throws IOException { return execute(id, "sequence", options, String.class); } public QueryResponse<String> getPopulationFrequency(String id, QueryOptions options) throws IOException { return execute(id, "population_frequency", options, String.class); } public QueryResponse<Xref> getXref(String id, QueryOptions options) throws IOException { return execute(id, "xref", options, Xref.class); } public QueryResponse<VariantAnnotation> getAnnotations(String id, QueryOptions options) throws IOException { this.category = "genomic"; this.subcategory = "variant"; return execute(id, "annotation", options, VariantAnnotation.class); } public QueryResponse<VariantAnnotation> getAnnotations(List<String> ids, QueryOptions options) throws IOException { this.category = "genomic"; this.subcategory = "variant"; Future<QueryResponse<VariantAnnotation>> future = null; ExecutorService executorService = Executors.newFixedThreadPool(4); for (int i = 0; i < 4; i++) { future = executorService.submit(new AnnotatorRunnable(ids, options)); } QueryResponse<VariantAnnotation> response = null; try { response = future.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } executorService.shutdown(); return response; } class AnnotatorRunnable implements Callable<QueryResponse<VariantAnnotation>> { private List<String> ids; private QueryOptions options; public AnnotatorRunnable(List<String> ids, QueryOptions options) { this.ids = ids; this.options = options; } @Override public QueryResponse<VariantAnnotation> call() throws Exception { QueryResponse<VariantAnnotation> annotation = execute(ids, "annotation", options, VariantAnnotation.class); return annotation; } } }
package org.opendaylight.yangtools.yang.model.util; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.ChoiceNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.ModuleImport; import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaNode; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Schema Context Util contains support methods for searching through Schema * Context modules for specified schema nodes via Schema Path or Revision Aware * XPath. The Schema Context Util is designed as mixin, so it is not * instantiable. * */ public final class SchemaContextUtil { private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class); private static final Splitter COLON_SPLITTER = Splitter.on(':'); private static final Splitter SLASH_SPLITTER = Splitter.on('/'); private SchemaContextUtil() { } public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) { Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL"); Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL"); final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot(); if (prefixedPath == null) { LOG.debug("Schema path {} has null path", schemaPath); return null; } LOG.trace("Looking for path {} in context {}", schemaPath, context); return findNodeInSchemaContext(context, prefixedPath); } public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module, final RevisionAwareXPath nonCondXPath) { Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL"); Preconditions.checkArgument(module != null, "Module reference cannot be NULL"); Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL"); String strXPath = nonCondXPath.toString(); if (strXPath != null) { Preconditions.checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition"); if (nonCondXPath.isAbsolute()) { List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath); if (qnamedPath != null) { return findNodeInSchemaContext(context, qnamedPath); } } } return null; } public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module, final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) { Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL"); Preconditions.checkArgument(module != null, "Module reference cannot be NULL"); Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL"); Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL"); Preconditions.checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, " + "for non relative Revision Aware XPath use findDataSchemaNode method"); SchemaPath actualNodePath = actualSchemaNode.getPath(); if (actualNodePath != null) { Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode); if (qnamePath != null) { return findNodeInSchemaContext(context, qnamePath); } } return null; } public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) { Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!"); Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!"); Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not " + "set properly (Schema Path is NULL)"); final QName qname = Iterables.getFirst(schemaNode.getPath().getPathTowardsRoot(), null); Preconditions.checkState(qname != null, "Schema Path contains invalid state of path parts. " + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path."); return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision()); } public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) { final QName current = path.iterator().next(); LOG.trace("Looking up module {} in context {}", current, path); final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision()); if (module == null) { LOG.debug("Module {} not found", current); return null; } return findNodeInModule(module, path); } private static SchemaNode findNodeInModule(Module module, Iterable<QName> path) { Preconditions.checkArgument(module != null, "Parent reference cannot be NULL"); Preconditions.checkArgument(path != null, "Path reference cannot be NULL"); if (!path.iterator().hasNext()) { LOG.debug("No node matching {} found in node {}", path, module); return null; } QName current = path.iterator().next(); LOG.trace("Looking for node {} in module {}", current, module); SchemaNode foundNode = null; Iterable<QName> nextPath = nextLevel(path); foundNode = module.getDataChildByName(current); if (foundNode != null && nextPath.iterator().hasNext()) { foundNode = findNodeIn(foundNode, nextPath); } if (foundNode == null) { foundNode = getGroupingByName(module, current); if (foundNode != null && nextPath.iterator().hasNext()) { foundNode = findNodeIn(foundNode, nextPath); } } if (foundNode == null) { foundNode = getRpcByName(module, current); if (foundNode != null && nextPath.iterator().hasNext()) { foundNode = findNodeIn(foundNode, nextPath); } } if (foundNode == null) { foundNode = getNotificationByName(module, current); if (foundNode != null && nextPath.iterator().hasNext()) { foundNode = findNodeIn(foundNode, nextPath); } } if (foundNode == null) { LOG.debug("No node matching {} found in node {}", path, module); } return foundNode; } private static SchemaNode findNodeIn(SchemaNode parent, Iterable<QName> path) { Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL"); Preconditions.checkArgument(path != null, "Path reference cannot be NULL"); if (!path.iterator().hasNext()) { LOG.debug("No node matching {} found in node {}", path, parent); return null; } QName current = path.iterator().next(); LOG.trace("Looking for node {} in node {}", current, parent); SchemaNode foundNode = null; Iterable<QName> nextPath = nextLevel(path); if (parent instanceof DataNodeContainer) { DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent; foundNode = parentDataNodeContainer.getDataChildByName(current); if (foundNode != null && nextPath.iterator().hasNext()) { foundNode = findNodeIn(foundNode, nextPath); } if (foundNode == null) { foundNode = getGroupingByName(parentDataNodeContainer, current); if (foundNode != null && nextPath.iterator().hasNext()) { foundNode = findNodeIn(foundNode, nextPath); } } } if (foundNode == null && parent instanceof RpcDefinition) { RpcDefinition parentRpcDefinition = (RpcDefinition) parent; if (current.getLocalName().equals("input")) { foundNode = parentRpcDefinition.getInput(); if (foundNode != null && nextPath.iterator().hasNext()) { foundNode = findNodeIn(foundNode, nextPath); } } if (current.getLocalName().equals("output")) { foundNode = parentRpcDefinition.getOutput(); if (foundNode != null && nextPath.iterator().hasNext()) { foundNode = findNodeIn(foundNode, nextPath); } } if (foundNode == null) { foundNode = getGroupingByName(parentRpcDefinition, current); if (foundNode != null && nextPath.iterator().hasNext()) { foundNode = findNodeIn(foundNode, nextPath); } } } if (foundNode == null && parent instanceof ChoiceNode) { foundNode = ((ChoiceNode) parent).getCaseNodeByName(current); if (foundNode != null && nextPath.iterator().hasNext()) { foundNode = findNodeIn(foundNode, nextPath); } } if (foundNode == null) { LOG.debug("No node matching {} found in node {}", path, parent); } return foundNode; } private static Iterable<QName> nextLevel(final Iterable<QName> path) { return Iterables.skip(path, 1); } private static RpcDefinition getRpcByName(final Module module, final QName name) { for (RpcDefinition rpc : module.getRpcs()) { if (rpc.getQName().equals(name)) { return rpc; } } return null; } private static NotificationDefinition getNotificationByName(final Module module, final QName name) { for (NotificationDefinition notification : module.getNotifications()) { if (notification.getQName().equals(name)) { return notification; } } return null; } private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) { for (GroupingDefinition grouping : dataNodeContainer.getGroupings()) { if (grouping.getQName().equals(name)) { return grouping; } } return null; } private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) { for (GroupingDefinition grouping : rpc.getGroupings()) { if (grouping.getQName().equals(name)) { return grouping; } } return null; } private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) { Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL"); Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL"); Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL"); List<QName> path = new LinkedList<QName>(); for (String pathComponent : SLASH_SPLITTER.split(xpath)) { if (!pathComponent.isEmpty()) { path.add(stringPathPartToQName(context, parentModule, pathComponent)); } } return path; } private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) { Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL"); Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL"); Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!"); if (prefixedPathPart.indexOf(':') != -1) { final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator(); final String modulePrefix = prefixedName.next(); Module module = resolveModuleForPrefix(context, parentModule, modulePrefix); Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix, parentModule.getName()); return QName.create(module.getQNameModule(), prefixedName.next()); } else { return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart); } } private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) { Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL"); Preconditions.checkArgument(module != null, "Module reference cannot be NULL"); Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL"); if (prefix.equals(module.getPrefix())) { return module; } Set<ModuleImport> imports = module.getImports(); for (ModuleImport mi : imports) { if (prefix.equals(mi.getPrefix())) { return context.findModuleByName(mi.getModuleName(), mi.getRevision()); } } return null; } private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module, final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) { Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL"); Preconditions.checkArgument(module != null, "Module reference cannot be NULL"); Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL"); Preconditions.checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, " + "for non relative Revision Aware XPath use findDataSchemaNode method"); Preconditions.checkState(actualSchemaNode.getPath() != null, "Schema Path reference for Leafref cannot be NULL"); final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString()); // Find out how many "parent" components there are // FIXME: is .contains() the right check here? // FIXME: case ../../node1/node2/../node3/../node4 int colCount = 0; for (Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) { ++colCount; } final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot(); if (Iterables.size(schemaNodePath) - colCount >= 0) { return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount), Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() { @Override public QName apply(final String input) { return stringPathPartToQName(context, module, input); } })); } return Iterables.concat(schemaNodePath, Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() { @Override public QName apply(final String input) { return stringPathPartToQName(context, module, input); } })); } /** * Extracts the base type of node on which schema node points to. If target node is again of type LeafrefTypeDefinition, methods will be call recursively until it reach concrete * type definition. * * @param typeDefinition * type of node which will be extracted * @param schemaContext * Schema Context * @param schema * Schema Node * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null is there to preserve backwards compatibility) */ public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition, final SchemaContext schemaContext, final SchemaNode schema) { RevisionAwareXPath pathStatement = typeDefinition.getPathStatement(); pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute()); final Module parentModule = SchemaContextUtil.findParentModule(schemaContext, schema); final DataSchemaNode dataSchemaNode; if(pathStatement.isAbsolute()) { dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, pathStatement); } else { dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule, schema, pathStatement); } // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths // and current expected behaviour for such cases is to just use pure string // This should throw an exception about incorrect XPath in leafref if(dataSchemaNode == null) { return null; } final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode); if(targetTypeDefinition instanceof LeafrefTypeDefinition) { return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode); } else { return targetTypeDefinition; } } /** * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle case * when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other module as typedef * which is then imported to referenced module. * * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful. * * @param typeDefinition * @param schemaContext * @param qName * @return */ public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition, final SchemaContext schemaContext, final QName qName) { final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement(); final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute()); if (!strippedPathStatement.isAbsolute()) { return null; } final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace(),qName.getRevision()); final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, strippedPathStatement); final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode); if (targetTypeDefinition instanceof LeafrefTypeDefinition) { return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode); } else { return targetTypeDefinition; } } /** * Removes conditions from xPath pointed to target node. * * @param pathStatement * xPath to target node * @return string representation of xPath without conditions * */ private static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) { return pathStatement.toString().replaceAll("\\[.*\\]", ""); } /** * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition. * * @param node * a node representing LeafSchemaNode * @return concrete type definition of node value */ private static TypeDefinition<? extends Object> typeDefinition(final LeafSchemaNode node) { TypeDefinition<?> baseType = node.getType(); while (baseType.getBaseType() != null) { baseType = baseType.getBaseType(); } return baseType; } /** * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition. * * @param node * a node representing LeafListSchemaNode * @return concrete type definition of node value */ private static TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) { TypeDefinition<?> baseType = node.getType(); while (baseType.getBaseType() != null) { baseType = baseType.getBaseType(); } return baseType; } /** * Gets the base type of DataSchemaNode value. * * @param node * a node representing DataSchemaNode * @return concrete type definition of node value */ private static TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) { if (node instanceof LeafListSchemaNode) { return typeDefinition((LeafListSchemaNode) node); } else if (node instanceof LeafSchemaNode) { return typeDefinition((LeafSchemaNode) node); } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString()); } } }
package com.code4ge.json.service; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.type.TypeFactory; import org.codehaus.jackson.node.ArrayNode; import org.codehaus.jackson.node.ObjectNode; import org.codehaus.jackson.node.POJONode; /** * This class is responsible for building service mapping descriptor and * processes JSON-RPC request. * * @author Daniel Stefaniuk */ public class JsonServiceObject { private static ObjectMapper mapper = new ObjectMapper(); private boolean isInitialized = false; private final Class<?> clazz; private Object context; private Map<String, Method> methods = new HashMap<String, Method>();; private Transport transport = Transport.POST; private ContentType contentType = ContentType.APPLICATION_JSON; private Envelope envelope = Envelope.JSON_RPC_2_0; private Version version = Version.SMD_2_0; private ObjectNode smd; /** * Transport * * @author Daniel Stefaniuk */ public static enum Transport { UNDEFINED(""), POST("POST"); private final String name; Transport(String name) { this.name = name; } @Override public String toString() { return this.name; } } /** * Content type. * * @author Daniel Stefaniuk */ public static enum ContentType { UNDEFINED(""), APPLICATION_JSON("application/json"); private final String name; ContentType(String name) { this.name = name; } @Override public String toString() { return this.name; } } /** * Envelope * * @author Daniel Stefaniuk */ public static enum Envelope { UNDEFINED(""), JSON_RPC_2_0("JSON-RPC-2.0"); private final String name; Envelope(String name) { this.name = name; } @Override public String toString() { return this.name; } } /** * SMD version. * * @author Daniel Stefaniuk */ public static enum Version { UNDEFINED(""), SMD_2_0("2.0"); private final String name; Version(String name) { this.name = name; } @Override public String toString() { return this.name; } } /** * Data type * * @author Daniel Stefaniuk */ public static enum DataType { ARRAY(new Class<?>[] { ArrayList.class }), OBJECT(new Class<?>[] { LinkedHashMap.class }), NUMBER(new Class<?>[] { Float.class, Double.class }), INTEGER(new Class<?>[] { Integer.class, Long.class }), BOOLEAN(new Class<?>[] { Boolean.class }), STRING(new Class<?>[] { String.class }); private final Class<?>[] classes; private DataType(Class<?>[] classes) { this.classes = classes; } public static String getName(Class<?> clazz) { for(DataType type: DataType.values()) { for(Class<?> c: type.classes) { if(clazz.equals(c)) { return type.toString(); } } } // if non of the above this must be POJO return DataType.OBJECT.toString(); } @Override public String toString() { return name().toLowerCase(); } } /** * Constructor * * @param clazz */ public JsonServiceObject(Class<?> clazz) { this.clazz = clazz; } /** * Constructor * * @param obj */ public JsonServiceObject(Object obj) { this.clazz = obj.getClass(); this.context = obj; } /** * Sets transport. * * @param transport * @return */ public JsonServiceObject setTransport(Transport transport) { this.transport = transport; return this; } /** * Gets transport. * * @return */ public Transport getTransport() { return transport; } /** * Sets content type. * * @param contentType * @return */ public JsonServiceObject setContentType(ContentType contentType) { this.contentType = contentType; return this; } /** * Gets content type. * * @return */ public ContentType getContentType() { return contentType; } /** * Sets envelope. * * @param envelope * @return */ public JsonServiceObject setEnvelope(Envelope envelope) { this.envelope = envelope; return this; } /** * Gets envelope. * * @return */ public Envelope getEnvelope() { return envelope; } /** * Sets version. * * @param version * @return */ public JsonServiceObject setVersion(Version version) { this.version = version; return this; } /** * Gets version. * * @return */ public Version getVersion() { return version; } /** * Builds service mapping descriptor. */ private void init() { try { if(context == null) { // get context object Constructor<?> ctor = clazz.getConstructor(); context = ctor.newInstance(); } // get methods for(Method method: clazz.getMethods()) { if(isService(clazz, method)) { methods.put(method.getName(), method); } } // get service mapping description smd = mapper.createObjectNode(); smd.put("transport", transport.toString()); smd.put("contentType", contentType.toString()); smd.put("envelope", envelope.toString()); smd.put("SMDVersion", version.toString()); smd.put("additionalParameters", false); ObjectNode services = mapper.createObjectNode(); for(Method method: methods.values()) { ObjectNode temp = mapper.createObjectNode(); JsonService annotation = method.getAnnotation(JsonService.class); if(annotation == null) { annotation = clazz.getAnnotation(JsonService.class); } // transport Transport transport = annotation.transport(); if(transport != Transport.UNDEFINED && transport != this.transport) { temp.put("transport", transport.toString()); } // contentType ContentType contentType = annotation.contentType(); if(contentType != ContentType.UNDEFINED && contentType != this.contentType) { temp.put("contentType", contentType.toString()); } // envelope Envelope envelope = annotation.envelope(); if(envelope != Envelope.UNDEFINED && envelope != this.envelope) { temp.put("envelope", envelope.toString()); } // target String target = annotation.target(); if(!target.equals("")) { temp.put("target", target); } // description String description = annotation.description(); if(!description.equals("")) { temp.put("description", description); } // parameters ArrayNode parameters = mapper.createArrayNode(); for(Class<?> type: method.getParameterTypes()) { ObjectNode node = mapper.createObjectNode(); node.put("type", DataType.getName(type)); parameters.add(node); } temp.put("parameters", parameters); // returns Class<?> returnType = method.getReturnType(); if(!"void".equals(returnType.toString())) { ObjectNode node = mapper.createObjectNode(); node.put("type", DataType.getName(returnType)); temp.put("returns", node); } services.put(method.getName(), temp); } smd.put("services", services); } catch(Exception e) { e.printStackTrace(System.err); } } /** * Checks if a given method is defined as JSON-RPC method. * * @param clazz * @param method * @return */ private boolean isService(Class<?> clazz, Method method) { boolean hasAnnotation = clazz.getAnnotation(JsonService.class) != null || method.getAnnotation(JsonService.class) != null; return hasAnnotation && Modifier.isPublic(method.getModifiers()); } /** * Returns service mapping descriptor as JSON object. * * @return */ protected JsonNode getServiceMap() { if(!isInitialized) { init(); } return smd; } protected JsonNode process(HttpServletRequest request, String method, Object... args) throws IllegalAccessException, InvocationTargetException, JsonParseException, JsonMappingException, IOException { if(!isInitialized) { init(); } JsonNode response = null; try { // get method Method m = methods.get(method); if(m == null) { throw new JsonServiceException(JsonServiceError.METHOD_NOT_FOUND); } // get parameters ArrayList<Object> temp = new ArrayList<Object>(); Type[] types = m.getGenericParameterTypes(); int i = 0; for(Type type: types) { if(type.equals(HttpServletRequest.class)) { temp.add(request); } else { temp.add(args[i++]); } } Object[] arguments = new Object[temp.size()]; temp.toArray(arguments); // invoke method try { response = getJsonSuccessResponse(m.invoke(context, arguments)); } catch(IllegalArgumentException e) { throw new JsonServiceException(JsonServiceError.INVALID_PARAMS); } } catch(InvocationTargetException e) { Throwable t = e.getCause(); if(t instanceof JsonServiceException) { JsonServiceException jse = (JsonServiceException) t; response = getJsonErrorResponse(jse.getError()); } else { throw e; } } catch(JsonServiceException e) { response = getJsonErrorResponse(e.getError()); } return response; } protected JsonNode process(HttpServletRequest request, ObjectNode requestNode) throws IllegalAccessException, InvocationTargetException, JsonParseException, JsonMappingException, IOException { if(!isInitialized) { init(); } JsonNode response = null; try { if(!requestNode.has("method") || "".equals(requestNode.get("method"))) { throw new JsonServiceException(JsonServiceError.INVALID_REQUEST); } String name = requestNode.get("method").getTextValue(); // get method Method method = methods.get(name); if(method == null) { throw new JsonServiceException(JsonServiceError.METHOD_NOT_FOUND); } // get parameters ArrayNode params = ArrayNode.class.cast(requestNode.get("params")); ArrayList<Object> temp = new ArrayList<Object>(); Type[] types = method.getGenericParameterTypes(); int i = 0; for(Type type: types) { if(type.equals(HttpServletRequest.class)) { temp.add(request); } else { JsonNode node = params.get(i++); temp.add(mapper.treeToValue(node, TypeFactory.type(type).getRawClass())); } } Object[] args = new Object[temp.size()]; temp.toArray(args); // invoke method try { response = getJsonRpcSuccessResponse(requestNode.get("id").getIntValue(), method.invoke(context, args)); } catch(IllegalArgumentException e) { throw new JsonServiceException(JsonServiceError.INVALID_PARAMS); } } catch(InvocationTargetException e) { Throwable t = e.getCause(); if(t instanceof JsonServiceException) { JsonServiceException jse = (JsonServiceException) t; response = getJsonRpcErrorResponse(requestNode.get("id").getIntValue(), jse.getError()); } else { throw e; } } catch(JsonServiceException e) { response = getJsonRpcErrorResponse(requestNode.get("id").getIntValue(), e.getError()); } return response; } /** * Returns response. * * @param result * @return */ private JsonNode getJsonSuccessResponse(Object result) { // set result if(result instanceof Map<?, ?>) { return toJson((Map<?, ?>) result); } else { return new POJONode(result); } } /** * Returns error response. * * @param error * @return */ private JsonNode getJsonErrorResponse(JsonServiceError error) { ObjectNode errorNode = mapper.createObjectNode(); errorNode.put("code", error.getCode()); errorNode.put("message", error.getMessage()); ObjectNode responseNode = mapper.createObjectNode(); responseNode.put("error", errorNode); return responseNode; } /** * Returns success response. * * @param id * @param result * @return */ private JsonNode getJsonRpcSuccessResponse(Integer id, Object result) { ObjectNode responseNode = mapper.createObjectNode(); // set id if(id != null) { responseNode.put("id", id); } else { responseNode.putNull("id"); } // set result if(result instanceof List<?>) { responseNode.put("result", toJson((List<?>) result)); } else if(result instanceof Map<?, ?>) { responseNode.put("result", toJson((Map<?, ?>) result)); } else { try { responseNode.put("result", new POJONode(result)); } catch(Exception e) { responseNode.put("result", result != null ? result.toString() : null); } } responseNode.putNull("error"); responseNode.put("jsonrpc", envelope.toString()); return responseNode; } /** * Returns error response. * * @param id * @param error * @return */ private JsonNode getJsonRpcErrorResponse(Integer id, JsonServiceError error) { ObjectNode errorNode = mapper.createObjectNode(); errorNode.put("code", error.getCode()); errorNode.put("message", error.getMessage()); ObjectNode responseNode = mapper.createObjectNode(); if(id != null) { responseNode.put("id", id); } else { responseNode.putNull("id"); } responseNode.putNull("result"); responseNode.put("error", errorNode); responseNode.put("jsonrpc", envelope.toString()); return responseNode; } /** * Converts a list to JSON array. * * @param list * @return */ private ArrayNode toJson(List<?> list) { ArrayNode node = mapper.createArrayNode(); for(Object obj: list) { if(obj instanceof Number) { // most probable if(obj instanceof Integer) { node.add((Integer) obj); } else if(obj instanceof Double) { node.add((Double) obj); } // others else if(obj instanceof BigDecimal) { node.add((BigDecimal) obj); } else if(obj instanceof Float) { node.add((Float) obj); } else if(obj instanceof Long) { node.add((Long) obj); } else if(obj instanceof Short) { node.add((Short) obj); } else if(obj instanceof Byte) { node.add((Byte) obj); } } else if(obj instanceof Boolean) { node.add((Boolean) obj); } else if(obj instanceof String) { node.add((String) obj); } else if(obj instanceof List<?>) { node.add(toJson((List<?>) obj)); } else if(obj instanceof Map<?, ?>) { node.add(toJson((Map<?, ?>) obj)); } else { try { node.addPOJO(obj); } catch(Exception e) { node.add(obj != null ? obj.toString() : null); } } } return node; } /** * Converts a map to JSON object. * * @param map * @return */ private ObjectNode toJson(Map<?, ?> map) { ObjectNode node = mapper.createObjectNode(); for(Object key: map.keySet()) { String name = (String) key; Object obj = map.get(name); if(obj instanceof Number) { // most probable if(obj instanceof Integer) { node.put(name, (Integer) obj); } else if(obj instanceof Double) { node.put(name, (Double) obj); } // others else if(obj instanceof BigDecimal) { node.put(name, (BigDecimal) obj); } else if(obj instanceof Float) { node.put(name, (Float) obj); } else if(obj instanceof Long) { node.put(name, (Long) obj); } else if(obj instanceof Short) { node.put(name, (Short) obj); } else if(obj instanceof Byte) { node.put(name, (Byte) obj); } } else if(obj instanceof Boolean) { node.put(name, (Boolean) obj); } else if(obj instanceof String) { node.put(name, (String) obj); } else if(obj instanceof List<?>) { node.put(name, toJson((List<?>) obj)); } else if(obj instanceof Map<?, ?>) { node.put(name, toJson((Map<?, ?>) obj)); } else { try { node.putPOJO(name, obj); } catch(Exception e) { node.put(name, obj != null ? obj.toString() : null); } } } return node; } }
package edu.duke.cabig.c3pr.web; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import edu.duke.cabig.c3pr.domain.Identifier; import edu.duke.cabig.c3pr.domain.Participant; import edu.duke.cabig.c3pr.service.ParticipantService; /** * @author Ramakrishna * */ public class SearchParticipantController extends SimpleFormController{ private static Log log = LogFactory.getLog(SearchParticipantController.class); private ParticipantService participantService; public SearchParticipantController(){ setCommandClass(SearchParticipantCommand.class); this.setFormView("particpant_search"); this.setSuccessView("participant_search_results"); } protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object oCommand, BindException errors) throws Exception { SearchParticipantCommand searchParticipantCommand = (SearchParticipantCommand) oCommand; Participant participant = new Participant(); String text = searchParticipantCommand.getSearchText(); String type = searchParticipantCommand.getSearchType(); log.debug("search string = " +text+"; type = "+type); if ("N".equals(type)){ participant.setLastName(text); } if ("Identifier".equals(type)) { Identifier identifier = new Identifier(); identifier.setValue(text); //FIXME: participant.addIdentifier(identifier); } List<Participant> participants = participantService.search(participant); Iterator<Participant> participantIter = participants.iterator(); log.debug("Search results size " +participants.size()); Map map =errors.getModel(); map.put("participants", participants); map.put("searchType",getSearchType() ); ModelAndView modelAndView= new ModelAndView(getSuccessView(), map); return modelAndView; } protected Map<String, Object> referenceData(HttpServletRequest httpServletRequest) throws Exception { Map<String, Object> refdata = new HashMap<String, Object>(); refdata.put("searchType", getSearchType()); return refdata; } private List<LOV> getSearchType(){ List<LOV> col = new ArrayList<LOV>(); LOV lov1 = new LOV("N", "Last Name"); LOV lov2 = new LOV("Identifier", "Identifier"); col.add(lov1); col.add(lov2); return col; } public class LOV { private String code; private String desc; LOV(String code, String desc) { this.code=code; this.desc=desc; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDesc(){ return desc; } public void setDesc(String desc){ this.desc=desc; } } public ParticipantService getParticipantService() { return participantService; } public void setParticipantService(ParticipantService participantService) { this.participantService = participantService; } }
package at.fhjoanneum.ippr.processengine.feign; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import at.fhjoanneum.ippr.commons.dto.communicator.BusinessObject; import at.fhjoanneum.ippr.commons.dto.communicator.BusinessObjectField; import at.fhjoanneum.ippr.commons.dto.communicator.ExternalCommunicatorMessage; import at.fhjoanneum.ippr.persistence.entities.engine.businessobject.BusinessObjectInstanceBuilder; import at.fhjoanneum.ippr.persistence.entities.engine.businessobject.BusinessObjectInstanceImpl; import at.fhjoanneum.ippr.persistence.entities.engine.businessobject.field.BusinessObjectFieldInstanceBuilder; import at.fhjoanneum.ippr.persistence.entities.engine.businessobject.field.BusinessObjectFieldInstanceImpl; import at.fhjoanneum.ippr.persistence.entities.engine.state.SubjectStateImpl; import at.fhjoanneum.ippr.persistence.entities.engine.subject.SubjectImpl; import at.fhjoanneum.ippr.persistence.objects.engine.businessobject.BusinessObjectFieldInstance; import at.fhjoanneum.ippr.persistence.objects.engine.businessobject.BusinessObjectInstance; import at.fhjoanneum.ippr.persistence.objects.engine.process.ProcessInstance; import at.fhjoanneum.ippr.persistence.objects.engine.subject.Subject; import at.fhjoanneum.ippr.persistence.objects.model.businessobject.BusinessObjectModel; import at.fhjoanneum.ippr.persistence.objects.model.messageflow.MessageFlow; import at.fhjoanneum.ippr.processengine.repositories.BusinessObjectFieldInstanceRepository; import at.fhjoanneum.ippr.processengine.repositories.BusinessObjectInstanceRepository; import at.fhjoanneum.ippr.processengine.repositories.MessageFlowRepository; import at.fhjoanneum.ippr.processengine.repositories.ProcessInstanceRepository; import at.fhjoanneum.ippr.processengine.repositories.SubjectRepository; import at.fhjoanneum.ippr.processengine.repositories.SubjectStateRepository; @Service @Transactional(isolation = Isolation.READ_COMMITTED) public class ProcessEngineFeignServiceImpl implements ProcessEngineFeignService { private static final int MF_ID_INDEX = 2; private static final int S_ID_INDEX = 1; private static final int PI_ID_INDEX = 0; private final static Logger LOG = LoggerFactory.getLogger(ProcessEngineFeignServiceImpl.class); @Autowired private SubjectRepository subjectRepository; @Autowired private SubjectStateRepository subjectStateRepository; @Autowired private ProcessInstanceRepository processInstanceRepository; @Autowired private MessageFlowRepository messageFlowRepository; @Autowired private BusinessObjectInstanceRepository businessObjectInstanceRepository; @Autowired private BusinessObjectFieldInstanceRepository businessObjectFieldInstanceRepository; @Override public void markAsSent(final String transferId) { final String[] split = transferId.split("-"); final Long sId = Long.valueOf(split[S_ID_INDEX]); final Subject subject = subjectRepository.findOne(sId); subject.getSubjectState().setToSent(); LOG.info("Marked as 'SENT' [{}]", subject.getSubjectState()); subjectStateRepository.save((SubjectStateImpl) subject.getSubjectState()); } @Override public void storeExternalCommunicatorMessage(final ExternalCommunicatorMessage message) { final String[] split = message.getTransferId().split("-"); final Long piID = Long.valueOf(split[PI_ID_INDEX]); final Long mfId = Long.valueOf(split[MF_ID_INDEX]); final Long sId = Long.valueOf(split[S_ID_INDEX]); final ProcessInstance processInstance = processInstanceRepository.findOne(piID); final MessageFlow messageFlow = Optional.ofNullable(messageFlowRepository.findOne(mfId)) .orElseThrow(() -> new IllegalArgumentException( "Could not find message flow for MF_ID [" + mfId + "]")); final Set<BusinessObjectInstance> businessObjectInstances = getBusinessObjectInstances(processInstance, messageFlow.getBusinessObjectModels()); final Table<String, String, BusinessObjectField> records = convertToMap(message.getBusinessObjects()); businessObjectInstances.stream() .forEachOrdered(objectInstance -> storeValues(records, objectInstance)); final Subject subject = subjectRepository.findOne(sId); subject.getSubjectState().setToReceived(messageFlow); subjectRepository.save((SubjectImpl) subject); } private Set<BusinessObjectInstance> getBusinessObjectInstances( final ProcessInstance processInstance, final List<BusinessObjectModel> models) { final Set<BusinessObjectInstance> instances = new HashSet<>(); models.stream() .forEachOrdered(model -> getBusinessObjectInstance(processInstance, model, instances)); return instances; } private void getBusinessObjectInstance(final ProcessInstance processInstance, final BusinessObjectModel model, final Set<BusinessObjectInstance> instances) { if (processInstance.isBusinessObjectInstanceOfModelCreated(model)) { instances.add(businessObjectInstanceRepository .getBusinessObjectInstanceOfModelInProcess(processInstance.getPiId(), model.getBomId())); } else { final BusinessObjectInstance businessObjectInstance = new BusinessObjectInstanceBuilder() .processInstance(processInstance).businessObjectModel(model).build(); final List<BusinessObjectFieldInstanceImpl> fields = model.getBusinessObjectFieldModels().stream() .map(fieldModel -> new BusinessObjectFieldInstanceBuilder() .businessObjectInstance(businessObjectInstance) .businessObjectFieldModel(fieldModel).build()) .map(field -> (BusinessObjectFieldInstanceImpl) field).collect(Collectors.toList()); businessObjectInstanceRepository.save((BusinessObjectInstanceImpl) businessObjectInstance); businessObjectFieldInstanceRepository.save(fields); instances.add(businessObjectInstance); } model.getChildren().stream() .forEachOrdered((child) -> getBusinessObjectInstance(processInstance, child, instances)); } private Table<String, String, BusinessObjectField> convertToMap( final Set<BusinessObject> objects) { final Table<String, String, BusinessObjectField> records = HashBasedTable.create(); objects.stream().forEachOrdered(object -> { object.getFields().stream() .forEachOrdered(field -> records.put(object.getName(), field.getName(), field)); }); return records; } private void storeValues(final Table<String, String, BusinessObjectField> records, final BusinessObjectInstance objectInstance) { final Map<String, BusinessObjectField> column = records.column(objectInstance.getBusinessObjectModel().getName()); if (column != null) { objectInstance.getBusinessObjectFieldInstances().stream() .forEachOrdered(field -> storeValue(column, field)); } } private void storeValue(final Map<String, BusinessObjectField> column, final BusinessObjectFieldInstance field) { final BusinessObjectField ecField = column.get(field.getBusinessObjectFieldModel().getFieldName()); if (ecField != null) { field.setValue(ecField.getValue()); businessObjectFieldInstanceRepository.save((BusinessObjectFieldInstanceImpl) field); } } }
package gov.hhs.fha.nhinc.direct; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.util.StreamUtils; import gov.hhs.fha.nhinc.nhinclib.NullChecker; import ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.Session; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.util.ByteArrayDataSource; import gov.hhs.fha.nhinc.properties.PropertyAccessException; import gov.hhs.fha.nhinc.properties.PropertyAccessor; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.nhindirect.xd.common.DirectDocument2; import org.nhindirect.xd.common.DirectDocuments; import org.nhindirect.xd.transform.util.type.MimeType; /** * Builder for {@link MimeMessage}. */ public class MimeMessageBuilder { private final String DIRECT_ATTACHMENT_OPTION = "direct_attachment_option"; @SuppressWarnings("unused") private final String XDM_OPTION = "xdm"; private final String XML_OPTION = "xml"; private final String GATEWAY_PROPERTIES_FILE = "gateway"; private static final Logger LOG = Logger.getLogger(MimeMessageBuilder.class); private final Session session; private final Address fromAddress; private final Address[] recipients; private String subject; private String text; private DirectDocuments documents; private String messageId; private Document attachment; private String attachmentName; /** * Construct the Mime Message builder with required fields. * * @param session used to build the message. * @param fromAddress sender of the message. * @param recipients - list of recipients of the message. */ public MimeMessageBuilder(Session session, Address fromAddress, Address[] recipients) { this.session = session; this.fromAddress = fromAddress; this.recipients = recipients; } /** * @param str for subject. * @return builder */ public MimeMessageBuilder subject(String str) { this.subject = str; return this; } /** * @param str for text * @return builder */ public MimeMessageBuilder text(String str) { this.text = str; return this; } /** * @param directDocuments for attachment * @return builder of mime messages. */ public MimeMessageBuilder documents(DirectDocuments directDocuments) { this.documents = directDocuments; return this; } /** * @param str messageId for message * @return builder of mime messages. */ public MimeMessageBuilder messageId(String str) { this.messageId = str; return this; } /** * @param doc for attachment * @return builder */ public MimeMessageBuilder attachment(Document doc) { this.attachment = doc; return this; } /** * @param str for attachment name * @return builder */ public MimeMessageBuilder attachmentName(String str) { this.attachmentName = str; return this; } /** * Build the Mime Message. * * @return the Mime message. */ public MimeMessage build() { final MimeMessage message = new MimeMessage(session); try { message.setFrom(fromAddress); } catch (Exception e) { throw new DirectException("Exception setting from address: " + fromAddress, e); } try { message.addRecipients(Message.RecipientType.TO, recipients); } catch (Exception e) { throw new DirectException("Exception setting recipient to address(es): " + recipients, e); } try { message.setSubject(subject); } catch (Exception e) { throw new DirectException("Exception setting subject: " + subject, e); } MimeBodyPart messagePart = new MimeBodyPart(); try { messagePart.setText(text); } catch (Exception e) { throw new DirectException("Exception setting mime message part text: " + text, e); } List<MimeBodyPart> attachmentParts = new ArrayList<MimeBodyPart>(); MimeBodyPart attachmentPart = null; try { if (documents != null && !StringUtils.isBlank(messageId)) { addAttachments(attachmentParts, documents, messageId); } else if (attachment != null && !StringUtils.isBlank(attachmentName)) { attachmentPart = createAttachmentFromSOAPRequest(attachment, attachmentName); attachmentParts.add(attachmentPart); } else { throw new Exception( "Could not create attachment. Need documents and messageId or attachment and attachmentName."); } } catch (Exception e) { throw new DirectException("Exception creating attachment: " + attachmentName, e); } Multipart multipart = new MimeMultipart(); try { multipart.addBodyPart(messagePart); if (!attachmentParts.isEmpty()) { for (MimeBodyPart attPart : attachmentParts) { multipart.addBodyPart(attPart); } } message.setContent(multipart); } catch (Exception e) { throw new DirectException("Exception creating multi-part attachment.", e); } try { message.saveChanges(); } catch (Exception e) { throw new DirectException("Exception saving changes.", e); } return message; } /** * Add attachments to the passed in "MimeBodyPart" list. These attachments can be XDM or XML. * * @param attachmentParts * Contains the existing "MimeBodyPart" list for which to add other attachments. Upon return this list * will be updated with new items being added. * @param documents * Contains the Direct documents to attach. * @param messageId * Contains the Direct message "id". * @throws Exception */ private void addAttachments(List<MimeBodyPart> attachmentParts, DirectDocuments documents, String messageId) throws Exception { LOG.debug("Begin MimeMessageBuilder.addAttachments"); String directAttachmentOption = getDirectAttachmentOption(); if (XML_OPTION.equalsIgnoreCase(directAttachmentOption)) { for (DirectDocument2 document : documents.getDocuments()) { if (document.getData() != null) { File xmlFile = null; MimeBodyPart attachmentPart = getMimeBodyPart(); String fileName = document.getMetadata().getId(); fileName = fileName.replace("urn:uuid:", ""); fileName = fileName + getSuffix(document.getMetadata().getMimeType()); LOG.debug("Direct: Processing attachment fileName: '" + fileName + "'"); BufferedOutputStream bufferedOutput = null; try { xmlFile = new File(fileName); LOG.debug("Direct: Writing xml attachment to fileOutputStream"); bufferedOutput = new BufferedOutputStream(new FileOutputStream(xmlFile)); bufferedOutput.write(document.getData()); bufferedOutput.flush(); attachmentPart.attachFile(xmlFile); // NOTE: The header added below is needed in order for the "signature" validation to succeed when sending Direct // messages with XML attachments to the NIST TTT tool. It MUST also come AFTER the xml file has been // attached by the code above this line. attachmentPart.setHeader("Content-Transfer-Encoding", "base64"); attachmentParts.add(attachmentPart); } catch (Exception e) { e.printStackTrace(); String errMessage = "Direct: Error occurred writing xml attachment to bufferedOutputStream. " + e.getMessage(); LOG.error(errMessage); throw new Exception(errMessage, e); } finally { if (bufferedOutput != null) { bufferedOutput.close(); } } LOG.debug("Direct: Successfully added XML attachment to MimeBodyPart list"); } } } else { // Default to "xdm" attachment option String formattedMessageId = formatMessageIdForXDMAttachmentName(messageId); MimeBodyPart attachmentPart = getMimeBodyPart(); attachmentPart.attachFile(documents.toXdmPackage(formattedMessageId).toFile()); attachmentParts.add(attachmentPart); } LOG.debug("End MimeMessageBuilder.addAttachments"); } /** * Format the "messageId" to be used to name the XDM attachment. * * @param messageId * Contains a "messageId" to format. * @return * Returns a formatted "messageId". */ private String formatMessageIdForXDMAttachmentName(String messageId) { String formattedMessageId = messageId; LOG.debug("MimeMessageBuilder.formatMessageIdForXDMAttachmentName - Passed in value: '" + messageId + "'"); if (NullChecker.isNotNullish(messageId)) { formattedMessageId = messageId.replace(NhincConstants.WS_SOAP_HEADER_MESSAGE_ID_PREFIX, ""); if (formattedMessageId.startsWith("<")) { formattedMessageId = formattedMessageId.substring(1); } if (formattedMessageId.endsWith(">")) { formattedMessageId = formattedMessageId.substring(0, formattedMessageId.length() - 1); } } LOG.debug("MimeMessageBuilder.formatMessageIdForXDMAttachmentName - Return value: '" + formattedMessageId + "'"); return formattedMessageId; } /** * Get the mime type suffix. * * @param mimeType * Contains the mime type for which to get the suffix. * @return * Returns a String of the mime suffix. */ private String getSuffix(String mimeType) { return "." + MimeType.lookup(mimeType).getSuffix(); } /** * Get the direct attachment option from a properties file. * * @return * Returns the direct attachment option. */ private String getDirectAttachmentOption() { String directAttachmentOption = ""; try { directAttachmentOption = PropertyAccessor.getInstance(GATEWAY_PROPERTIES_FILE).getProperty(DIRECT_ATTACHMENT_OPTION); } catch (PropertyAccessException e) { e.printStackTrace(); LOG.error("Error occured in retrieving the direct attachment option. Defaulting to 'xdm'."); directAttachmentOption = "xdm"; } LOG.debug("Direct: Direct attachment option is: '" + directAttachmentOption + "'"); return directAttachmentOption; } /** * @return mime body part of the message. */ protected MimeBodyPart getMimeBodyPart() { return new MimeBodyPart(); } private MimeBodyPart createAttachmentFromSOAPRequest(Document data, String name) throws MessagingException, IOException { InputStream is = null; DataSource source = null; DataHandler dhnew = null; MimeBodyPart bodypart = null; try { is = data.getValue().getInputStream(); source = new ByteArrayDataSource(is, "application/octet-stream"); dhnew = new DataHandler(source); bodypart = new MimeBodyPart(); bodypart.setDataHandler(dhnew); bodypart.setHeader("Content-Type", "application/octet-stream"); bodypart.setDisposition(Part.ATTACHMENT); bodypart.setFileName(name); } finally { StreamUtils.closeStreamSilently(is); } return (MimeBodyPart) bodypart; } }
package org.thingml.compilers.java; import org.apache.commons.io.IOUtils; import org.sintef.thingml.*; import org.sintef.thingml.constraints.cepHelper.UnsupportedException; import org.thingml.compilers.Context; import org.thingml.compilers.DebugProfile; import org.thingml.compilers.thing.common.FSMBasedThingImplCompiler; import java.io.File; import java.io.FileWriter; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class JavaThingImplCompiler extends FSMBasedThingImplCompiler { public void generateMessages(Message m, Context ctx) { //TODO: migrate code related to string/binary serialization into plugins String pack = ctx.getContextAnnotation("package"); if (pack == null) pack = "org.thingml.generated"; String rootPack = pack; pack += ".messages"; final StringBuilder builder = ctx.getNewBuilder("src/main/java/" + pack.replace(".", "/") + "/" + ctx.firstToUpper(m.getName()) + "MessageType.java"); JavaHelper.generateHeader(pack, rootPack, builder, ctx, false, false, false); builder.append("import java.nio.*;\n\n"); builder.append("public class " + ctx.firstToUpper(m.getName()) + "MessageType extends EventType {\n"); builder.append("public " + ctx.firstToUpper(m.getName()) + "MessageType(short code) {super(\"" + m.getName() + "\", code);\n}\n\n"); final String code = m.hasAnnotation("code") ? m.annotation("code").get(0) : "0"; builder.append("public " + ctx.firstToUpper(m.getName()) + "MessageType() {\nsuper(\"" + m.getName() + "\", (short) " + code + ");\n}\n\n"); builder.append("public Event instantiate("); for (Parameter p : m.getParameters()) { if (m.getParameters().indexOf(p) > 0) builder.append(", "); builder.append("final " + JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " " + ctx.protectKeyword(p.getName())); } builder.append(") { return new " + ctx.firstToUpper(m.getName()) + "Message(this"); for (Parameter p : m.getParameters()) { builder.append(", " + ctx.protectKeyword(p.getName())); } builder.append("); }\n"); builder.append("@Override\n"); builder.append("public Event instantiate(Map<String, Object> params) {"); builder.append("return instantiate("); for (Parameter p : m.getParameters()) { String cast; if (JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx).equals("int")) cast = "Integer"; else if (JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx).equals("char")) cast = "Character"; else if (JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx).contains(".")) cast = JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx); //extern datatype with full qualified name else cast = ctx.firstToUpper(JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx)); if (m.getParameters().indexOf(p) > 0) builder.append(", "); builder.append("(" + cast + ") params.get(\"" + ctx.protectKeyword(p.getName()) + "\")"); } builder.append(");\n"); builder.append("}\n\n"); //Instantiate message from binary builder.append("/**Instantiates a message from a binary representation*/\n"); builder.append("@Override\npublic Event instantiate(byte[] payload, String serialization) {\n"); builder.append("if (serialization == null || serialization.equals(\"default\")) {\n"); builder.append("ByteBuffer buffer = ByteBuffer.wrap(payload);\n"); builder.append("buffer.order(ByteOrder.BIG_ENDIAN);\n"); builder.append("final short code = buffer.getShort();\n"); builder.append("if (code == this.code) {\n"); for (Parameter p : m.getParameters()) { if (JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx).equals("byte")) { builder.append("final " + JavaHelper.getJavaType(p.getType(), p.getCardinality() != null, ctx) + " " + p.getName() + " = " + "buffer.get();\n"); } else if (JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx).equals("boolean")) { builder.append("final " + JavaHelper.getJavaType(p.getType(), p.getCardinality() != null, ctx) + " " + p.getName() + " = " + "buffer.get() == 0x00 ? false : true;\n"); } else { builder.append("final " + JavaHelper.getJavaType(p.getType(), p.getCardinality() != null, ctx) + " " + p.getName() + " = " + "buffer.get" + ctx.firstToUpper(JavaHelper.getJavaType(p.getType(), p.getCardinality() != null, ctx)) + "();\n"); } } builder.append("return instantiate("); int size = 2; for (Parameter p : m.getParameters()) { if (m.getParameters().indexOf(p) > 0) builder.append(", "); builder.append(p.getName()); size = size + ((PrimitiveType)p.getType()).getByteSize(); } builder.append(");\n"); builder.append("}\n"); builder.append("return null;\n"); builder.append("}\n"); builder.append("//Do NOT remove following comment. Might be used by a serialization plugin\n"); builder.append("/*BINARY_LOAD*/\n"); builder.append("return null;\n"); builder.append("}\n\n"); //Instantiate message from String builder.append("/**Instantiates a message from a string representation*/\n"); builder.append("@Override\npublic Event instantiate(String payload, String serialization) {\n"); builder.append("if (serialization == null || serialization.equals(\"default\")) {\n"); builder.append("final String[] msg = payload.trim().replace(\" \", \"\").replace(\"\\t\", \"\").replace(\"\\n\", \"\").replace(\"\\\"\", \"\").replace(\")\", \"\").split(\"[(:,]+\");\n"); builder.append("return parse(msg);\n"); builder.append("} else if (serialization.equals(\"json-default\")) {\n"); builder.append("final String[] msg = payload.trim().replace(\" \", \"\").replace(\"\\t\", \"\").replace(\"\\n\", \"\").replace(\"\\\"\", \"\").replace(\"{\", \"\").replace(\"}\", \"\").split(\"[:,]+\");\n"); builder.append("return parse(msg);\n"); builder.append("}\n"); builder.append("//Do NOT remove following comment. Might be used by a serialization plugin\n"); builder.append("/*STRING_LOAD*/\n"); builder.append("return null;\n"); builder.append("}\n\n"); builder.append("private Event parse(String[] msg) {\n"); builder.append("if (msg.length != " + (2*m.getParameters().size()+1) + ")\n"); builder.append("return null;\n"); builder.append("if (\"" + m.getName() + "\".equals(msg[0])) {\n"); StringBuilder temp = new StringBuilder(); for (Parameter p : m.getParameters()) { String cast; if (JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx).equals("int")) cast = "Integer"; else if (JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx).equals("char")) cast = "Character"; else if (JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx).contains(".")) throw new UnsupportedException("Cannot serialize non-primitive types", "type", "java"); else cast = ctx.firstToUpper(JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx)); builder.append("if (\"" + p.getName() + "\".equals(msg[" + (2*m.getParameters().indexOf(p) + 1) + "])) {\n"); if (cast.equals("Character")) { builder.append("final " + JavaHelper.getJavaType(p.getType(), p.getCardinality() != null, ctx) + " " + p.getName() + " = " + "msg[" + (2 * m.getParameters().indexOf(p) + 2) + "].toCharArray()[0];\n"); } else { builder.append("final " + JavaHelper.getJavaType(p.getType(), p.getCardinality() != null, ctx) + " " + p.getName() + " = " + cast + ".parse" + ctx.firstToUpper(JavaHelper.getJavaType(p.getType(), p.getCardinality() != null, ctx)) + "(msg[" + (2 * m.getParameters().indexOf(p) + 2) + "]);\n"); } if (m.getParameters().indexOf(p) > 0) temp.append(", "); temp.append(p.getName()); if (m.getParameters().indexOf(p) == m.getParameters().size()-1) { builder.append("return instantiate(" + temp.toString() + ");\n"); } } for(int i = 0; i < m.getParameters().size(); i++) { builder.append("}\n"); } builder.append("}\n"); builder.append("return null;\n"); builder.append("}\n\n"); builder.append("public class " + ctx.firstToUpper(m.getName()) + "Message extends Event implements java.io.Serializable {\n\n"); for (Parameter p : m.getParameters()) { builder.append("public final " + JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " " + ctx.protectKeyword(p.getName()) + ";\n"); } builder.append("@Override\npublic String toString(){\n"); builder.append("return \"" + m.getName() + " (\""); int i = 0; for (Parameter p : m.getParameters()) { if (i > 0) { builder.append(" + \", \""); } builder.append(" + \"" + p.getName() + ": \" + " + ctx.protectKeyword(p.getName())); i++; } builder.append(" + \")\";\n}\n\n"); builder.append("protected " + ctx.firstToUpper(m.getName()) + "Message(EventType type"); for (Parameter p : m.getParameters()) { builder.append(", final " + JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " " + ctx.protectKeyword(p.getName())); } builder.append(") {\n"); builder.append("super(type);\n"); for (Parameter p : m.getParameters()) { builder.append("this." + ctx.protectKeyword(p.getName()) + " = " + ctx.protectKeyword(p.getName()) + ";\n"); } builder.append("}\n"); builder.append("@Override\n"); builder.append("public Event clone() {\n"); builder.append("return instantiate("); for (Parameter p : m.getParameters()) { if (m.getParameters().indexOf(p) > 0) builder.append(", "); builder.append("this." + ctx.protectKeyword(p.getName())); } builder.append(");\n"); builder.append("}"); //Serialize message into String builder.append("/**Serializes a message into a string*/\n"); builder.append("@Override\npublic String toString(String serialization) {\n"); builder.append("if (serialization == null || serialization.equals(\"default\")) {\n"); builder.append("return toString();\n"); builder.append("} else if (serialization.equals(\"json-default\")) {"); builder.append("return \"{\\\"" + m.getName() + "\\\":{"); for (Parameter p : m.getParameters()) { if (m.getParameters().indexOf(p)>0) builder.append(","); builder.append("\\\"" + p.getName() + "\\\":\" + " + p.getName() + " + \""); } builder.append("}}\";\n"); builder.append("}\n"); builder.append("//Do NOT remove following comment. Might be used by a serialization plugin\n"); builder.append("/*STRING_SAVE*/\n"); builder.append("return null;\n"); builder.append("}\n\n"); //Serialize message into binary builder.append("/**Serializes a message into a binary format*/\n"); builder.append("@Override\npublic byte[] toBytes(String serialization) {\n"); builder.append("if (serialization == null || serialization.equals(\"default\")) {\n"); builder.append("ByteBuffer buffer = ByteBuffer.allocate(" + size + ");\n"); builder.append("buffer.order(ByteOrder.BIG_ENDIAN);\n"); builder.append("buffer.putShort(code);\n"); for (Parameter p : m.getParameters()) { if (JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx).equals("byte")) { builder.append("buffer.put(" + p.getName() + ");\n"); } else if (JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx).equals("boolean")) { builder.append("if(" + p.getName() + ") buffer.put((byte)0x01); else buffer.put((byte)0x00); "); } else { builder.append("buffer.put" + ctx.firstToUpper(JavaHelper.getJavaType(p.getType(), p.getCardinality() != null, ctx)) + "(" + p.getName() + ");\n"); } } builder.append("return buffer.array();\n"); builder.append("}\n"); builder.append("//Do NOT remove following comment. Might be used by a serialization plugin\n"); builder.append("/*BINARY_SAVE*/\n"); builder.append("return null;\n"); builder.append("}\n\n"); builder.append("}\n\n"); builder.append("}\n\n"); } protected void generateFunction(Function f, Thing thing, StringBuilder builder, Context ctx) { if (!f.isDefined("abstract", "true")) { DebugProfile debugProfile = ctx.getCompiler().getDebugProfiles().get(thing); if (f.hasAnnotation("override") || f.hasAnnotation("implements")) { builder.append("@Override\npublic "); } else { builder.append("private "); } final String returnType = JavaHelper.getJavaType(f.getType(), f.isIsArray(), ctx); builder.append(returnType + " " + f.getName() + "("); JavaHelper.generateParameter(f, builder, ctx); builder.append(") {\n"); if(!(debugProfile==null) && debugProfile.getDebugFunctions().contains(f)) { //builder.append("if(isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|blue \" + getName() + \": executing function " + f.getName() + "("); builder.append("printDebug(\"" + ctx.traceFunctionBegin(thing, f) + "(\""); int i = 0; for (Parameter pa : f.getParameters()) { if (i > 0) builder.append(" + \", \""); builder.append(" + "); builder.append(ctx.protectKeyword(ctx.getVariableName(pa))); } builder.append("+ \")\");\n"); } ctx.getCompiler().getThingActionCompiler().generate(f.getBody(), builder, ctx); if(!(debugProfile==null) && debugProfile.getDebugFunctions().contains(f)) { builder.append("printDebug(\"" + ctx.traceFunctionDone(thing, f) + "\");"); } builder.append("}\n"); } } @Override public void generateImplementation(Thing thing, Context ctx) { DebugProfile debugProfile = ctx.getCompiler().getDebugProfiles().get(thing); String pack = ctx.getContextAnnotation("package"); if (pack == null) pack = "org.thingml.generated"; final StringBuilder builder = ctx.getBuilder("src/main/java/" + pack.replace(".", "/") + "/" + ctx.firstToUpper(thing.getName()) + ".java"); boolean hasMessages = thing.allMessages().size() > 0; boolean hasStream = thing.getStreams().size() > 0; JavaHelper.generateHeader(pack, pack, builder, ctx, false, hasMessages,hasStream); builder.append("\n/**\n"); builder.append(" * Definition for type : " + thing.getName() + "\n"); builder.append(" **/\n"); List<String> interfaces = new ArrayList<String>(); for (Port p : thing.allPorts()) { if (!p.isDefined("public", "false") && p.getReceives().size() > 0) { interfaces.add("I" + ctx.firstToUpper(thing.getName()) + "_" + p.getName()); } } if (thing.hasAnnotation("java_interface")) { interfaces.addAll(thing.annotation("java_interface")); } builder.append("public class " + ctx.firstToUpper(thing.getName()) + " extends Component "); if (interfaces.size() > 0) { builder.append("implements "); int id = 0; for (String i : interfaces) { if (id > 0) { builder.append(", "); } builder.append(i); id++; } } builder.append(" {\n\n"); builder.append("private List<AttributeListener> attListener = new ArrayList<AttributeListener>();\n"); builder.append("public void addAttributeListener(AttributeListener listener){\nthis.attListener.add(listener);\n}\n\n"); builder.append("public void removeAttributeListener(AttributeListener listener){\nthis.attListener.remove(listener);\n}\n\n"); builder.append("private boolean debug = false;\n"); builder.append("public boolean isDebug() {return debug;}\n"); builder.append("public void setDebug(boolean debug) {this.debug = debug;}\n"); builder.append("@Override\npublic String toString() {\n"); builder.append("String result = \"instance \" + getName() + \"\\n\";\n"); for(Property p : thing.allProperties()) { builder.append("result += \"\\t" + p.getName() + " = \" + " + ctx.getVariableName(p) + ";\n" ); } builder.append("result += \"\";\n"); builder.append("return result;\n"); builder.append("}\n\n"); if(debugProfile.isActive()) { builder.append("public String instanceName;"); builder.append("public void printDebug("); builder.append("String trace");//if debugWithString builder.append(") {\n"); builder.append("if(this.isDebug()) {\n"); builder.append("System.out.println(this.instanceName + trace);\n"); builder.append("}\n"); builder.append("}\n\n"); } boolean overrideReceive = false; for(StateMachine sm : thing.getBehaviour()) { if (sm.getInternal().size() > 0) { overrideReceive = true; break; } } if (overrideReceive) { builder.append("@Override\npublic void receive(Event event, final Port p){\n"); builder.append("if (root == null) {\n"); builder.append("boolean consumed = false;\n"); for (StateMachine sm : thing.getBehaviour()) { int id = 0; for (InternalTransition i : sm.getInternal()) { for (Event e : i.getEvent()) { ReceiveMessage rm = (ReceiveMessage) e; builder.append("if ("); if (id > 0) builder.append("!consumed && "); builder.append("event.getType().equals(" + rm.getMessage().getName() + "Type)) {\n"); builder.append("final " + ctx.firstToUpper(rm.getMessage().getName()) + "MessageType." + ctx.firstToUpper(rm.getMessage().getName()) + "Message " + rm.getMessage().getName() + " = (" + ctx.firstToUpper(rm.getMessage().getName()) + "MessageType." + ctx.firstToUpper(rm.getMessage().getName()) + "Message) event;\n"); if (i.getGuard() != null) { builder.append(" if ("); ctx.getCompiler().getThingActionCompiler().generate(i.getGuard(), builder, ctx); builder.append(") {\n"); } builder.append("consumed = true;\n"); ctx.getCompiler().getThingActionCompiler().generate(i.getAction(), builder, ctx); builder.append("}\n"); id++; } if (i.getEvent().size() == 0) {//FIXME: some code duplication from above... if (i.getGuard() != null) { builder.append("if ("); if (id > 0) builder.append("!consumed && "); ctx.getCompiler().getThingActionCompiler().generate(i.getGuard(), builder, ctx); builder.append(") {\n"); } builder.append("consumed = true;\n"); ctx.getCompiler().getThingActionCompiler().generate(i.getAction(), builder, ctx); builder.append("}\n"); id++; } builder.append("}\n"); } } builder.append("if (!consumed){\nsuper.receive(event, p);\n}\n"); builder.append("else {"); builder.append("for (Component child : forks) {\n"); builder.append("Event child_e = event.clone();\n"); builder.append("child.receive(child_e, p);\n"); builder.append("}\n"); builder.append("for(int i = 0; i < behavior.regions.length; i++) {\n"); builder.append("behavior.regions[i].handle(event, p);"); builder.append("}\n"); builder.append("}\n"); builder.append("} else {\n"); builder.append("super.receive(event, p);\n"); builder.append("}\n"); builder.append("}\n\n"); } for (Port p : thing.allPorts()) { if (!p.isDefined("public", "false") && p.getSends().size() > 0) { builder.append("private Collection<I" + ctx.firstToUpper(thing.getName()) + "_" + p.getName() + "Client> " + p.getName() + "_clients = Collections.synchronizedCollection(new LinkedList<I" + ctx.firstToUpper(thing.getName()) + "_" + p.getName() + "Client>());\n"); builder.append("public synchronized void registerOn" + ctx.firstToUpper(p.getName()) + "(I" + ctx.firstToUpper(thing.getName()) + "_" + p.getName() + "Client client){\n"); builder.append(p.getName() + "_clients.add(client);\n"); builder.append("}\n\n"); builder.append("public synchronized void unregisterFrom" + ctx.firstToUpper(p.getName()) + "(I" + ctx.firstToUpper(thing.getName()) + "_" + p.getName() + "Client client){\n"); builder.append(p.getName() + "_clients.remove(client);\n"); builder.append("}\n\n"); } } /*if (!debugProfile.getDebugMessages().isEmpty()) {//FIXME: receive is overridden elsewhere, cannot be overridden twice. To be merged. builder.append("@Override\npublic void receive(Event event, final Port p){\n"); int i = 0; for (Port p : thing.allPorts()) { for (Message m : p.getReceives()) { if (debugProfile.getDebugMessages().containsKey(p) && debugProfile.getDebugMessages().get(p).contains(m)) { if (i > 0) builder.append("else "); builder.append("if(p.getName().equals(\"" + p.getName() + "\") && event.getType().getName().equals(\"" + m.getName() + "\")) {\n"); //builder.append("if(this.isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|green \" + getName() + \": " + p.getName() + "?" + m.getName() + "("); builder.append("printDebug(\"" + ctx.traceReceiveMessage(thing, p, m) + "(\""); int j = 0; for (Parameter pa : m.getParameters()) { if (j > 0) builder.append(" + \", \""); builder.append(" + ((" + ctx.firstToUpper(m.getName()) + "MessageType." + ctx.firstToUpper(m.getName()) + "Message) event)." + ctx.protectKeyword(pa.getName())); j++; } builder.append(" + \")\");\n"); builder.append("}\n"); i++; } } } builder.append("super.receive(event, p);\n"); builder.append("}\n\n"); }*/ for (Port p : thing.allPorts()) { if (!p.isDefined("public", "false")) { for (Message m : p.getReceives()) { builder.append("@Override\n"); builder.append("public synchronized void " + m.getName() + "_via_" + p.getName() + "("); JavaHelper.generateParameter(m, builder, ctx); builder.append("){\n"); builder.append("receive(" + m.getName() + "Type.instantiate("); for (Parameter pa : m.getParameters()) { if (m.getParameters().indexOf(pa) > 0) builder.append(", "); builder.append(ctx.protectKeyword(ctx.getVariableName(pa))); } builder.append("), " + p.getName() + "_port);\n"); builder.append("}\n\n"); } } } for (Port p : thing.allPorts()) { for (Message m : p.getSends()) { builder.append("private void send" + ctx.firstToUpper(m.getName()) + "_via_" + p.getName() + "("); JavaHelper.generateParameter(m, builder, ctx); builder.append("){\n"); if (debugProfile.getDebugMessages().get(p) != null && debugProfile.getDebugMessages().get(p).contains(m)) { //builder.append("if(this.isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|green \" + getName() + \": " + p.getName() + "!" + m.getName() + "("); builder.append("printDebug(\"" + ctx.traceSendMessage(thing, p, m) + "(\""); int i = 0; for (Parameter pa : m.getParameters()) { if (i > 0) builder.append(" + \", \""); builder.append(" + " + ctx.protectKeyword(ctx.getVariableName(pa))); } builder.append(" + \")\");\n"); } builder.append("//ThingML send\n"); builder.append(p.getName() + "_port.send(" + m.getName() + "Type.instantiate("); for (Parameter pa : m.getParameters()) { if (m.getParameters().indexOf(pa) > 0) builder.append(", "); builder.append(ctx.protectKeyword(ctx.getVariableName(pa))); } builder.append("));\n"); if (!p.isDefined("public", "false")) { builder.append("//send to other clients\n"); builder.append("for(I" + ctx.firstToUpper(thing.getName()) + "_" + p.getName() + "Client client : " + p.getName() + "_clients){\n"); builder.append("client." + m.getName() + "_from_" + p.getName() + "("); int id = 0; for (Parameter pa : m.getParameters()) { if (id > 0) { builder.append(", "); } builder.append(ctx.protectKeyword(ctx.getVariableName(pa))); id++; } builder.append(");\n"); builder.append("}"); } builder.append("}\n\n"); } } builder.append("//Attributes\n"); for (Property p : thing.allPropertiesInDepth()) { builder.append("private "); if (!p.isChangeable()) { builder.append("final "); } builder.append(JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " " + ctx.getVariableName(p) + ";\n"); } for(Property p : thing.allPropertiesInDepth()/*debugProfile.getDebugProperties()*/) {//FIXME: we should only generate overhead for the properties we actually want to debug! builder.append("private "); builder.append(JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " debug_" + ctx.getVariableName(p) + ";\n"); } builder.append("//Ports\n"); for (Port p : thing.allPorts()) { builder.append("private Port " + p.getName() + "_port;\n"); } builder.append("//Message types\n"); for (Message m : thing.allMessages()) { builder.append("protected final " + ctx.firstToUpper(m.getName()) + "MessageType " + m.getName() + "Type = new " + ctx.firstToUpper(m.getName()) + "MessageType();\n"); builder.append("public " + ctx.firstToUpper(m.getName()) + "MessageType get" + ctx.firstToUpper(m.getName()) + "Type(){\nreturn " + m.getName() + "Type;\n}\n\n"); generateMessages(m, ctx); } builder.append("//CEP Streams\n"); for (Stream stream : thing.getStreams()) { if(stream.getInput() instanceof SimpleSource) { builder.append("private rx.Observable " + stream.getInput().qname("_") + ";\n"); builder.append("private Action1 sub_" + stream.getInput().qname("_") + ";\n"); builder.append("private rx.Subscription hook_" + stream.getInput().qname("_") + ";\n"); } else if (stream.getInput() instanceof SourceComposition) { builder.append("private rx.Observable " + stream.qname("_") + ";\n"); builder.append("private Action1 sub_" + stream.qname("_") + ";\n"); builder.append("private rx.Subscription hook_" + stream.qname("_") + ";\n"); } } builder.append("//Empty Constructor\n"); builder.append("public " + ctx.firstToUpper(thing.getName()) + "() {\nsuper();\n"); //builder.append("org.fusesource.jansi.AnsiConsole.systemInstall();\n");//FIXME: only if debug for (Property p : thing.allPropertiesInDepth()) { Expression e = thing.initExpression(p); if (e != null) { builder.append(ctx.getVariableName(p) + " = "); ctx.getCompiler().getThingActionCompiler().generate(e, builder, ctx); builder.append(";\n"); } } builder.append("}\n\n"); boolean hasReadonly = false; for (Property p : thing.allPropertiesInDepth()) { if (!p.isChangeable()) { hasReadonly = true; break; } } if (hasReadonly) { builder.append("//Constructor (only readonly (final) attributes)\n"); builder.append("public " + ctx.firstToUpper(thing.getName()) + "("); int i = 0; for (Property p : thing.allPropertiesInDepth()) { if (!p.isChangeable()) { if (i > 0) builder.append(", "); builder.append("final " + JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " " + ctx.getVariableName(p)); i++; } } builder.append(") {\n"); builder.append("super();\n"); for (Property p : thing.allPropertiesInDepth()) { if (!p.isChangeable()) { builder.append("this." + ctx.getVariableName(p) + " = " + ctx.getVariableName(p) + ";\n"); } } builder.append("}\n\n"); } builder.append("//Constructor (all attributes)\n"); builder.append("public " + ctx.firstToUpper(thing.getName()) + "(String name"); for (Property p : thing.allPropertiesInDepth()) { builder.append(", final " + JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " " + ctx.getVariableName(p)); } builder.append(") {\n"); builder.append("super(name);\n"); for (Property p : thing.allPropertiesInDepth()) { builder.append("this." + ctx.getVariableName(p) + " = " + ctx.getVariableName(p) + ";\n"); } builder.append("}\n\n"); builder.append("//Getters and Setters for non readonly/final attributes\n"); for (Property p : thing.allPropertiesInDepth()) { builder.append("public " + JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " get" + ctx.firstToUpper(ctx.getVariableName(p)) + "() {\nreturn " + ctx.getVariableName(p) + ";\n}\n\n"); if (p.isChangeable()) { builder.append("public void set" + ctx.firstToUpper(ctx.getVariableName(p)) + "(" + JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " " + ctx.getVariableName(p) + ") {\nthis." + ctx.getVariableName(p) + " = " + ctx.getVariableName(p) + ";\n}\n\n"); } } builder.append("//Getters for Ports\n"); for (Port p : thing.allPorts()) { builder.append("public Port get" + ctx.firstToUpper(p.getName()) + "_port() {\nreturn " + p.getName() + "_port;\n}\n"); } for (StateMachine b : thing.allStateMachines()) { for (Region r : b.allContainedRegions()) { ((FSMBasedThingImplCompiler) ctx.getCompiler().getThingImplCompiler()).generateRegion(r, builder, ctx); } for(Session s : b.allContainedSessions()) {//Session are only allowed at the root ((FSMBasedThingImplCompiler) ctx.getCompiler().getThingImplCompiler()).generateRegion(s, builder, ctx); } } builder.append("public Component buildBehavior(String session, Component root) {\n"); builder.append("if (root == null) {\n"); builder.append("//Init ports\n"); for (Port p : thing.allPorts()) { builder.append(p.getName() + "_port = new Port("); if (p instanceof ProvidedPort) builder.append("PortType.PROVIDED"); else builder.append("PortType.REQUIRED"); builder.append(", \"" + p.getName() + "\", this);\n"); } builder.append("} else {\n"); for (Port p : thing.allPorts()) { builder.append(p.getName() + "_port = ((" + thing.getName() + ")root)." + p.getName() + "_port;\n"); } builder.append("}\n"); builder.append("createCepStreams();"); builder.append("if (session == null){\n"); builder.append("//Init state machine\n"); for (StateMachine b : thing.allStateMachines()) { builder.append("behavior = build" + b.qname("_") + "();\n"); } builder.append("}\n"); for(StateMachine b : thing.allStateMachines()) { for(Session s : b.allContainedSessions()) { builder.append("else if (\"" + s.getName() + "\".equals(session)) {\n"); builder.append("behavior = build" + s.qname("_") + "();\n"); builder.append("}\n"); } } builder.append("return this;\n"); builder.append("}\n\n"); if(thing.getStreams().size() > 0) { builder.append("@Override\n") .append("protected void createCepStreams() {\n"); for (Stream stream : thing.getStreams()) { builder.append("create" + stream.getInput().qname("_") + "();\n"); } builder.append("}\n\n"); builder.append("protected void stopAllStreams() {\n"); for (Stream stream : thing.getStreams()) { builder.append("stop" + stream.getInput().qname("_") + "();\n"); } builder.append("}\n\n"); builder.append("@Override\npublic void stop(){\nsuper.stop();\nstopAllStreams();\n}\n\n"); for (Stream stream : thing.getStreams()) { builder.append("private void create" + stream.getInput().qname("_") + "() {\n"); ctx.getCompiler().getCepCompiler().generateStream(stream, builder, ctx); builder.append("}\n\n"); builder.append("private void start" + stream.getInput().qname("_") + "(){\n"); if(stream.getInput() instanceof SimpleSource) { builder.append("if (this.hook_" + stream.getInput().qname("_") + " == null)"); builder.append("this.hook_" + stream.getInput().qname("_") + " = this." + stream.getInput().qname("_") + ".subscribe(this.sub_" + stream.getInput().qname("_") + ");\n"); } else if (stream.getInput() instanceof SourceComposition) { builder.append("if (this.hook_" + stream.qname("_") + " == null)"); builder.append("this.hook_" + stream.qname("_") + " = this." + stream.qname("_") + ".subscribe(this.sub_" + stream.qname("_") + ");\n"); } builder.append("}\n\n"); builder.append("private void stop" + stream.getInput().qname("_") + "(){\n"); if(stream.getInput() instanceof SimpleSource) { builder.append("this.hook_" + stream.getInput().qname("_") + ".unsubscribe();\n"); builder.append("this.hook_" + stream.getInput().qname("_") + " = null;\n"); } else if (stream.getInput() instanceof SourceComposition) { builder.append("this.hook_" + stream.qname("_") + ".unsubscribe();\n"); builder.append("this.hook_" + stream.qname("_") + " = null;\n"); } builder.append("}\n\n"); } } for (Function f : thing.allFunctions()) { generateFunction(f, thing, builder, ctx); } builder.append("}\n"); } protected void generateStateMachine(StateMachine sm, StringBuilder builder, Context ctx) { generateCompositeState(sm, builder, ctx); } private void generateActionsForState(State s, StringBuilder builder, Context ctx) { } protected void generateCompositeState(CompositeState c, StringBuilder builder, Context ctx) { final String actionName = (c.getEntry() != null || c.getExit() != null) ? ctx.firstToUpper(c.qname("_")) + "Action" : "NullStateAction"; builder.append("final List<AtomicState> states_" + c.qname("_") + " = new ArrayList<AtomicState>();\n"); for (State s : c.getSubstate()) { if (!(s instanceof Session)) { if (s instanceof CompositeState) { CompositeState cs = (CompositeState) s; builder.append("final CompositeState state_" + cs.qname("_") + " = build" + cs.qname("_") + "();\n"); builder.append("states_" + c.qname("_") + ".add(state_" + cs.qname("_") + ");\n"); } else { generateState(s, builder, ctx); } } } builder.append("final List<Region> regions_" + c.qname("_") + " = new ArrayList<Region>();\n"); for (Region r : c.getRegion()) { builder.append("regions_" + c.qname("_") + ".add(build" + r.qname("_") + "());\n"); } builder.append("final List<Handler> transitions_" + c.qname("_") + " = new ArrayList<Handler>();\n"); for (State s : c.getSubstate()) { for (InternalTransition i : s.getInternal()) { buildTransitionsHelper(builder, ctx, s, i); } for (Transition t : s.getOutgoing()) { buildTransitionsHelper(builder, ctx, s, t); } } builder.append("final CompositeState state_" + c.qname("_") + " = "); builder.append("new CompositeState(\"" + c.getName() + "\", states_" + c.qname("_") + ", state_" + c.getInitial().qname("_") + ", transitions_" + c.qname("_") + ", regions_" + c.qname("_") + ", "); if (c.isHistory()) builder.append("true"); else builder.append("false"); builder.append(")"); DebugProfile debugProfile = ctx.getCompiler().getDebugProfiles().get(c.findContainingThing()); if (c.getEntry() != null || c.getExit() != null || debugProfile.isDebugBehavior() || c.getProperties().size() > 0) { builder.append("{\n"); for(Property p : c.getProperties()) { builder.append("private " + JavaHelper.getJavaType(p.getType(), p.getCardinality()!=null, ctx) + " " + ctx.getVariableName(p)); if (c instanceof Session) { builder.append(" = " + ctx.getVariableName(p) + "_"); } else { if (p.getInit() != null) { builder.append(" = "); ctx.getCompiler().getThingActionCompiler().generate(p.getInit(), builder, ctx); } } builder.append(";\n"); builder.append("public " + JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " get" + ctx.firstToUpper(ctx.getVariableName(p)) + "() {\nreturn " + ctx.getVariableName(p) + ";\n}\n\n"); //if (p.isChangeable()) { builder.append("public void set" + ctx.firstToUpper(ctx.getVariableName(p)) + "(" + JavaHelper.getJavaType(p.getType(), p.isIsArray(), ctx) + " " + ctx.getVariableName(p) + ") {\nthis." + ctx.getVariableName(p) + " = " + ctx.getVariableName(p) + ";\n}\n\n"); } if (c.getEntry() != null || debugProfile.isDebugBehavior()) { builder.append("@Override\n"); builder.append("public void onEntry() {\n"); if (debugProfile.isDebugBehavior()) { //builder.append("if(isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|yellow \" + getName() + \": enters " + c.qualifiedName(":") + "|@\"));\n"); builder.append("printDebug(\"" + ctx.traceOnEntry(c.findContainingThing(), c.findContainingRegion(), c.findContainingState()) + "\");\n"); } if (c.getEntry() != null) ctx.getCompiler().getThingActionCompiler().generate(c.getEntry(), builder, ctx); builder.append("super.onEntry();\n"); builder.append("}\n\n"); } if (c.getExit() != null || debugProfile.isDebugBehavior()) { builder.append("@Override\n"); builder.append("public void onExit() {\n"); builder.append("super.onExit();\n"); if (debugProfile.isDebugBehavior()) { //builder.append("if(isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|yellow \" + getName() + \": exits " + c.qualifiedName(":") + "|@\"));\n"); builder.append("printDebug(\"" + ctx.traceOnExit(c.findContainingThing(), c.findContainingRegion(), c.findContainingState()) + "\");\n"); } if (c.getExit() != null) ctx.getCompiler().getThingActionCompiler().generate(c.getExit(), builder, ctx); builder.append("}\n\n"); } builder.append("}\n"); } builder.append(";\n"); } protected void generateFinalState(FinalState s, StringBuilder builder, Context ctx) { generateAtomicState(s, builder, ctx); } protected void generateAtomicState(State s, StringBuilder builder, Context ctx) { if (s instanceof FinalState) { builder.append("final FinalState state_" + s.qname("_") + " = new FinalState(\"" + s.getName() + "\")\n"); } else { builder.append("final AtomicState state_" + s.qname("_") + " = new AtomicState(\"" + s.getName() + "\")\n"); } DebugProfile debugProfile = ctx.getCompiler().getDebugProfiles().get(s.findContainingThing()); if (s.getEntry() != null || s.getExit() != null || debugProfile.isDebugBehavior() || s instanceof FinalState) { builder.append("{\n"); if (s.getEntry() != null || debugProfile.isDebugBehavior() || s instanceof FinalState) { builder.append("@Override\n"); builder.append("public void onEntry() {\n"); if (debugProfile.isDebugBehavior()) { //builder.append("if(isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|yellow \" + getName() + \": enters " + s.qualifiedName(":") + "|@\"));\n"); builder.append("printDebug(\"" + ctx.traceOnEntry(s.findContainingThing(), s.findContainingRegion(), s) + "\");\n"); } if (s.getEntry() != null) ctx.getCompiler().getThingActionCompiler().generate(s.getEntry(), builder, ctx); if (s instanceof FinalState) { builder.append("stop();\n"); builder.append("delete();\n"); //builder.append("System.gc();\n"); } builder.append("}\n\n"); } if (s.getExit() != null || debugProfile.isDebugBehavior()) { builder.append("@Override\n"); builder.append("public void onExit() {\n"); if (debugProfile.isDebugBehavior()) { //builder.append("if(isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|yellow \" + getName() + \": enters " + s.qualifiedName(":") + "|@\"));\n"); builder.append("printDebug(\"" + ctx.traceOnExit(s.findContainingThing(), s.findContainingRegion(), s) + "\");\n"); } if (s.getExit() != null) ctx.getCompiler().getThingActionCompiler().generate(s.getExit(), builder, ctx); builder.append("}\n\n"); } builder.append("}"); } builder.append(";\n"); if (s.eContainer() instanceof State || s.eContainer() instanceof Region) { builder.append("states_" + ((ThingMLElement) s.eContainer()).qname("_") + ".add(state_" + s.qname("_") + ");\n"); } } public void generateRegion(Region r, StringBuilder builder, Context ctx) { if (r instanceof CompositeState) { builder.append("private CompositeState build" + r.qname("_") + "(){\n"); CompositeState c = (CompositeState) r; generateState(c, builder, ctx); builder.append("return state_" + r.qname("_") + ";\n"); } else { builder.append("private Region build" + r.qname("_") + "(){\n"); buildRegion(r, builder, ctx); builder.append("return reg_" + r.qname("_") + ";\n"); } builder.append("}\n\n"); } private void buildRegion(Region r, StringBuilder builder, Context ctx) { builder.append("final List<AtomicState> states_" + r.qname("_") + " = new ArrayList<AtomicState>();\n"); for (State s : r.getSubstate()) { if (s instanceof CompositeState) { builder.append("CompositeState state_" + s.qname("_") + " = build" + s.qname("_") + "();\n"); builder.append("states_" + r.qname("_") + ".add(state_" + s.qname("_") + ");\n"); } else { generateState(s, builder, ctx); } } builder.append("final List<Handler> transitions_" + r.qname("_") + " = new ArrayList<Handler>();\n"); for (State s : r.getSubstate()) { for (InternalTransition i : s.getInternal()) { buildTransitionsHelper(builder, ctx, s, i); } for (Transition t : s.getOutgoing()) { buildTransitionsHelper(builder, ctx, s, t); } } builder.append("final Region reg_" + r.qname("_") + " = new Region(\"" + r.getName() + "\", states_" + r.qname("_") + ", state_" + r.getInitial().qname("_") + ", transitions_" + r.qname("_") + ", "); if (r.isHistory()) builder.append("true"); else builder.append("false"); builder.append(");\n"); } private void buildTransitionsHelper(StringBuilder builder, Context ctx, State s, Handler i) { DebugProfile debugProfile = ctx.getCompiler().getDebugProfiles().get(s.findContainingThing()); if (i.getEvent() != null && i.getEvent().size() > 0) { for (Event e : i.getEvent()) { ReceiveMessage r = (ReceiveMessage) e; if (i instanceof Transition) { Transition t = (Transition) i; builder.append("transitions_" + ((ThingMLElement) s.eContainer()).qname("_") + ".add(new Transition(\""); if (i.getName() != null) builder.append(i.getName()); else builder.append(i.hashCode()); builder.append("\"," + r.getMessage().getName() + "Type, " + r.getPort().getName() + "_port, state_" + s.qname("_") + ", state_" + t.getTarget().qname("_") + ")"); } else { InternalTransition h = (InternalTransition) i; builder.append("transitions_" + ((ThingMLElement) s.eContainer()).qname("_") + ".add(new InternalTransition(\""); if (i.getName() != null) builder.append(i.getName()); else builder.append(i.hashCode()); builder.append("\"," + r.getMessage().getName() + "Type, " + r.getPort().getName() + "_port, state_" + s.qname("_") + ")"); } if (i.getGuard() != null || i.getAction() != null || debugProfile.isDebugBehavior()) builder.append("{\n"); if (i.getGuard() != null) { builder.append("@Override\n"); builder.append("public boolean doCheck(final Event e) {\n"); if (e != null) { builder.append("final " + ctx.firstToUpper(r.getMessage().getName()) + "MessageType." + ctx.firstToUpper(r.getMessage().getName()) + "Message " + r.getMessage().getName() + " = (" + ctx.firstToUpper(r.getMessage().getName()) + "MessageType." + ctx.firstToUpper(r.getMessage().getName()) + "Message) e;\n"); } else { } builder.append("return "); ctx.getCompiler().getThingActionCompiler().generate(i.getGuard(), builder, ctx); builder.append(";\n"); builder.append("}\n\n"); } if (i.getAction() != null || debugProfile.isDebugBehavior()) { builder.append("@Override\n"); builder.append("public void doExecute(final Event e) {\n"); if (debugProfile.isDebugBehavior()) { if (i instanceof Transition) { Transition t = (Transition) i; //builder.append("if(isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|yellow \" + getName() + \": on " + r.getPort().getName() + "?" + r.getMessage().getName() + " from " + ((State) t.eContainer()).qualifiedName(":") + " to " + t.getTarget().qualifiedName(":") + "|@\"));\n"); builder.append("printDebug(\"" + ctx.traceTransition(s.findContainingThing(), t, r.getPort(), r.getMessage()) + "\");\n"); } else { //builder.append("if(isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|yellow \" + getName() + \": on " + r.getPort().getName() + "?" + r.getMessage().getName() + " in state " + ((State) i.eContainer()).qualifiedName(":") + "|@\"));\n"); builder.append("printDebug(\"" + ctx.traceInternal(s.findContainingThing(), r.getPort(), r.getMessage()) + "\");\n"); } } if (e != null) { builder.append("final " + ctx.firstToUpper(r.getMessage().getName()) + "MessageType." + ctx.firstToUpper(r.getMessage().getName()) + "Message " + r.getMessage().getName() + " = (" + ctx.firstToUpper(r.getMessage().getName()) + "MessageType." + ctx.firstToUpper(r.getMessage().getName()) + "Message) e;\n"); } else { builder.append("final NullEvent " + r.getMessage().getName() + " = (NullEvent) e;\n"); } if (i.getAction() != null) ctx.getCompiler().getThingActionCompiler().generate(i.getAction(), builder, ctx); builder.append("}\n\n"); } if (i.getGuard() != null || i.getAction() != null || debugProfile.isDebugBehavior()) builder.append("}"); builder.append(");\n"); } } else { //FIXME: lots of duplication here from above if (i instanceof Transition) { Transition t = (Transition) i; builder.append("transitions_" + ((ThingMLElement) s.eContainer()).qname("_") + ".add(new Transition(\""); if (i.getName() != null) builder.append(i.getName()); else builder.append(i.hashCode()); builder.append("\", new NullEventType(), null, state_" + s.qname("_") + ", state_" + t.getTarget().qname("_") + ")"); } else { InternalTransition h = (InternalTransition) i; builder.append("transitions_" + ((ThingMLElement) s.eContainer()).qname("_") + ".add(new InternalTransition(\""); if (i.getName() != null) builder.append(i.getName()); else builder.append(i.hashCode()); builder.append("\", new NullEventType(), null, state_" + s.qname("_") + ")"); } if (i.getGuard() != null || i.getAction() != null || debugProfile.isDebugBehavior()) builder.append("{\n"); if (i.getGuard() != null) { builder.append("@Override\n"); builder.append("public boolean doCheck(final Event e) {\n"); builder.append("final NullEvent ce = (NullEvent) e;\n"); builder.append("return "); ctx.getCompiler().getThingActionCompiler().generate(i.getGuard(), builder, ctx); builder.append(";\n"); builder.append("}\n\n"); } if (i.getAction() != null || debugProfile.isDebugBehavior()) { builder.append("@Override\n"); builder.append("public void doExecute(final Event e) {\n"); if (debugProfile.isDebugBehavior()) { if (i instanceof Transition) { Transition t = (Transition) i; //builder.append("if(isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|yellow \" + getName() + \": auto from " + ((State) t.eContainer()).qualifiedName(":") + " to " + t.getTarget().qualifiedName(":") + "|@\"));\n"); builder.append("printDebug(\"" + ctx.traceTransition(s.findContainingThing(), t) + "\");\n"); } else { //builder.append("if(isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|yellow \" + getName() + \": auto in state " + ((State) i.eContainer()).qualifiedName(":") + "|@\"));\n"); //builder.append("printDebug(\"" + ctx.traceInternal(s.findContainingThing()) + "\");\n"); } } builder.append("final NullEvent ce = (NullEvent) e;\n"); if (i.getAction() != null) ctx.getCompiler().getThingActionCompiler().generate(i.getAction(), builder, ctx); builder.append("}\n\n"); } if (i.getGuard() != null || i.getAction() != null || debugProfile.isDebugBehavior()) builder.append("}"); builder.append(");\n"); } } private void generateHandlerAction(Handler h, StringBuilder builder, Context ctx) { } protected void generateTransition(Transition t, Message msg, Port p, StringBuilder builder, Context ctx) { } protected void generateInternalTransition(InternalTransition t, Message msg, Port p, StringBuilder builder, Context ctx) { } }
package buttons; import java.io.*; import java.awt.Component; import java.awt.FileDialog; import java.util.*; import java.util.prefs.Preferences; import javax.swing.*; /** * This class contains static methods that perform tasks based on which buttons * are pressed. * * @author Curtis Madsen */ public class Buttons { /** * Returns the pathname of the selected file in the file chooser. */ public static String browse(JFrame frame, File file, JTextField text, int i, String approve, int fileType) { Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) { FileDialog fd; if (i == JFileChooser.DIRECTORIES_ONLY) { if (approve.equals("Save") || approve.equals("New")) { fd = new FileDialog(frame, approve, FileDialog.SAVE); } else if (approve.equals("Open")) { fd = new FileDialog(frame, approve, FileDialog.LOAD); } else { fd = new FileDialog(frame, approve); } fd.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { return false; } }); } else { if (approve.equals("Save") || approve.equals("New")) { fd = new FileDialog(frame, approve, FileDialog.SAVE); } else if (approve.equals("Open")) { fd = new FileDialog(frame, approve, FileDialog.LOAD); } else if (approve.equals("Export TSD")) { fd = new FileDialog(frame, approve, FileDialog.SAVE); fd.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".csv") || name.endsWith(".dat") || name.endsWith(".eps") || name.endsWith(".jpg") || name.endsWith(".pdf") || name.endsWith(".png") || name.endsWith(".svg") || name.endsWith(".tsd"); } }); } else if (approve.equals("Export Probability")) { fd = new FileDialog(frame, approve, FileDialog.SAVE); fd.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".eps") || name.endsWith(".jpg") || name.endsWith(".pdf") || name.endsWith(".png") || name.endsWith(".svg"); } }); } else if (approve.equals("Import SBML")) { fd = new FileDialog(frame, approve, FileDialog.LOAD); fd.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".sbml") || name.endsWith(".xml"); } }); } else if (approve.equals("Import Genetic Circuit")) { fd = new FileDialog(frame, approve, FileDialog.LOAD); fd.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".gcm"); } }); } else if (approve.equals("Import")) { fd = new FileDialog(frame, approve, FileDialog.LOAD); fd.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".csv") || name.endsWith(".dat") || name.endsWith(".tsd"); } }); } else { fd = new FileDialog(frame, approve); } } if (file != null) { if (file.isDirectory()) { fd.setDirectory(file.getPath()); } else { fd.setDirectory(file.getPath()); fd.setFile(file.getName()); } } if (i == JFileChooser.DIRECTORIES_ONLY) { System.setProperty("apple.awt.fileDialogForDirectories", "true"); } fd.setVisible(true); if (i == JFileChooser.DIRECTORIES_ONLY) { System.setProperty("apple.awt.fileDialogForDirectories", "false"); } if (fd.getFile() != null) { if (fd.getDirectory() != null) { String selectedFile = fd.getFile(); if (approve.equals("Export TSD")) { if (!selectedFile.endsWith(".csv") && !selectedFile.endsWith(".dat") && !selectedFile.endsWith(".eps") && !selectedFile.endsWith(".jpg") && !selectedFile.endsWith(".pdf") && !selectedFile.endsWith(".png") && !selectedFile.endsWith(".svg") && !selectedFile.endsWith(".tsd")) { selectedFile += ".pdf"; } } else if (approve.equals("Export Probability")) { if (!selectedFile.endsWith(".eps") && !selectedFile.endsWith(".jpg") && !selectedFile.endsWith(".pdf") && !selectedFile.endsWith(".png") && !selectedFile.endsWith(".svg")) { selectedFile += ".pdf"; } } else if (approve.equals("Import SBML")) { if (!selectedFile.endsWith(".sbml") && !selectedFile.endsWith(".xml")) { selectedFile += ".xml"; } } else if (approve.equals("Import Genetic Circuit")) { if (!selectedFile.endsWith(".gcm")) { selectedFile += ".gcm"; } } else if (approve.equals("Import")) { if (!selectedFile.endsWith(".csv") && !selectedFile.endsWith(".dat") && !selectedFile.endsWith(".tsd")) { selectedFile += ".tsd"; } } if (File.separator.equals("\\")) { return fd.getDirectory() + "\\\\" + selectedFile; } else { return fd.getDirectory() + File.separator + selectedFile; } } else { return ""; } } else if (fd.getDirectory() != null) { return ""; // fd.getDirectory(); } else { return ""; } /* * String open; Display display = new Display(); Shell shell = new * Shell(display); shell.setImage(new Image(display, * System.getenv("BIOSIM") + separator + "gui" + separator + "icons" * + separator + "iBioSim.png")); if (i == * JFileChooser.DIRECTORIES_ONLY) { DirectoryDialog dd = null; if * (approve.equals("Save") || approve.equals("New")) { dd = new * DirectoryDialog(shell, SWT.SAVE); dd.setText(approve); } else if * (approve.equals("Open")) { dd = new DirectoryDialog(shell, * SWT.OPEN); dd.setText(approve); } else { dd = new * DirectoryDialog(shell); dd.setText(approve); } if (file != null) * { dd.setFilterPath(file.getPath()); } open = dd.open(); } else { * FileDialog fd = null; if (approve.equals("Save") || * approve.equals("New")) { fd = new FileDialog(shell, SWT.SAVE); * fd.setText(approve); } else if (approve.equals("Open")) { fd = * new FileDialog(shell, SWT.OPEN); fd.setText(approve); } else if * (approve.equals("Export TSD")) { fd = new FileDialog(shell, * SWT.SAVE); fd.setText(approve); fd.setFilterNames(new String[] { * "Comma Separated Values (*.csv)", "Tab Delimited Data * (*.dat)", "Encapsulated Postscript (*.eps)", "JPEG * (*.jpg)", "Portable Document Format (*.pdf)", "Portable Network * Graphics (*.png)", "Scalable Vector Graphics (*.svg)", "Time * Series Data * (*.tsd)" }); fd.setFilterExtensions(new String[] { "*.csv", * "*.dat", "*.eps", "*.jpg", "*.pdf", "*.png", "*.svg", "*.tsd" }); * fd.setFilterIndex(4); } else if * (approve.equals("Export Probability")) { fd = new * FileDialog(shell, SWT.SAVE); fd.setText(approve); * fd.setFilterNames(new String[] { * "Encapsulated Postscript (*.eps)", "JPEG (*.jpg)", * "Portable Document Format (*.pdf)", "Portable Network Graphics * (*.png)", "Scalable Vector Graphics (*.svg)" }); * fd.setFilterExtensions(new String[] { "*.eps", "*.jpg", "*.pdf", * "*.png", "*.svg" }); fd.setFilterIndex(2); } else if * (approve.equals("Import SBML")) { fd = new FileDialog(shell, * SWT.OPEN); fd.setText(approve); fd.setFilterNames(new String[] { * "Systems Biology Markup Language (*.sbml)", "Extensible Markup * Language (*.xml)" }); fd.setFilterExtensions(new String[] { * "*.sbml", "*.xml" }); fd.setFilterIndex(1); } else if * (approve.equals("Import Genetic Circuit")) { fd = new * FileDialog(shell, SWT.OPEN); fd.setText(approve); * fd.setFilterNames(new String[] { "Genetic Circuit Model (*.gcm)" * }); fd.setFilterExtensions(new String[] { "*.gcm" }); } else if * (approve.equals("Import")) { fd = new FileDialog(shell, * SWT.OPEN); fd.setText(approve); fd.setFilterNames(new String[] { * "Comma Separated Values (*.csv)", "Tab Delimited Data * (*.dat)", "Time Series Data * (*.tsd)" }); fd.setFilterExtensions(new String[] { " * *.csv", "*.dat", "*.tsd" }); fd.setFilterIndex(2); } else { fd = * new FileDialog(shell); fd.setText(approve); } if (file != null) { * fd.setFilterPath(file.getParentFile().getPath()); } open = * fd.open(); } shell.dispose(); display.dispose(); if (open != * null) { return open; } else { return ""; } */ } else { String filename = ""; JFileChooser fc = new JFileChooser(); /* * This sets the default directory to the one where BioSim is * executed */ /* * String startDir = System.getProperty("user.dir"); File curDir = * new File(startDir); fc.setCurrentDirectory(curDir); */ ExampleFileFilter csvFilter = new ExampleFileFilter(); csvFilter.addExtension("csv"); csvFilter.setDescription("Comma Separated Values"); ExampleFileFilter datFilter = new ExampleFileFilter(); datFilter.addExtension("dat"); datFilter.setDescription("Tab Delimited Data"); ExampleFileFilter tsdFilter = new ExampleFileFilter(); tsdFilter.addExtension("tsd"); tsdFilter.setDescription("Time Series Data"); ExampleFileFilter epsFilter = new ExampleFileFilter(); epsFilter.addExtension("eps"); epsFilter.setDescription("Encapsulated Postscript"); ExampleFileFilter jpgFilter = new ExampleFileFilter(); jpgFilter.addExtension("jpg"); jpgFilter.setDescription("JPEG"); ExampleFileFilter pdfFilter = new ExampleFileFilter(); pdfFilter.addExtension("pdf"); pdfFilter.setDescription("Portable Document Format"); ExampleFileFilter pngFilter = new ExampleFileFilter(); pngFilter.addExtension("png"); pngFilter.setDescription("Portable Network Graphics"); ExampleFileFilter svgFilter = new ExampleFileFilter(); svgFilter.addExtension("svg"); svgFilter.setDescription("Scalable Vector Graphics"); ExampleFileFilter sbmlFilter = new ExampleFileFilter(); sbmlFilter.addExtension("sbml"); sbmlFilter.setDescription("Systems Biology Markup Language"); ExampleFileFilter xmlFilter = new ExampleFileFilter(); xmlFilter.addExtension("xml"); xmlFilter.setDescription("Extensible Markup Language"); ExampleFileFilter gcmFilter = new ExampleFileFilter(); gcmFilter.addExtension("gcm"); gcmFilter.setDescription("Genetic Circuit Model"); if (file != null) { fc.setSelectedFile(file); } fc.setFileSelectionMode(i); int retValue; if (approve.equals("Save")) { retValue = fc.showSaveDialog(frame); } else if (approve.equals("Open")) { retValue = fc.showOpenDialog(frame); } else if (approve.equals("Export TSD")) { fc.addChoosableFileFilter(csvFilter); fc.addChoosableFileFilter(datFilter); fc.addChoosableFileFilter(epsFilter); fc.addChoosableFileFilter(jpgFilter); fc.addChoosableFileFilter(pdfFilter); fc.addChoosableFileFilter(pngFilter); fc.addChoosableFileFilter(svgFilter); fc.addChoosableFileFilter(tsdFilter); fc.setAcceptAllFileFilterUsed(false); if (fileType == 5) { fc.setFileFilter(csvFilter); } if (fileType == 6) { fc.setFileFilter(datFilter); } if (fileType == 3) { fc.setFileFilter(epsFilter); } if (fileType == 0) { fc.setFileFilter(jpgFilter); } if (fileType == 2) { fc.setFileFilter(pdfFilter); } if (fileType == 1) { fc.setFileFilter(pngFilter); } if (fileType == 4) { fc.setFileFilter(svgFilter); } if (fileType == 7) { fc.setFileFilter(tsdFilter); } retValue = fc.showDialog(frame, approve); } else if (approve.equals("Export Probability")) { fc.addChoosableFileFilter(epsFilter); fc.addChoosableFileFilter(jpgFilter); fc.addChoosableFileFilter(pdfFilter); fc.addChoosableFileFilter(pngFilter); fc.addChoosableFileFilter(svgFilter); fc.setAcceptAllFileFilterUsed(false); if (fileType == 3) { fc.setFileFilter(epsFilter); } if (fileType == 0) { fc.setFileFilter(jpgFilter); } if (fileType == 2) { fc.setFileFilter(pdfFilter); } if (fileType == 1) { fc.setFileFilter(pngFilter); } if (fileType == 4) { fc.setFileFilter(svgFilter); } retValue = fc.showDialog(frame, approve); } else if (approve.equals("Import SBML")) { fc.addChoosableFileFilter(sbmlFilter); fc.addChoosableFileFilter(xmlFilter); fc.setAcceptAllFileFilterUsed(false); fc.setFileFilter(xmlFilter); retValue = fc.showDialog(frame, approve); } else if (approve.equals("Import Genetic Circuit")) { fc.addChoosableFileFilter(gcmFilter); fc.setAcceptAllFileFilterUsed(false); fc.setFileFilter(gcmFilter); retValue = fc.showDialog(frame, approve); } else { retValue = fc.showDialog(frame, approve); } if (retValue == JFileChooser.APPROVE_OPTION) { file = fc.getSelectedFile(); if (text != null) { text.setText(file.getPath()); } filename = file.getPath(); if (approve.equals("Export TSD")) { if ((filename.length() < 4) || (!(filename.substring((filename.length() - 4), filename.length()) .equals(".jpg")) && !(filename.substring((filename.length() - 4), filename .length()).equals(".png")) && !(filename.substring((filename.length() - 4), filename .length()).equals(".pdf")) && !(filename.substring((filename.length() - 4), filename .length()).equals(".eps")) && !(filename.substring((filename.length() - 4), filename .length()).equals(".svg")) && !(filename.substring((filename.length() - 4), filename .length()).equals(".dat")) && !(filename.substring((filename.length() - 4), filename .length()).equals(".tsd")) && !(filename.substring( (filename.length() - 4), filename.length()).equals(".csv")))) { ExampleFileFilter selectedFilter = (ExampleFileFilter) fc.getFileFilter(); if (selectedFilter == jpgFilter) { filename += ".jpg"; } else if (selectedFilter == pngFilter) { filename += ".png"; } else if (selectedFilter == pdfFilter) { filename += ".pdf"; } else if (selectedFilter == epsFilter) { filename += ".eps"; } else if (selectedFilter == svgFilter) { filename += ".svg"; } else if (selectedFilter == datFilter) { filename += ".dat"; } else if (selectedFilter == tsdFilter) { filename += ".tsd"; } else if (selectedFilter == csvFilter) { filename += ".csv"; } } } else if (approve.equals("Export Probability")) { if ((filename.length() < 4) || (!(filename.substring((filename.length() - 4), filename.length()) .equals(".jpg")) && !(filename.substring((filename.length() - 4), filename .length()).equals(".png")) && !(filename.substring((filename.length() - 4), filename .length()).equals(".pdf")) && !(filename.substring((filename.length() - 4), filename .length()).equals(".eps")) && !(filename.substring( (filename.length() - 4), filename.length()).equals(".svg")))) { ExampleFileFilter selectedFilter = (ExampleFileFilter) fc.getFileFilter(); if (selectedFilter == jpgFilter) { filename += ".jpg"; } else if (selectedFilter == pngFilter) { filename += ".png"; } else if (selectedFilter == pdfFilter) { filename += ".pdf"; } else if (selectedFilter == epsFilter) { filename += ".eps"; } else if (selectedFilter == svgFilter) { filename += ".svg"; } } } } return filename; } } /** * Removes the selected values of the given JList from the given list and * updates the JList. */ public static Object[] remove(JList currentList, Object[] list) { Object[] removeSelected = currentList.getSelectedValues(); int[] select = new int[list.length]; for (int i = 0; i < list.length; i++) { select[i] = i; } currentList.setSelectedIndices(select); Object[] getAll = currentList.getSelectedValues(); currentList.removeSelectionInterval(0, list.length - 1); ArrayList<Object> remove = new ArrayList<Object>(); for (int i = 0; i < getAll.length; i++) { remove.add(getAll[i]); } for (int i = 0; i < removeSelected.length; i++) { remove.remove(removeSelected[i]); } String[] keep = new String[remove.size()]; for (int i = 0; i < remove.size(); i++) { keep[i] = (String) remove.get(i); } currentList.setListData(keep); list = keep; return list; } /** * Removes the selected values of the given JList from the given list and * updates the JList. */ public static void remove(JList currentList) { Object[] list = new Object[currentList.getModel().getSize()]; for (int i = 0; i < currentList.getModel().getSize(); i++) { list[i] = currentList.getModel().getElementAt(i); } Object[] removeSelected = currentList.getSelectedValues(); int[] select = new int[list.length]; for (int i = 0; i < list.length; i++) { select[i] = i; } currentList.setSelectedIndices(select); Object[] getAll = currentList.getSelectedValues(); currentList.removeSelectionInterval(0, list.length - 1); ArrayList<Object> remove = new ArrayList<Object>(); for (int i = 0; i < getAll.length; i++) { remove.add(getAll[i]); } for (int i = 0; i < removeSelected.length; i++) { remove.remove(removeSelected[i]); } String[] keep = new String[remove.size()]; for (int i = 0; i < remove.size(); i++) { keep[i] = (String) remove.get(i); } currentList.setListData(keep); list = keep; } /** * Adds a new item to a JList */ public static void add(JList currentList, Object newItem) { Object[] list = new Object[currentList.getModel().getSize() + 1]; int addAfter = currentList.getSelectedIndex(); for (int i = 0; i <= currentList.getModel().getSize(); i++) { if (i <= addAfter) { list[i] = currentList.getModel().getElementAt(i); } else if (i == (addAfter + 1)) { list[i] = newItem; } else { list[i] = currentList.getModel().getElementAt(i - 1); } } currentList.setListData(list); } /** * Adds the selected values in the add JList to the list JList. Stores all * these values into the currentList array and returns this array. */ public static Object[] add(Object[] currentList, JList list, JList add, boolean isTermCond, JTextField amountTerm, JRadioButton ge, JRadioButton gt, JRadioButton eq, JRadioButton lt, JRadioButton le, Component component) { int[] select = new int[currentList.length]; for (int i = 0; i < currentList.length; i++) { select[i] = i; } list.setSelectedIndices(select); currentList = list.getSelectedValues(); Object[] newSelected = add.getSelectedValues(); if (isTermCond) { for (int i = 0; i < newSelected.length; i++) { String temp = (String) newSelected[i]; double amount = 0.0; try { amount = Double.parseDouble(amountTerm.getText().trim()); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Must Enter A Real Number Into The Termination Condition Field.", "Error", JOptionPane.ERROR_MESSAGE); return currentList; } if (ge.isSelected()) { newSelected[i] = temp + ".amount.ge." + amount; } else if (gt.isSelected()) { newSelected[i] = temp + ".amount.gt." + amount; } else if (eq.isSelected()) { newSelected[i] = temp + ".amount.eq." + amount; } else if (lt.isSelected()) { newSelected[i] = temp + ".amount.lt." + amount; } else if (le.isSelected()) { newSelected[i] = temp + ".amount.le." + amount; } } } Object[] temp = currentList; int newLength = temp.length; for (int i = 0; i < newSelected.length; i++) { int j = 0; for (j = 0; j < temp.length; j++) { if (temp[j].equals(newSelected[i])) { break; } } if (j == temp.length) newLength++; } currentList = new Object[newLength]; for (int i = 0; i < temp.length; i++) { currentList[i] = temp[i]; } int num = temp.length; for (int i = 0; i < newSelected.length; i++) { int j = 0; for (j = 0; j < temp.length; j++) if (temp[j].equals(newSelected[i])) break; if (j == temp.length) { currentList[num] = newSelected[i]; num++; } } sort(currentList); list.setListData(currentList); return currentList; } /** * Returns a list of all the objects in the given JList. */ public static String[] getList(Object[] size, JList objects) { String[] list; if (size.length == 0) { list = new String[0]; } else { int[] select = new int[size.length]; for (int i = 0; i < size.length; i++) { select[i] = i; } objects.setSelectedIndices(select); size = objects.getSelectedValues(); list = new String[size.length]; for (int i = 0; i < size.length; i++) { list[i] = (String) size[i]; } } return list; } private static void sort(Object[] sort) { int i, j; String index; for (i = 1; i < sort.length; i++) { index = (String) sort[i]; j = i; while ((j > 0) && ((String) sort[j - 1]).compareToIgnoreCase(index) > 0) { sort[j] = sort[j - 1]; j = j - 1; } sort[j] = index; } } }
package com.applovin.mediation; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.applovin.nativeAds.AppLovinNativeAd; import com.google.android.gms.ads.formats.NativeAd; import com.google.android.gms.ads.mediation.NativeAppInstallAdMapper; import java.util.ArrayList; /** * A {@link NativeAppInstallAdMapper} used to map an AppLovin Native ad to Google Native App Install * ad. */ class AppLovinNativeAdMapper extends NativeAppInstallAdMapper { /** AppLovin native ad instance. */ private AppLovinNativeAd mNativeAd; AppLovinNativeAdMapper(AppLovinNativeAd nativeAd, Context context) { mNativeAd = nativeAd; setHeadline(nativeAd.getTitle()); setBody(nativeAd.getDescriptionText()); setCallToAction(nativeAd.getCtaText()); ImageView mediaView = new ImageView(context); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); mediaView.setLayoutParams(layoutParams); ArrayList<NativeAd.Image> images = new ArrayList<>(1); Uri imageUri = Uri.parse(nativeAd.getImageUrl()); Drawable imageDrawable = Drawable.createFromPath(imageUri.getPath()); Uri iconUri = Uri.parse(nativeAd.getIconUrl()); Drawable iconDrawable = Drawable.createFromPath(iconUri.getPath()); AppLovinNativeAdImage image = new AppLovinNativeAdImage(imageUri, imageDrawable); AppLovinNativeAdImage icon = new AppLovinNativeAdImage(iconUri, iconDrawable); images.add(image); setImages(images); setIcon(icon); // AppLovin SDK does not have an AdChoices icon. setAdChoicesContent(null); mediaView.setImageDrawable(imageDrawable); setMediaView(mediaView); setStarRating(nativeAd.getStarRating()); Bundle extraAssets = new Bundle(); extraAssets.putLong(AppLovinNativeAdapter.KEY_EXTRA_AD_ID, nativeAd.getAdId()); extraAssets.putString(AppLovinNativeAdapter.KEY_EXTRA_CAPTION_TEXT, nativeAd.getCaptionText()); setExtras(extraAssets); setOverrideClickHandling(false); setOverrideImpressionRecording(false); } @Override public void recordImpression() { mNativeAd.trackImpression(); } @Override public void handleClick(View view) { mNativeAd.launchClickTarget(view.getContext()); } }
package reb2sac; import java.io.*; import java.util.*; import java.util.prefs.Preferences; import java.util.regex.Pattern; import java.awt.*; import java.awt.event.*; import javax.swing.*; import org.sbml.libsbml.*; import sbmleditor.*; import gcm2sbml.gui.GCM2SBMLEditor; import graph.*; import biomodelsim.*; import buttons.*; /** * This class creates a GUI for the reb2sac program. It implements the * ActionListener class, the KeyListener class, the MouseListener class, and the * Runnable class. This allows the GUI to perform actions when buttons are * pressed, text is entered into a field, or the mouse is clicked. It also * allows this class to execute many reb2sac programs at the same time on * different threads. * * @author Curtis Madsen */ public class Reb2Sac extends JPanel implements ActionListener, Runnable, MouseListener { private static final long serialVersionUID = 3181014495993143825L; private JTextField amountTerm; // Amount for termination condition /* * Buttons for adding and removing conditions and species */ private JButton addIntSpecies, removeIntSpecies, addTermCond, removeTermCond, clearIntSpecies, clearTermCond; /* * Radio Buttons that represent the different abstractions */ private JRadioButton none, abstraction, nary, ODE, monteCarlo, markov; private JRadioButton sbml, dot, xhtml, lhpn; // Radio Buttons output option /* * Radio Buttons for termination conditions */ private JRadioButton ge, gt, eq, le, lt; private JButton run, save; // The save and run button /* * Added interesting species and termination conditions */ private JList species, terminations; private JList intSpecies, termCond; // List of species in sbml file private JLabel spLabel, speciesLabel; // Labels for interesting species /* * Text fields for changes in the abstraction */ private JTextField limit, interval, step, absErr, seed, runs, fileStem; private JComboBox intervalLabel; /* * Labels for the changes in the abstraction */ private JLabel limitLabel, stepLabel, errorLabel, seedLabel, runsLabel, fileStemLabel; /* * Description of selected simulator */ private JLabel description, explanation; /* * List of interesting species */ private Object[] interestingSpecies = new Object[0]; private Object[] allSpecies = new Object[0]; /* * List of species with termination conditions */ private Object[] termConditions = new Object[0]; private JComboBox simulators; // Combo Box for possible simulators private JLabel simulatorsLabel; // Label for possible simulators private JTextField rapid1, rapid2, qssa, maxCon; // advanced options /* * advanced labels */ private JLabel rapidLabel1, rapidLabel2, qssaLabel, maxConLabel; private JCheckBox usingSSA, usingSAD; // check box for using ssa private JComboBox availSpecies; // species for SSA private JList ssa, sad; // list of ssa private JTextField time; // time for ssa private JTextField TCid; // id for sad private JTextField desc; // description for sad private JTextField cond; // condition for sad private JTextField ssaModNum; // number that the ssa is changed by private JComboBox ssaMod; // amount to mod the ssa species by private JButton addSSA, editSSA, removeSSA; // Buttons for editing SSA private JButton addSAD, editSAD, removeSAD; // Buttons for editing SAD private JButton newSSA; // Buttons for SSA file private JButton newSAD; // Buttons for SAD file private JLabel timeLabel; // Label for SSA private JLabel idLabel; // ID label for SAD private JLabel descLabel; // Description label for SAD private JLabel condLabel; // Condition label for SAD private Object[] ssaList, sadList; // array for ssa/sad JList private JList properties; // JList for properties private JTextField prop, value; // text areas for properties private JButton addProp, editProp, removeProp, newProp; // buttons for // properties private Object[] props; // array for properties JList private String sbmlFile, root; // sbml file and root directory private BioSim biomodelsim; // reference to the tstubd class private String simName; // simulation id private Log log; // the log private JTabbedPane simTab; // the simulation tab private SBML_Editor sbmlEditor; // sbml editor private GCM2SBMLEditor gcmEditor; // gcm editor private JRadioButton overwrite, append; private JRadioButton amounts, concentrations; private JLabel choose3; private JLabel report; private boolean runFiles; private String separator; private String sbmlProp; private boolean change; private ArrayList<JFrame> frames; private Pattern stemPat = Pattern.compile("([a-zA-Z]|[0-9]|_)*"); private JPanel propertiesPanel, advanced; /** * This is the constructor for the GUI. It initializes all the input fields, * puts them on panels, adds the panels to the frame, and then displays the * GUI. * * @param modelFile */ public Reb2Sac(String sbmlFile, String sbmlProp, String root, BioSim biomodelsim, String simName, Log log, JTabbedPane simTab, String open, String modelFile) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } this.biomodelsim = biomodelsim; this.sbmlFile = sbmlFile; this.sbmlProp = sbmlProp; this.root = root; this.simName = simName; this.log = log; this.simTab = simTab; change = false; frames = new ArrayList<JFrame>(); // Creates the input fields for the changes in abstraction Preferences biosimrc = Preferences.userRoot(); String[] odeSimulators = new String[6]; odeSimulators[0] = "euler"; odeSimulators[1] = "gear1"; odeSimulators[2] = "gear2"; odeSimulators[3] = "rk4imp"; odeSimulators[4] = "rk8pd"; odeSimulators[5] = "rkf45"; explanation = new JLabel("Description Of Selected Simulator: "); description = new JLabel("Embedded Runge-Kutta-Fehlberg (4, 5) method"); simulators = new JComboBox(odeSimulators); simulators.setSelectedItem("rkf45"); simulators.addActionListener(this); limit = new JTextField(biosimrc.get("biosim.sim.limit", ""), 39); interval = new JTextField(biosimrc.get("biosim.sim.interval", ""), 15); step = new JTextField(biosimrc.get("biosim.sim.step", ""), 15); absErr = new JTextField(biosimrc.get("biosim.sim.error", ""), 15); int next = 1; String filename = "sim" + next; while (new File(root + separator + filename).exists()) { next++; filename = "sim" + next; } // dir = new JTextField(filename, 15); seed = new JTextField(biosimrc.get("biosim.sim.seed", ""), 15); runs = new JTextField(biosimrc.get("biosim.sim.runs", ""), 15); simulatorsLabel = new JLabel("Possible Simulators/Analyzers:"); limitLabel = new JLabel("Time Limit:"); String[] intervalChoices = { "Print Interval", "Number Of Steps" }; intervalLabel = new JComboBox(intervalChoices); intervalLabel.setSelectedItem(biosimrc.get("biosim.sim.useInterval", "")); stepLabel = new JLabel("Maximum Time Step:"); errorLabel = new JLabel("Absolute Error:"); seedLabel = new JLabel("Random Seed:"); runsLabel = new JLabel("Runs:"); fileStem = new JTextField("", 15); fileStemLabel = new JLabel("Simulation ID:"); JPanel inputHolder = new JPanel(new BorderLayout()); JPanel inputHolderLeft = new JPanel(new GridLayout(9, 1)); JPanel inputHolderRight = new JPanel(new GridLayout(9, 1)); inputHolderLeft.add(simulatorsLabel); inputHolderRight.add(simulators); inputHolderLeft.add(explanation); inputHolderRight.add(description); inputHolderLeft.add(limitLabel); inputHolderRight.add(limit); inputHolderLeft.add(intervalLabel); inputHolderRight.add(interval); inputHolderLeft.add(stepLabel); inputHolderRight.add(step); inputHolderLeft.add(errorLabel); inputHolderRight.add(absErr); inputHolderLeft.add(seedLabel); inputHolderRight.add(seed); inputHolderLeft.add(runsLabel); inputHolderRight.add(runs); inputHolderLeft.add(fileStemLabel); inputHolderRight.add(fileStem); inputHolder.add(inputHolderLeft, "West"); inputHolder.add(inputHolderRight, "Center"); JPanel topInputHolder = new JPanel(); topInputHolder.add(inputHolder); // Creates the interesting species JList intSpecies = new JList(); species = new JList(); spLabel = new JLabel("Available Species:"); speciesLabel = new JLabel("Interesting Species:"); JPanel speciesHolder = new JPanel(new BorderLayout()); JPanel listOfSpeciesLabelHolder = new JPanel(new GridLayout(1, 2)); JPanel listOfSpeciesHolder = new JPanel(new GridLayout(1, 2)); JScrollPane scroll = new JScrollPane(); JScrollPane scroll1 = new JScrollPane(); scroll.setMinimumSize(new Dimension(260, 200)); scroll.setPreferredSize(new Dimension(276, 132)); scroll.setViewportView(species); scroll1.setMinimumSize(new Dimension(260, 200)); scroll1.setPreferredSize(new Dimension(276, 132)); scroll1.setViewportView(intSpecies); addIntSpecies = new JButton("Add Species"); removeIntSpecies = new JButton("Remove Species"); clearIntSpecies = new JButton("Clear Species"); listOfSpeciesLabelHolder.add(spLabel); listOfSpeciesHolder.add(scroll1); listOfSpeciesLabelHolder.add(speciesLabel); listOfSpeciesHolder.add(scroll); speciesHolder.add(listOfSpeciesLabelHolder, "North"); speciesHolder.add(listOfSpeciesHolder, "Center"); JPanel buttonHolder = new JPanel(); buttonHolder.add(addIntSpecies); buttonHolder.add(removeIntSpecies); buttonHolder.add(clearIntSpecies); speciesHolder.add(buttonHolder, "South"); intSpecies.setEnabled(false); species.setEnabled(false); intSpecies.addMouseListener(this); species.addMouseListener(this); spLabel.setEnabled(false); speciesLabel.setEnabled(false); addIntSpecies.setEnabled(false); removeIntSpecies.setEnabled(false); addIntSpecies.addActionListener(this); removeIntSpecies.addActionListener(this); clearIntSpecies.setEnabled(false); clearIntSpecies.addActionListener(this); // Creates some abstraction options JPanel advancedGrid = new JPanel(new GridLayout(8, 2)); advanced = new JPanel(new GridLayout(2, 1)); JPanel rapidSpace1 = new JPanel(); JPanel rapidSpace2 = new JPanel(); JPanel rapidSpace3 = new JPanel(); JPanel rapidSpace4 = new JPanel(); JPanel qssaSpace1 = new JPanel(); JPanel qssaSpace2 = new JPanel(); JPanel maxConSpace1 = new JPanel(); JPanel maxConSpace2 = new JPanel(); rapidLabel1 = new JLabel("Rapid Equilibrium Condition 1:"); rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", ""), 15); rapidLabel2 = new JLabel("Rapid Equilibrium Condition 2:"); rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", ""), 15); qssaLabel = new JLabel("QSSA Condition:"); qssa = new JTextField(biosimrc.get("biosim.sim.qssa", ""), 15); maxConLabel = new JLabel("Max Concentration Threshold:"); maxCon = new JTextField(biosimrc.get("biosim.sim.concentration", ""), 15); maxConLabel.setEnabled(false); maxCon.setEnabled(false); qssaLabel.setEnabled(false); qssa.setEnabled(false); rapidLabel1.setEnabled(false); rapid1.setEnabled(false); rapidLabel2.setEnabled(false); rapid2.setEnabled(false); advancedGrid.add(rapidLabel1); advancedGrid.add(rapid1); advancedGrid.add(rapidSpace1); advancedGrid.add(rapidSpace2); advancedGrid.add(rapidLabel2); advancedGrid.add(rapid2); advancedGrid.add(rapidSpace3); advancedGrid.add(rapidSpace4); advancedGrid.add(qssaLabel); advancedGrid.add(qssa); advancedGrid.add(qssaSpace1); advancedGrid.add(qssaSpace2); advancedGrid.add(maxConLabel); advancedGrid.add(maxCon); advancedGrid.add(maxConSpace1); advancedGrid.add(maxConSpace2); advanced.add(advancedGrid); // JPanel space = new JPanel(); // advanced.add(space); advanced.add(speciesHolder); // Sets up the radio buttons for Abstraction and Nary JLabel choose = new JLabel("Abstraction:"); none = new JRadioButton("None"); abstraction = new JRadioButton("Abstraction"); nary = new JRadioButton("Logical Abstraction"); ButtonGroup abs = new ButtonGroup(); abs.add(none); abs.add(abstraction); abs.add(nary); none.setSelected(true); JPanel topPanel = new JPanel(new BorderLayout()); JPanel backgroundPanel = new JPanel(); JLabel backgroundLabel = new JLabel("Model File:"); String[] tempArray = modelFile.split(separator); JTextField backgroundField = new JTextField(tempArray[tempArray.length - 1]); backgroundField.setEditable(false); backgroundPanel.add(backgroundLabel); backgroundPanel.add(backgroundField); JPanel absAndNaryPanel = new JPanel(); absAndNaryPanel.add(choose); absAndNaryPanel.add(none); absAndNaryPanel.add(abstraction); absAndNaryPanel.add(nary); topPanel.add(backgroundPanel, BorderLayout.NORTH); topPanel.add(absAndNaryPanel, BorderLayout.SOUTH); none.addActionListener(this); abstraction.addActionListener(this); nary.addActionListener(this); // Sets up the radio buttons for ODE, Monte Carlo, and Markov JLabel choose2 = new JLabel("Simulation Type:"); ODE = new JRadioButton("ODE"); monteCarlo = new JRadioButton("Monte Carlo"); markov = new JRadioButton("Markov"); ODE.setSelected(true); markov.setEnabled(false); seed.setEnabled(true); seedLabel.setEnabled(true); runs.setEnabled(true); runsLabel.setEnabled(true); fileStem.setEnabled(true); fileStemLabel.setEnabled(true); step.setEnabled(true); stepLabel.setEnabled(true); absErr.setEnabled(true); errorLabel.setEnabled(true); JPanel odeMonteAndMarkovPanel = new JPanel(); odeMonteAndMarkovPanel.add(choose2); odeMonteAndMarkovPanel.add(ODE); odeMonteAndMarkovPanel.add(monteCarlo); odeMonteAndMarkovPanel.add(markov); ODE.addActionListener(this); monteCarlo.addActionListener(this); markov.addActionListener(this); // Sets up the radio buttons for output option sbml = new JRadioButton("SBML"); dot = new JRadioButton("Network"); xhtml = new JRadioButton("Browser"); lhpn = new JRadioButton("LHPN"); sbml.setSelected(true); odeMonteAndMarkovPanel.add(sbml); odeMonteAndMarkovPanel.add(dot); odeMonteAndMarkovPanel.add(xhtml); odeMonteAndMarkovPanel.add(lhpn); sbml.addActionListener(this); dot.addActionListener(this); xhtml.addActionListener(this); lhpn.addActionListener(this); ButtonGroup sim = new ButtonGroup(); sim.add(ODE); sim.add(monteCarlo); sim.add(markov); sim.add(sbml); sim.add(dot); sim.add(xhtml); sim.add(lhpn); report = new JLabel("Report:"); amounts = new JRadioButton("Amounts"); concentrations = new JRadioButton("Concentrations"); amounts.setSelected(true); amounts.setEnabled(true); concentrations.setEnabled(true); JPanel reportPanel = new JPanel(); reportPanel.add(report); reportPanel.add(amounts); reportPanel.add(concentrations); amounts.addActionListener(this); concentrations.addActionListener(this); ButtonGroup rept = new ButtonGroup(); rept.add(amounts); rept.add(concentrations); choose3 = new JLabel("Choose One:"); overwrite = new JRadioButton("Overwrite"); append = new JRadioButton("Append"); overwrite.setSelected(true); overwrite.setEnabled(true); append.setEnabled(true); choose3.setEnabled(true); JPanel overwritePanel = new JPanel(); overwritePanel.add(choose3); overwritePanel.add(overwrite); overwritePanel.add(append); overwrite.addActionListener(this); append.addActionListener(this); ButtonGroup over = new ButtonGroup(); over.add(overwrite); over.add(append); // Puts all the radio buttons in a panel JPanel radioButtonPanel = new JPanel(new BorderLayout()); radioButtonPanel.add(topPanel, "North"); radioButtonPanel.add(odeMonteAndMarkovPanel, "Center"); JPanel bottomPanel = new JPanel(new BorderLayout()); bottomPanel.add(overwritePanel, "North"); bottomPanel.add(reportPanel, "South"); radioButtonPanel.add(bottomPanel, "South"); // Creates the main tabbed panel JPanel mainTabbedPanel = new JPanel(new BorderLayout()); mainTabbedPanel.add(topInputHolder, "Center"); mainTabbedPanel.add(radioButtonPanel, "North"); // Creates the run button run = new JButton("Save and Run"); save = new JButton("Save Parameters"); JPanel runHolder = new JPanel(); runHolder.add(run); run.addActionListener(this); run.setMnemonic(KeyEvent.VK_R); runHolder.add(save); save.addActionListener(this); save.setMnemonic(KeyEvent.VK_S); // Creates the termination conditions tab termCond = new JList(); terminations = new JList(); addTermCond = new JButton("Add Condition"); removeTermCond = new JButton("Remove Condition"); clearTermCond = new JButton("Clear Conditions"); addTermCond.addActionListener(this); removeTermCond.addActionListener(this); clearTermCond.addActionListener(this); amountTerm = new JTextField("0.0", 15); JLabel spLabel2 = new JLabel("Available Species:"); JLabel specLabel = new JLabel("Termination Conditions:"); JScrollPane scroll2 = new JScrollPane(); scroll2.setMinimumSize(new Dimension(260, 200)); scroll2.setPreferredSize(new Dimension(276, 132)); scroll2.setViewportView(termCond); JScrollPane scroll3 = new JScrollPane(); scroll3.setMinimumSize(new Dimension(260, 200)); scroll3.setPreferredSize(new Dimension(276, 132)); scroll3.setViewportView(terminations); JPanel mainTermCond = new JPanel(new BorderLayout()); JPanel termCondPanel = new JPanel(new GridLayout(1, 2)); JPanel speciesPanel = new JPanel(new GridLayout(1, 2)); ge = new JRadioButton(">="); gt = new JRadioButton(">"); eq = new JRadioButton("="); le = new JRadioButton("<="); lt = new JRadioButton("<"); ButtonGroup condition = new ButtonGroup(); condition.add(gt); condition.add(ge); condition.add(eq); condition.add(le); condition.add(lt); gt.setSelected(true); JPanel termOptionsPanel = new JPanel(new BorderLayout()); JPanel termSelectionPanel = new JPanel(); JPanel termButtonPanel = new JPanel(); termSelectionPanel.add(gt); termSelectionPanel.add(ge); termSelectionPanel.add(eq); termSelectionPanel.add(le); termSelectionPanel.add(lt); termSelectionPanel.add(amountTerm); termButtonPanel.add(addTermCond); termButtonPanel.add(removeTermCond); termButtonPanel.add(clearTermCond); termOptionsPanel.add(termSelectionPanel, "North"); termOptionsPanel.add(termButtonPanel, "South"); speciesPanel.add(spLabel2); speciesPanel.add(specLabel); termCondPanel.add(scroll2); termCondPanel.add(scroll3); termCond.addMouseListener(this); terminations.addMouseListener(this); mainTermCond.add(speciesPanel, "North"); mainTermCond.add(termCondPanel, "Center"); mainTermCond.add(termOptionsPanel, "South"); JPanel sadTermCondPanel = new JPanel(new BorderLayout()); // sadFile = new JTextArea(); // JScrollPane scroll9 = new JScrollPane(); // scroll9.setViewportView(sadFile); // sadTermCondPanel.add(scroll9, "Center"); newSAD = new JButton("Clear Conditions"); newSAD.setEnabled(false); newSAD.addActionListener(this); usingSAD = new JCheckBox("Use Termination Conditions"); usingSAD.setSelected(false); usingSAD.addActionListener(this); sad = new JList(); sad.setEnabled(false); sad.addMouseListener(this); sadList = new Object[0]; JScrollPane scroll9 = new JScrollPane(); scroll9.setMinimumSize(new Dimension(260, 200)); scroll9.setPreferredSize(new Dimension(276, 132)); scroll9.setViewportView(sad); JPanel sadAddPanel = new JPanel(new BorderLayout()); JPanel sadAddPanel1 = new JPanel(); JPanel sadAddPanel3 = new JPanel(); idLabel = new JLabel("ID: "); idLabel.setEnabled(false); TCid = new JTextField(10); TCid.setEnabled(false); descLabel = new JLabel("Description: "); descLabel.setEnabled(false); desc = new JTextField(20); desc.setEnabled(false); condLabel = new JLabel("Condition: "); condLabel.setEnabled(false); cond = new JTextField(35); cond.setEnabled(false); sadAddPanel1.add(idLabel); sadAddPanel1.add(TCid); sadAddPanel1.add(descLabel); sadAddPanel1.add(desc); sadAddPanel1.add(condLabel); sadAddPanel1.add(cond); addSAD = new JButton("Add Condition"); addSAD.setEnabled(false); addSAD.addActionListener(this); editSAD = new JButton("Edit Condition"); editSAD.setEnabled(false); editSAD.addActionListener(this); removeSAD = new JButton("Remove Condition"); removeSAD.setEnabled(false); removeSAD.addActionListener(this); sadAddPanel3.add(addSAD); sadAddPanel3.add(editSAD); sadAddPanel3.add(removeSAD); sadAddPanel3.add(newSAD); sadAddPanel.add(sadAddPanel1, "North"); // sadAddPanel.add(sadAddPanel2, "Center"); sadAddPanel.add(sadAddPanel3, "South"); sadTermCondPanel.add(usingSAD, "North"); sadTermCondPanel.add(scroll9, "Center"); sadTermCondPanel.add(sadAddPanel, "South"); if (new File(root + separator + simName + separator + "termCond.sad").exists()) { try { BufferedReader input = new BufferedReader(new FileReader(root + separator + simName + separator + "termCond.sad")); // + load.getProperty("computation.analysis.sad.path"))); String read = input.readLine(); while (read != null) { String[] TCid = read.split(" "); String desc = input.readLine(); String cond = input.readLine(); String add = TCid[1] + "; " + desc.substring(8, desc.length() - 2) + "; " + cond.substring(7, cond.indexOf(';')); JList addSAD = new JList(); Object[] adding = { add }; addSAD.setListData(adding); addSAD.setSelectedIndex(0); sadList = Buttons.add(sadList, sad, addSAD, false, null, null, null, null, null, null, this); // sadFile.append("" + (char) read); read = input.readLine(); read = input.readLine(); } sad.setListData(sadList); input.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to load termination condition file!", "Error Loading File", JOptionPane.ERROR_MESSAGE); } } // Creates the ssa with user defined species level update feature tab JPanel ssaPanel = new JPanel(new BorderLayout()); newSSA = new JButton("Clear Data Points"); newSSA.setEnabled(false); newSSA.addActionListener(this); usingSSA = new JCheckBox("Use User Defined Data"); usingSSA.setSelected(false); usingSSA.addActionListener(this); ssa = new JList(); ssa.setEnabled(false); ssa.addMouseListener(this); ssaList = new Object[0]; JScrollPane scroll5 = new JScrollPane(); scroll5.setMinimumSize(new Dimension(260, 200)); scroll5.setPreferredSize(new Dimension(276, 132)); scroll5.setViewportView(ssa); JPanel ssaAddPanel = new JPanel(new BorderLayout()); JPanel ssaAddPanel1 = new JPanel(); JPanel ssaAddPanel2 = new JPanel(); JPanel ssaAddPanel3 = new JPanel(); timeLabel = new JLabel("At time step: "); timeLabel.setEnabled(false); time = new JTextField(15); time.setEnabled(false); availSpecies = new JComboBox(); availSpecies.setEnabled(false); String[] mod = new String[5]; mod[0] = "goes to"; mod[1] = "is added by"; mod[2] = "is subtracted by"; mod[3] = "is multiplied by"; mod[4] = "is divided by"; ssaMod = new JComboBox(mod); ssaMod.setEnabled(false); ssaModNum = new JTextField(15); ssaModNum.setEnabled(false); ssaAddPanel1.add(timeLabel); ssaAddPanel1.add(time); ssaAddPanel1.add(availSpecies); ssaAddPanel2.add(ssaMod); ssaAddPanel2.add(ssaModNum); addSSA = new JButton("Add Data Point"); addSSA.setEnabled(false); addSSA.addActionListener(this); editSSA = new JButton("Edit Data Point"); editSSA.setEnabled(false); editSSA.addActionListener(this); removeSSA = new JButton("Remove Data Point"); removeSSA.setEnabled(false); removeSSA.addActionListener(this); ssaAddPanel3.add(addSSA); ssaAddPanel3.add(editSSA); ssaAddPanel3.add(removeSSA); ssaAddPanel3.add(newSSA); ssaAddPanel.add(ssaAddPanel1, "North"); ssaAddPanel.add(ssaAddPanel2, "Center"); ssaAddPanel.add(ssaAddPanel3, "South"); ssaPanel.add(usingSSA, "North"); ssaPanel.add(scroll5, "Center"); ssaPanel.add(ssaAddPanel, "South"); if (new File(root + separator + simName + separator + "user-defined.dat").exists()) { String getData = ""; try { Scanner scan = new Scanner(new File(root + separator + simName + separator + "user-defined.dat")); while (scan.hasNextLine()) { String get = scan.nextLine(); if (get.split(" ").length == 3) { if (scan.hasNextLine()) { getData += get + "\n"; } else { getData += get; } } else { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to load user defined file!", "Error Loading File", JOptionPane.ERROR_MESSAGE); return; } } } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to load user defined file!", "Error Loading File", JOptionPane.ERROR_MESSAGE); } if (!getData.equals("")) { ssaList = getData.split("\n"); ArrayList<String> sortName = new ArrayList<String>(); for (int i = 0; i < ssaList.length; i++) { sortName.add(((String) ssaList[i]).split(" ")[1]); } int in, out; for (out = 1; out < sortName.size(); out++) { String temp = sortName.get(out); String temp2 = (String) ssaList[out]; in = out; while (in > 0 && sortName.get(in - 1).compareToIgnoreCase(temp) > 0) { sortName.set(in, sortName.get(in - 1)); ssaList[in] = ssaList[in - 1]; --in; } sortName.set(in, temp); ssaList[in] = temp2; } ArrayList<Double> sort = new ArrayList<Double>(); for (int i = 0; i < ssaList.length; i++) { sort.add(Double.parseDouble(((String) ssaList[i]).split(" ")[0])); } for (out = 1; out < sort.size(); out++) { double temp = sort.get(out); String temp2 = (String) ssaList[out]; in = out; while (in > 0 && sort.get(in - 1) > temp) { sort.set(in, sort.get(in - 1)); ssaList[in] = ssaList[in - 1]; --in; } sort.set(in, temp); ssaList[in] = temp2; } } else { ssaList = new Object[0]; } ssa.setListData(ssaList); ssa.setEnabled(true); timeLabel.setEnabled(true); time.setEnabled(true); availSpecies.setEnabled(true); ssaMod.setEnabled(true); ssaModNum.setEnabled(true); addSSA.setEnabled(true); editSSA.setEnabled(true); removeSSA.setEnabled(true); } // Creates tab for adding properties propertiesPanel = new JPanel(new BorderLayout()); JPanel propertiesPanel1 = new JPanel(new BorderLayout()); JPanel propertiesPanel2 = new JPanel(new BorderLayout()); JPanel propertiesInput = new JPanel(); JPanel propertiesButtons = new JPanel(); // JLabel propertiesLabel = new JLabel("Properties To Add:"); JLabel propLabel = new JLabel("Option:"); JLabel valueLabel = new JLabel("Value:"); properties = new JList(); properties.addMouseListener(this); JScrollPane scroll6 = new JScrollPane(); scroll6.setMinimumSize(new Dimension(260, 200)); scroll6.setPreferredSize(new Dimension(276, 132)); scroll6.setViewportView(properties); props = new Object[0]; prop = new JTextField(20); value = new JTextField(20); addProp = new JButton("Add Option"); addProp.addActionListener(this); editProp = new JButton("Edit Option"); editProp.addActionListener(this); removeProp = new JButton("Remove Option"); removeProp.addActionListener(this); newProp = new JButton("Clear Options"); newProp.addActionListener(this); propertiesInput.add(propLabel); propertiesInput.add(prop); propertiesInput.add(valueLabel); propertiesInput.add(value); propertiesButtons.add(addProp); propertiesButtons.add(editProp); propertiesButtons.add(removeProp); propertiesButtons.add(newProp); propertiesPanel2.add(propertiesInput, "Center"); propertiesPanel2.add(propertiesButtons, "South"); // propertiesPanel1.add(propertiesLabel, "North"); propertiesPanel1.add(scroll6, "Center"); propertiesPanel.add(propertiesPanel1, "Center"); propertiesPanel.add(propertiesPanel2, "South"); // Creates the tabs and adds them to the main panel // JTabbedPane tab = new JTabbedPane(); // tab.addTab("Simulation Options", mainTabbedPanel); // tab.addTab("Interesting Species", speciesHolder); // tab.addTab("User Defined Data", ssaPanel); // tab.addTab("Abstraction Options", advanced); // tab.addTab("Termination Conditions", mainTermCond); // tab.addTab("Termination Conditions", sadTermCondPanel); // tab.addTab("Advanced Options", propertiesPanel); this.setLayout(new BorderLayout()); this.add(mainTabbedPanel, "Center"); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // runHolder, null); // splitPane.setDividerSize(0); // this.add(splitPane, "South"); SBMLDocument document = BioSim.readSBML(sbmlFile); Model model = document.getModel(); ArrayList<String> listOfSpecs = new ArrayList<String>(); if (model != null) { ListOf listOfSpecies = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { Species species = (Species) listOfSpecies.get(i); listOfSpecs.add(species.getId()); } } allSpecies = listOfSpecs.toArray(); for (int i = 1; i < allSpecies.length; i++) { String index = (String) allSpecies[i]; int j = i; while ((j > 0) && ((String) allSpecies[j - 1]).compareToIgnoreCase(index) > 0) { allSpecies[j] = allSpecies[j - 1]; j = j - 1; } allSpecies[j] = index; } intSpecies.setListData(allSpecies); termCond.setListData(allSpecies); int rem = availSpecies.getItemCount(); for (int i = 0; i < rem; i++) { availSpecies.removeItemAt(0); } for (int i = 0; i < allSpecies.length; i++) { availSpecies.addItem(((String) allSpecies[i]).replace(" ", "_")); } runFiles = false; String[] searchForRunFiles = new File(root + separator + simName).list(); for (String s : searchForRunFiles) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { runFiles = true; } } if (biosimrc.get("biosim.sim.abs", "").equals("None")) { none.doClick(); } else if (biosimrc.get("biosim.sim.abs", "").equals("Abstraction")) { abstraction.doClick(); } else { nary.doClick(); } if (biosimrc.get("biosim.sim.type", "").equals("ODE")) { ODE.doClick(); simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); } else if (biosimrc.get("biosim.sim.type", "").equals("Monte Carlo")) { monteCarlo.doClick(); simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); } else if (biosimrc.get("biosim.sim.type", "").equals("Markov")) { markov.doClick(); simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); } else if (biosimrc.get("biosim.sim.type", "").equals("SBML")) { sbml.doClick(); simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); sbml.doClick(); } else if (biosimrc.get("biosim.sim.type", "").equals("LHPN")) { if (lhpn.isEnabled()) { lhpn.doClick(); simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); lhpn.doClick(); } } else if (biosimrc.get("biosim.sim.type", "").equals("Network")) { dot.doClick(); simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); dot.doClick(); } else { xhtml.doClick(); simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); xhtml.doClick(); } if (open != null) { open(open); } } /** * This method performs different functions depending on what buttons are * pushed and what input fields contain data. */ public void actionPerformed(ActionEvent e) { // if the none Radio Button is selected change = true; if (e.getSource() == none) { Button_Enabling.enableNoneOrAbs(ODE, monteCarlo, markov, seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, none, intSpecies, species, spLabel, speciesLabel, addIntSpecies, removeIntSpecies, rapid1, rapid2, qssa, maxCon, rapidLabel1, rapidLabel2, qssaLabel, maxConLabel, usingSSA, clearIntSpecies, fileStem, fileStemLabel, lhpn); if (!sbml.isSelected() && !xhtml.isSelected() && !dot.isSelected() && runFiles) { overwrite.setEnabled(true); append.setEnabled(true); choose3.setEnabled(true); amounts.setEnabled(true); concentrations.setEnabled(true); report.setEnabled(true); if (overwrite.isSelected()) { limit.setEnabled(true); interval.setEnabled(true); limitLabel.setEnabled(true); intervalLabel.setEnabled(true); } else { limit.setEnabled(false); interval.setEnabled(false); limitLabel.setEnabled(false); intervalLabel.setEnabled(false); } } } // if the abstraction Radio Button is selected else if (e.getSource() == abstraction) { Button_Enabling.enableNoneOrAbs(ODE, monteCarlo, markov, seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, none, intSpecies, species, spLabel, speciesLabel, addIntSpecies, removeIntSpecies, rapid1, rapid2, qssa, maxCon, rapidLabel1, rapidLabel2, qssaLabel, maxConLabel, usingSSA, clearIntSpecies, fileStem, fileStemLabel, lhpn); if (!sbml.isSelected() && !xhtml.isSelected() && !dot.isSelected() && runFiles) { overwrite.setEnabled(true); append.setEnabled(true); choose3.setEnabled(true); amounts.setEnabled(true); concentrations.setEnabled(true); report.setEnabled(true); if (overwrite.isSelected()) { limit.setEnabled(true); interval.setEnabled(true); limitLabel.setEnabled(true); intervalLabel.setEnabled(true); } else { limit.setEnabled(false); interval.setEnabled(false); limitLabel.setEnabled(false); intervalLabel.setEnabled(false); } } } // if the nary Radio Button is selected else if (e.getSource() == nary) { Button_Enabling.enableNary(ODE, monteCarlo, markov, seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, intSpecies, species, spLabel, speciesLabel, addIntSpecies, removeIntSpecies, rapid1, rapid2, qssa, maxCon, rapidLabel1, rapidLabel2, qssaLabel, maxConLabel, usingSSA, clearIntSpecies, fileStem, fileStemLabel, lhpn, gcmEditor); if (!sbml.isSelected() && !xhtml.isSelected() && !dot.isSelected() && runFiles) { overwrite.setEnabled(true); append.setEnabled(true); choose3.setEnabled(true); amounts.setEnabled(true); concentrations.setEnabled(true); report.setEnabled(true); if (overwrite.isSelected()) { limit.setEnabled(true); interval.setEnabled(true); limitLabel.setEnabled(true); intervalLabel.setEnabled(true); } else { limit.setEnabled(false); interval.setEnabled(false); limitLabel.setEnabled(false); intervalLabel.setEnabled(false); } } } // if the ODE Radio Button is selected else if (e.getSource() == ODE) { Button_Enabling.enableODE(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, usingSSA, fileStem, fileStemLabel); overwrite.setEnabled(true); append.setEnabled(true); choose3.setEnabled(true); amounts.setEnabled(true); concentrations.setEnabled(true); report.setEnabled(true); } // if the monteCarlo Radio Button is selected else if (e.getSource() == monteCarlo) { Button_Enabling.enableMonteCarlo(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, usingSSA, fileStem, fileStemLabel); if (runFiles) { overwrite.setEnabled(true); append.setEnabled(true); choose3.setEnabled(true); amounts.setEnabled(true); concentrations.setEnabled(true); report.setEnabled(true); if (overwrite.isSelected()) { limit.setEnabled(true); interval.setEnabled(true); limitLabel.setEnabled(true); intervalLabel.setEnabled(true); } else { limit.setEnabled(false); interval.setEnabled(false); limitLabel.setEnabled(false); intervalLabel.setEnabled(false); } } } // if the markov Radio Button is selected else if (e.getSource() == markov) { Button_Enabling.enableMarkov(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, usingSSA, fileStem, fileStemLabel, gcmEditor); overwrite.setEnabled(false); append.setEnabled(false); choose3.setEnabled(false); amounts.setEnabled(false); concentrations.setEnabled(false); report.setEnabled(false); } // if the sbml Radio Button is selected else if (e.getSource() == sbml) { Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, fileStem, fileStemLabel); overwrite.setEnabled(false); append.setEnabled(false); choose3.setEnabled(false); amounts.setEnabled(false); concentrations.setEnabled(false); report.setEnabled(false); absErr.setEnabled(false); } // if the dot Radio Button is selected else if (e.getSource() == dot) { Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, fileStem, fileStemLabel); overwrite.setEnabled(false); append.setEnabled(false); choose3.setEnabled(false); amounts.setEnabled(false); concentrations.setEnabled(false); report.setEnabled(false); absErr.setEnabled(false); } // if the xhtml Radio Button is selected else if (e.getSource() == xhtml) { Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, fileStem, fileStemLabel); overwrite.setEnabled(false); append.setEnabled(false); choose3.setEnabled(false); amounts.setEnabled(false); concentrations.setEnabled(false); report.setEnabled(false); absErr.setEnabled(false); } // if the lhpn Radio Button is selected else if (e.getSource() == lhpn) { Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, fileStem, fileStemLabel); overwrite.setEnabled(false); append.setEnabled(false); choose3.setEnabled(false); amounts.setEnabled(false); concentrations.setEnabled(false); report.setEnabled(false); absErr.setEnabled(false); } // if the add interesting species button is clicked else if (e.getSource() == addIntSpecies) { interestingSpecies = Buttons.add(interestingSpecies, species, intSpecies, false, amountTerm, ge, gt, eq, lt, le, this); } // if the remove interesting species button is clicked else if (e.getSource() == removeIntSpecies) { removeIntSpecies(); } // if the clear interesting species button is clicked else if (e.getSource() == clearIntSpecies) { int[] select = new int[interestingSpecies.length]; for (int i = 0; i < interestingSpecies.length; i++) { select[i] = i; } species.setSelectedIndices(select); removeIntSpecies(); } // if the add termination conditions button is clicked else if (e.getSource() == addTermCond) { termConditions = Buttons.add(termConditions, terminations, termCond, true, amountTerm, ge, gt, eq, lt, le, this); } // if the remove termination conditions button is clicked else if (e.getSource() == removeTermCond) { termConditions = Buttons.remove(terminations, termConditions); } // if the clear termination conditions button is clicked else if (e.getSource() == clearTermCond) { termConditions = new Object[0]; terminations.setListData(termConditions); } // if the simulators combo box is selected else if (e.getSource() == simulators) { if (simulators.getItemCount() == 0) { description.setText(""); } else if (simulators.getSelectedItem().equals("euler")) { step.setEnabled(true); stepLabel.setEnabled(true); absErr.setEnabled(false); errorLabel.setEnabled(false); description.setText("Euler method"); } else if (simulators.getSelectedItem().equals("gear1")) { step.setEnabled(true); stepLabel.setEnabled(true); absErr.setEnabled(true); errorLabel.setEnabled(true); description.setText("Gear method, M=1"); } else if (simulators.getSelectedItem().equals("gear2")) { step.setEnabled(true); stepLabel.setEnabled(true); absErr.setEnabled(true); errorLabel.setEnabled(true); description.setText("Gear method, M=2"); } else if (simulators.getSelectedItem().equals("rk4imp")) { step.setEnabled(true); stepLabel.setEnabled(true); absErr.setEnabled(true); errorLabel.setEnabled(true); description.setText("Implicit 4th order Runge-Kutta at Gaussian points"); } else if (simulators.getSelectedItem().equals("rk8pd")) { step.setEnabled(true); stepLabel.setEnabled(true); absErr.setEnabled(true); errorLabel.setEnabled(true); description.setText("Embedded Runge-Kutta Prince-Dormand (8,9) method"); } else if (simulators.getSelectedItem().equals("rkf45")) { step.setEnabled(true); stepLabel.setEnabled(true); absErr.setEnabled(true); errorLabel.setEnabled(true); description.setText("Embedded Runge-Kutta-Fehlberg (4, 5) method"); } else if (simulators.getSelectedItem().equals("gillespie")) { description.setText("Gillespie's direct method"); step.setEnabled(true); stepLabel.setEnabled(true); errorLabel.setEnabled(false); absErr.setEnabled(false); } else if (simulators.getSelectedItem().equals("mpde")) { description.setText("iSSA (Marginal Probability Density Evolution)"); step.setEnabled(true); stepLabel.setEnabled(true); errorLabel.setEnabled(false); absErr.setEnabled(false); } else if (simulators.getSelectedItem().equals("mp")) { description.setText("iSSA (Mean Path)"); step.setEnabled(true); stepLabel.setEnabled(true); errorLabel.setEnabled(false); absErr.setEnabled(false); } else if (simulators.getSelectedItem().equals("emc-sim")) { description.setText("Monte Carlo sim with jump count as" + " independent variable"); step.setEnabled(true); stepLabel.setEnabled(true); errorLabel.setEnabled(false); absErr.setEnabled(false); } else if (simulators.getSelectedItem().equals("bunker")) { description.setText("Bunker's method"); step.setEnabled(true); stepLabel.setEnabled(true); errorLabel.setEnabled(false); absErr.setEnabled(false); } else if (simulators.getSelectedItem().equals("nmc")) { description.setText("Monte Carlo simulation with normally" + " distributed waiting time"); step.setEnabled(true); stepLabel.setEnabled(true); errorLabel.setEnabled(false); absErr.setEnabled(false); } else if (simulators.getSelectedItem().equals("ctmc-transient")) { description.setText("Transient Distribution Analysis"); step.setEnabled(false); stepLabel.setEnabled(false); errorLabel.setEnabled(false); absErr.setEnabled(false); } else if (simulators.getSelectedItem().equals("atacs")) { description.setText("ATACS Analysis Tool"); step.setEnabled(false); stepLabel.setEnabled(false); errorLabel.setEnabled(false); absErr.setEnabled(false); } else if (simulators.getSelectedItem().equals("markov-chain-analysis")) { description.setText("Markov Chain Analysis"); step.setEnabled(false); stepLabel.setEnabled(false); errorLabel.setEnabled(false); absErr.setEnabled(false); } } // if the Run button is clicked else if (e.getSource() == run) { String stem = ""; if (!fileStem.getText().trim().equals("")) { if (!(stemPat.matcher(fileStem.getText().trim()).matches())) { JOptionPane.showMessageDialog(biomodelsim.frame(), "A file stem can only contain letters, numbers, and underscores.", "Invalid File Stem", JOptionPane.ERROR_MESSAGE); return; } stem += fileStem.getText().trim(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (sbmlEditor != null) { if (biomodelsim.getTab().getTitleAt(i).equals(sbmlEditor.getRefFile())) { if (biomodelsim.getTab().getComponentAt(i) instanceof SBML_Editor) { SBML_Editor sbml = ((SBML_Editor) (biomodelsim.getTab() .getComponentAt(i))); if (sbml.isDirty()) { Object[] options = { "Yes", "No" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), "Do you want to save changes to " + sbmlEditor.getRefFile() + " before running the simulation?", "Save Changes", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { sbml.save(true, stem, true); } } } else if (biomodelsim.getTab().getComponentAt(i) instanceof GCM2SBMLEditor) { GCM2SBMLEditor gcm = ((GCM2SBMLEditor) (biomodelsim.getTab() .getComponentAt(i))); if (gcm.isDirty()) { Object[] options = { "Yes", "No" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), "Do you want to save changes to " + sbmlEditor.getRefFile() + " before running the simulation?", "Save Changes", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { gcm.save("gcm"); } } } } } else { if (biomodelsim.getTab().getTitleAt(i).equals(gcmEditor.getRefFile())) { if (biomodelsim.getTab().getComponentAt(i) instanceof GCM2SBMLEditor) { GCM2SBMLEditor gcm = ((GCM2SBMLEditor) (biomodelsim.getTab() .getComponentAt(i))); if (gcm.isDirty()) { Object[] options = { "Yes", "No" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), "Do you want to save changes to " + gcmEditor.getRefFile() + " before running the simulation?", "Save Changes", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { gcm.save("gcm"); } } } } } } if (sbmlEditor != null) { sbmlEditor.save(true, stem, true); } else { gcmEditor.saveParams(true, stem); } } else if (e.getSource() == save) { if (sbmlEditor != null) { sbmlEditor.save(false, "", true); } else { gcmEditor.saveParams(false, ""); } save(); } // if the using ssa check box is clicked else if (e.getSource() == usingSSA) { if (usingSSA.isSelected()) { newSSA.setEnabled(true); usingSSA.setSelected(true); description.setEnabled(false); explanation.setEnabled(false); simulators.setEnabled(false); simulatorsLabel.setEnabled(false); ODE.setEnabled(false); if (ODE.isSelected()) { ODE.setSelected(false); monteCarlo.setSelected(true); Button_Enabling.enableMonteCarlo(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, usingSSA, fileStem, fileStemLabel); if (runFiles) { overwrite.setEnabled(true); append.setEnabled(true); choose3.setEnabled(true); amounts.setEnabled(true); concentrations.setEnabled(true); report.setEnabled(true); if (overwrite.isSelected()) { limit.setEnabled(true); interval.setEnabled(true); limitLabel.setEnabled(true); intervalLabel.setEnabled(true); } else { limit.setEnabled(false); interval.setEnabled(false); limitLabel.setEnabled(false); intervalLabel.setEnabled(false); } } } markov.setEnabled(false); if (markov.isSelected()) { markov.setSelected(false); monteCarlo.setSelected(true); Button_Enabling.enableMonteCarlo(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, usingSSA, fileStem, fileStemLabel); if (runFiles) { overwrite.setEnabled(true); append.setEnabled(true); choose3.setEnabled(true); amounts.setEnabled(true); concentrations.setEnabled(true); report.setEnabled(true); if (overwrite.isSelected()) { limit.setEnabled(true); interval.setEnabled(true); limitLabel.setEnabled(true); intervalLabel.setEnabled(true); } else { limit.setEnabled(false); interval.setEnabled(false); limitLabel.setEnabled(false); intervalLabel.setEnabled(false); } } } ssa.setEnabled(true); timeLabel.setEnabled(true); time.setEnabled(true); availSpecies.setEnabled(true); ssaMod.setEnabled(true); ssaModNum.setEnabled(true); addSSA.setEnabled(true); editSSA.setEnabled(true); removeSSA.setEnabled(true); for (int i = 0; i < ssaList.length; i++) addToIntSpecies(((String) ssaList[i]).split(" ")[1]); } else { description.setEnabled(true); explanation.setEnabled(true); simulators.setEnabled(true); simulatorsLabel.setEnabled(true); newSSA.setEnabled(false); usingSSA.setSelected(false); ssa.setEnabled(false); timeLabel.setEnabled(false); time.setEnabled(false); availSpecies.setEnabled(false); ssaMod.setEnabled(false); ssaModNum.setEnabled(false); addSSA.setEnabled(false); editSSA.setEnabled(false); removeSSA.setEnabled(false); if (!nary.isSelected()) { ODE.setEnabled(true); } else { markov.setEnabled(true); } } } // if the using sad check box is clicked else if (e.getSource() == usingSAD) { if (usingSAD.isSelected()) { sad.setEnabled(true); newSAD.setEnabled(true); usingSAD.setSelected(true); idLabel.setEnabled(true); TCid.setEnabled(true); descLabel.setEnabled(true); desc.setEnabled(true); condLabel.setEnabled(true); cond.setEnabled(true); addSAD.setEnabled(true); editSAD.setEnabled(true); removeSAD.setEnabled(true); for (int i = 0; i < sadList.length; i++) { String[] get = ((String) sadList[i]).split(";"); String cond = get[2]; cond = cond.replace('>', ' '); cond = cond.replace('<', ' '); cond = cond.replace('=', ' '); cond = cond.replace('&', ' '); cond = cond.replace('|', ' '); cond = cond.replace('+', ' '); cond = cond.replace('-', ' '); cond = cond.replace('*', ' '); cond = cond.replace('/', ' '); cond = cond.replace(' cond = cond.replace('%', ' '); cond = cond.replace('@', ' '); cond = cond.replace('(', ' '); cond = cond.replace(')', ' '); cond = cond.replace('!', ' '); get = cond.split(" "); for (int j = 0; j < get.length; j++) if (get[j].length() > 0) if ((get[j].charAt(0) != '0') && (get[j].charAt(0) != '1') && (get[j].charAt(0) != '2') && (get[j].charAt(0) != '3') && (get[j].charAt(0) != '4') && (get[j].charAt(0) != '5') && (get[j].charAt(0) != '6') && (get[j].charAt(0) != '7') && (get[j].charAt(0) != '8') && (get[j].charAt(0) != '9')) { addToIntSpecies(get[j]); } } } else { sad.setEnabled(false); newSAD.setEnabled(false); usingSAD.setSelected(false); idLabel.setEnabled(false); TCid.setEnabled(false); descLabel.setEnabled(false); desc.setEnabled(false); condLabel.setEnabled(false); cond.setEnabled(false); addSAD.setEnabled(false); editSAD.setEnabled(false); removeSAD.setEnabled(false); } } // if the add ssa button is clicked else if (e.getSource() == addSSA) { double time = 0; int mod = 0; try { time = Double.parseDouble(this.time.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "You must enter a real " + "number into the time text field!", "Time Must Be A Real Number", JOptionPane.ERROR_MESSAGE); return; } try { mod = Integer.parseInt(ssaModNum.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "You must enter an integer " + "into the amount change text field!", "Amount Change Must Be An Integer", JOptionPane.ERROR_MESSAGE); return; } String modify; if (ssaMod.getSelectedItem().equals("goes to")) { modify = "="; } else if (ssaMod.getSelectedItem().equals("is added by")) { modify = "+"; } else if (ssaMod.getSelectedItem().equals("is subtracted by")) { modify = "-"; } else if (ssaMod.getSelectedItem().equals("is multiplied by")) { modify = "*"; } else { modify = "/"; } if (availSpecies.getSelectedItem() == null) { JOptionPane.showMessageDialog(biomodelsim.frame(), "You must select a model for simulation " + "in order to add a user defined condition.", "Select A Model For Simulation", JOptionPane.ERROR_MESSAGE); return; } addToIntSpecies((String) availSpecies.getSelectedItem()); String add = time + " " + availSpecies.getSelectedItem() + " " + modify + mod; boolean done = false; for (int i = 0; i < ssaList.length; i++) { String[] get = ((String) ssaList[i]).split(" "); if (get[0].equals(time + "") && get[1].equals(availSpecies.getSelectedItem() + "")) { ssaList[i] = add; done = true; } } if (!done) { JList addSSA = new JList(); Object[] adding = { add }; addSSA.setListData(adding); addSSA.setSelectedIndex(0); ssaList = Buttons.add(ssaList, ssa, addSSA, false, null, null, null, null, null, null, this); int[] index = ssa.getSelectedIndices(); ssaList = Buttons.getList(ssaList, ssa); ssa.setSelectedIndices(index); ArrayList<String> sortName = new ArrayList<String>(); for (int i = 0; i < ssaList.length; i++) { sortName.add(((String) ssaList[i]).split(" ")[1]); } int in, out; for (out = 1; out < sortName.size(); out++) { String temp = sortName.get(out); String temp2 = (String) ssaList[out]; in = out; while (in > 0 && sortName.get(in - 1).compareToIgnoreCase(temp) > 0) { sortName.set(in, sortName.get(in - 1)); ssaList[in] = ssaList[in - 1]; --in; } sortName.set(in, temp); ssaList[in] = temp2; } ArrayList<Double> sort = new ArrayList<Double>(); for (int i = 0; i < ssaList.length; i++) { sort.add(Double.parseDouble(((String) ssaList[i]).split(" ")[0])); } for (out = 1; out < sort.size(); out++) { double temp = sort.get(out); String temp2 = (String) ssaList[out]; in = out; while (in > 0 && sort.get(in - 1) > temp) { sort.set(in, sort.get(in - 1)); ssaList[in] = ssaList[in - 1]; --in; } sort.set(in, temp); ssaList[in] = temp2; } } ssa.setListData(ssaList); } // if the add sad button is clicked else if (e.getSource() == addSAD) { SBMLDocument document = BioSim.readSBML(sbmlFile); Model model = document.getModel(); ArrayList<String> listOfSpecs = new ArrayList<String>(); ArrayList<String> listOfReacs = new ArrayList<String>(); if (model != null) { ListOf listOfSpecies = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { Species species = (Species) listOfSpecies.get(i); listOfSpecs.add(species.getId()); } ListOf listOfReactions = model.getListOfReactions(); for (int i = 0; i < model.getNumReactions(); i++) { Reaction reaction = (Reaction) listOfReactions.get(i); listOfReacs.add(reaction.getId()); } } TermCond TCparser = new TermCond(false); int result = TCparser.ParseTermCond(biomodelsim, (this), listOfSpecs, listOfReacs, cond .getText().trim()); if (result == 0) { String add = TCid.getText().trim() + "; " + desc.getText().trim() + "; " + cond.getText().trim(); JList addSAD = new JList(); Object[] adding = { add }; addSAD.setListData(adding); addSAD.setSelectedIndex(0); TCid.setText(""); desc.setText(""); cond.setText(""); sadList = Buttons.add(sadList, sad, addSAD, false, null, null, null, null, null, null, this); sad.setListData(sadList); } else if (result == 1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Syntax error in the termination condition!", "Syntax Error", JOptionPane.ERROR_MESSAGE); } } // if the edit ssa button is clicked else if (e.getSource() == editSSA) { if (ssa.getSelectedIndex() != -1) { String[] get = ((String) ssaList[ssa.getSelectedIndex()]).split(" "); JPanel ssaAddPanel = new JPanel(new BorderLayout()); JPanel ssaAddPanel1 = new JPanel(); JPanel ssaAddPanel2 = new JPanel(); JLabel timeLabel = new JLabel("At time step: "); JTextField time = new JTextField(15); time.setText(get[0]); String filename = sbmlFile; SBMLDocument document = BioSim.readSBML(filename); Model model = document.getModel(); ArrayList<String> listOfSpecs = new ArrayList<String>(); if (model != null) { ListOf listOfSpecies = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { Species species = (Species) listOfSpecies.get(i); listOfSpecs.add(species.getId()); } } Object[] list = listOfSpecs.toArray(); for (int i = 1; i < list.length; i++) { String index = (String) list[i]; int j = i; while ((j > 0) && ((String) list[j - 1]).compareToIgnoreCase(index) > 0) { list[j] = list[j - 1]; j = j - 1; } list[j] = index; } JComboBox availSpecies = new JComboBox(); for (int i = 0; i < list.length; i++) { availSpecies.addItem(((String) list[i]).replace(" ", "_")); } availSpecies.setSelectedItem(get[1]); String[] mod = new String[5]; mod[0] = "goes to"; mod[1] = "is added by"; mod[2] = "is subtracted by"; mod[3] = "is multiplied by"; mod[4] = "is divided by"; JComboBox ssaMod = new JComboBox(mod); if (get[2].substring(0, 1).equals("=")) { ssaMod.setSelectedItem("goes to"); } else if (get[2].substring(0, 1).equals("+")) { ssaMod.setSelectedItem("is added by"); } else if (get[2].substring(0, 1).equals("-")) { ssaMod.setSelectedItem("is subtracted by"); } else if (get[2].substring(0, 1).equals("*")) { ssaMod.setSelectedItem("is multiplied by"); } else if (get[2].substring(0, 1).equals("/")) { ssaMod.setSelectedItem("is divided by"); } JTextField ssaModNum = new JTextField(15); ssaModNum.setText(get[2].substring(1)); ssaAddPanel1.add(timeLabel); ssaAddPanel1.add(time); ssaAddPanel1.add(availSpecies); ssaAddPanel2.add(ssaMod); ssaAddPanel2.add(ssaModNum); ssaAddPanel.add(ssaAddPanel1, "North"); ssaAddPanel.add(ssaAddPanel2, "Center"); String[] options = { "Save", "Cancel" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), ssaAddPanel, "Edit User Defined Data", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { double time1 = 0; int mod1 = 0; try { time1 = Double.parseDouble(time.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "You must enter a real number " + "into the time text field!", "Time Must Be A Real Number", JOptionPane.ERROR_MESSAGE); return; } try { mod1 = Integer.parseInt(ssaModNum.getText().trim()); } catch (Exception e1) { JOptionPane .showMessageDialog(biomodelsim.frame(), "You must enter an integer " + "into the amount change text field!", "Amount Change Must Be An Integer", JOptionPane.ERROR_MESSAGE); return; } String modify; if (ssaMod.getSelectedItem().equals("goes to")) { modify = "="; } else if (ssaMod.getSelectedItem().equals("is added by")) { modify = "+"; } else if (ssaMod.getSelectedItem().equals("is subtracted by")) { modify = "-"; } else if (ssaMod.getSelectedItem().equals("is multiplied by")) { modify = "*"; } else { modify = "/"; } if (availSpecies.getSelectedItem() == null) { JOptionPane.showMessageDialog(biomodelsim.frame(), "You must select a model for simulation " + "in order to add a user defined condition.", "Select A Model For Simulation", JOptionPane.ERROR_MESSAGE); return; } addToIntSpecies((String) availSpecies.getSelectedItem()); ssaList[ssa.getSelectedIndex()] = time1 + " " + availSpecies.getSelectedItem() + " " + modify + mod1; int[] index = ssa.getSelectedIndices(); ssa.setListData(ssaList); ssaList = Buttons.getList(ssaList, ssa); ssa.setSelectedIndices(index); ArrayList<String> sortName = new ArrayList<String>(); for (int i = 0; i < ssaList.length; i++) { sortName.add(((String) ssaList[i]).split(" ")[1]); } int in, out; for (out = 1; out < sortName.size(); out++) { String temp = sortName.get(out); String temp2 = (String) ssaList[out]; in = out; while (in > 0 && sortName.get(in - 1).compareToIgnoreCase(temp) > 0) { sortName.set(in, sortName.get(in - 1)); ssaList[in] = ssaList[in - 1]; --in; } sortName.set(in, temp); ssaList[in] = temp2; } ArrayList<Double> sort = new ArrayList<Double>(); for (int i = 0; i < ssaList.length; i++) { sort.add(Double.parseDouble(((String) ssaList[i]).split(" ")[0])); } for (out = 1; out < sort.size(); out++) { double temp = sort.get(out); String temp2 = (String) ssaList[out]; in = out; while (in > 0 && sort.get(in - 1) > temp) { sort.set(in, sort.get(in - 1)); ssaList[in] = ssaList[in - 1]; --in; } sort.set(in, temp); ssaList[in] = temp2; } ssa.setListData(ssaList); ArrayList<Integer> count = new ArrayList<Integer>(); for (int i = 0; i < ssaList.length; i++) { String[] remove = ((String) ssaList[i]).split(" "); if (remove[0].equals(time1 + "") && remove[1].equals(availSpecies.getSelectedItem() + "")) { count.add(i); } } if (count.size() > 1) { boolean done = false; for (int i : count) { String[] remove = ((String) ssaList[i]).split(" "); if (!remove[2].equals(modify + mod1) && !done) { ssa.setSelectedIndex(i); ssaList = Buttons.remove(ssa, ssaList); index = ssa.getSelectedIndices(); // ssaList = Buttons.getList(ssaList, ssa); ssa.setSelectedIndices(index); done = true; } } if (!done) { ssa.setSelectedIndex(count.get(0)); ssaList = Buttons.remove(ssa, ssaList); index = ssa.getSelectedIndices(); // ssaList = Buttons.getList(ssaList, ssa); ssa.setSelectedIndices(index); } } } } } // if the edit sad button is clicked else if (e.getSource() == editSAD) { if (sad.getSelectedIndex() != -1) { String[] get = ((String) sadList[sad.getSelectedIndex()]).split(";"); JPanel sadAddPanel = new JPanel(new BorderLayout()); JPanel sadAddPanel0 = new JPanel(); JPanel sadAddPanel1 = new JPanel(); JPanel sadAddPanel2 = new JPanel(); JLabel idLabel = new JLabel("ID: "); JTextField TCid = new JTextField(10); TCid.setText(get[0].trim()); JLabel descLabel = new JLabel("Description: "); JTextField desc = new JTextField(20); desc.setText(get[1].trim()); JLabel condLabel = new JLabel("Condition: "); JTextField cond = new JTextField(35); cond.setText(get[2].trim()); sadAddPanel0.add(idLabel); sadAddPanel0.add(TCid); sadAddPanel1.add(descLabel); sadAddPanel1.add(desc); sadAddPanel2.add(condLabel); sadAddPanel2.add(cond); sadAddPanel.add(sadAddPanel0, "North"); sadAddPanel.add(sadAddPanel1, "Center"); sadAddPanel.add(sadAddPanel2, "South"); String[] options = { "Save", "Cancel" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), sadAddPanel, "Edit Termination Condition", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { SBMLDocument document = BioSim.readSBML(sbmlFile); Model model = document.getModel(); ArrayList<String> listOfSpecs = new ArrayList<String>(); ArrayList<String> listOfReacs = new ArrayList<String>(); if (model != null) { ListOf listOfSpecies = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { Species species = (Species) listOfSpecies.get(i); listOfSpecs.add(species.getId()); } ListOf listOfReactions = model.getListOfReactions(); for (int i = 0; i < model.getNumReactions(); i++) { Reaction reaction = (Reaction) listOfReactions.get(i); listOfReacs.add(reaction.getId()); } } TermCond TCparser = new TermCond(false); int result = TCparser.ParseTermCond(biomodelsim, (this), listOfSpecs, listOfReacs, cond.getText().trim()); if (result == 0) { sadList[sad.getSelectedIndex()] = TCid.getText().trim() + "; " + desc.getText().trim() + "; " + cond.getText().trim(); int[] index = sad.getSelectedIndices(); sad.setListData(sadList); sadList = Buttons.getList(sadList, sad); sad.setSelectedIndices(index); sad.setListData(sadList); } else if (result == 1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Syntax error in the termination condition!", "Syntax Error", JOptionPane.ERROR_MESSAGE); } } } } // if the edit option button is clicked else if (e.getSource() == editProp) { if (properties.getSelectedIndex() != -1) { String[] get = ((String) props[properties.getSelectedIndex()]).split("="); JPanel OptAddPanel = new JPanel(new BorderLayout()); JPanel OptAddPanel0 = new JPanel(); JPanel OptAddPanel1 = new JPanel(); JLabel OptionLabel = new JLabel("Option: "); JTextField Option = new JTextField(20); Option.setText(get[0].trim()); JLabel ValueLabel = new JLabel("Value: "); JTextField Value = new JTextField(20); Value.setText(get[1].trim()); OptAddPanel0.add(OptionLabel); OptAddPanel0.add(Option); OptAddPanel1.add(ValueLabel); OptAddPanel1.add(Value); OptAddPanel.add(OptAddPanel0, "North"); OptAddPanel.add(OptAddPanel1, "Center"); String[] options = { "Save", "Cancel" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), OptAddPanel, "Edit Option", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { props[properties.getSelectedIndex()] = Option.getText().trim() + "=" + Value.getText().trim(); int[] index = properties.getSelectedIndices(); properties.setListData(props); props = Buttons.getList(props, properties); properties.setSelectedIndices(index); properties.setListData(props); } } } // if the remove ssa button is clicked else if (e.getSource() == removeSSA) { ssaList = Buttons.remove(ssa, ssaList); } // if the remove sad button is clicked else if (e.getSource() == removeSAD) { sadList = Buttons.remove(sad, sadList); } // if the new ssa button is clicked else if (e.getSource() == newSSA) { ssaList = new Object[0]; ssa.setListData(ssaList); ssa.setEnabled(true); timeLabel.setEnabled(true); time.setEnabled(true); availSpecies.setEnabled(true); ssaMod.setEnabled(true); ssaModNum.setEnabled(true); addSSA.setEnabled(true); editSSA.setEnabled(true); removeSSA.setEnabled(true); } // if the new sad button is clicked else if (e.getSource() == newSAD) { sadList = new Object[0]; sad.setListData(sadList); TCid.setText(""); desc.setText(""); cond.setText(""); } // if the new sad button is clicked else if (e.getSource() == newProp) { props = new Object[0]; properties.setListData(props); prop.setText(""); value.setText(""); } // if the remove properties button is clicked else if (e.getSource() == removeProp) { props = Buttons.remove(properties, props); } // if the add properties button is clicked else if (e.getSource() == addProp) { if (prop.getText().trim().equals("")) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Enter a option into the option field!", "Must Enter an Option", JOptionPane.ERROR_MESSAGE); return; } if (value.getText().trim().equals("")) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Enter a value into the value field!", "Must Enter a Value", JOptionPane.ERROR_MESSAGE); return; } String add = prop.getText().trim() + "=" + value.getText().trim(); JList addPropery = new JList(); Object[] adding = { add }; addPropery.setListData(adding); addPropery.setSelectedIndex(0); props = Buttons.add(props, properties, addPropery, false, null, null, null, null, null, null, this); } else if (e.getSource() == overwrite) { limit.setEnabled(true); interval.setEnabled(true); limitLabel.setEnabled(true); intervalLabel.setEnabled(true); } else if (e.getSource() == append) { limit.setEnabled(false); interval.setEnabled(false); limitLabel.setEnabled(false); intervalLabel.setEnabled(false); Random rnd = new Random(); seed.setText("" + rnd.nextInt()); int cut = 0; String[] getFilename = sbmlProp.split(separator); for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) { if (getFilename[getFilename.length - 1].charAt(i) == '.') { cut = i; } } String propName = sbmlProp.substring(0, sbmlProp.length() - getFilename[getFilename.length - 1].length()) + getFilename[getFilename.length - 1].substring(0, cut) + ".properties"; try { if (new File(propName).exists()) { Properties getProps = new Properties(); FileInputStream load = new FileInputStream(new File(propName)); getProps.load(load); load.close(); if (getProps.containsKey("monte.carlo.simulation.time.limit")) { step.setText(getProps.getProperty("monte.carlo.simulation.time.step")); limit.setText(getProps.getProperty("monte.carlo.simulation.time.limit")); interval.setText(getProps .getProperty("monte.carlo.simulation.print.interval")); } } } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to restore time limit and print interval.", "Error", JOptionPane.ERROR_MESSAGE); } } } /** * If the run button is pressed, this method starts a new thread for the * simulation. */ public void run(String direct) { double timeLimit = 100.0; double printInterval = 1.0; double timeStep = 1.0; double absError = 1.0e-9; String outDir = ""; long rndSeed = 314159; int run = 1; try { timeLimit = Double.parseDouble(limit.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The Time Limit Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { if (intervalLabel.getSelectedItem().equals("Print Interval")) { printInterval = Double.parseDouble(interval.getText().trim()); } else { printInterval = Integer.parseInt(interval.getText().trim()); } } catch (Exception e1) { if (intervalLabel.getSelectedItem().equals("Print Interval")) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The Print Interval Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } else { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter An Integer Into The Number Of Steps Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } } String sim = (String) simulators.getSelectedItem(); if (step.getText().trim().equals("inf") && !sim.equals("euler")) { timeStep = Double.MAX_VALUE; } else if (step.getText().trim().equals("inf") && sim.equals("euler")) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Cannot Select An Infinite Time Step With Euler Simulation.", "Error", JOptionPane.ERROR_MESSAGE); return; } else { try { // if (step.isEnabled()) { timeStep = Double.parseDouble(step.getText().trim()); } catch (Exception e1) { // if (step.isEnabled()) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The Time Step Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } } try { // if (absErr.isEnabled()) { absError = Double.parseDouble(absErr.getText().trim()); } catch (Exception e1) { // if (absErr.isEnabled()) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The Absolute Error Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (direct.equals(".")) { outDir = simName; } else { outDir = simName + separator + direct; } try { // if (seed.isEnabled()) { rndSeed = Long.parseLong(seed.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter An Integer Into The Random Seed Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } Preferences biosimrc = Preferences.userRoot(); try { // if (runs.isEnabled()) { run = Integer.parseInt(runs.getText().trim()); if (run < 0) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Positive Integer Into The Runs Field." + "\nProceding With Default: " + biosimrc.get("biosim.sim.runs", ""), "Error", JOptionPane.ERROR_MESSAGE); run = Integer.parseInt(biosimrc.get("biosim.sim.runs", "")); } } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Positive Integer Into The Runs Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (!runs.isEnabled()) { for (String runs : new File(root + separator + outDir).list()) { if (runs.length() >= 4) { String end = ""; for (int j = 1; j < 5; j++) { end = runs.charAt(runs.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (runs.contains("run-")) { run = Math.max(run, Integer.parseInt(runs.substring(4, runs.length() - end.length()))); } } } } } String printer_id = "tsd.printer"; String printer_track_quantity = "amount"; if (concentrations.isSelected()) { printer_track_quantity = "concentration"; } int[] index = terminations.getSelectedIndices(); String[] termCond = Buttons.getList(termConditions, terminations); terminations.setSelectedIndices(index); index = species.getSelectedIndices(); String[] intSpecies; // if (none.isSelected()) { // intSpecies = new String[allSpecies.length]; // for (int j = 0; j < allSpecies.length; j++) { // intSpecies[j] = (String) allSpecies[j]; // else { intSpecies = Buttons.getList(interestingSpecies, species); species.setSelectedIndices(index); String selectedButtons = ""; double rap1 = 0.1; double rap2 = 0.1; double qss = 0.1; int con = 15; try { // if (rapid1.isEnabled()) { rap1 = Double.parseDouble(rapid1.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The" + " Rapid Equilibrium Condition 1 Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { // if (rapid2.isEnabled()) { rap2 = Double.parseDouble(rapid2.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The" + " Rapid Equilibrium Condition 2 Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { // if (qssa.isEnabled()) { qss = Double.parseDouble(qssa.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The QSSA Condition Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { // if (maxCon.isEnabled()) { con = Integer.parseInt(maxCon.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter An Integer Into The Max" + " Concentration Threshold Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (none.isSelected() && ODE.isSelected()) { selectedButtons = "none_ODE"; } else if (none.isSelected() && monteCarlo.isSelected()) { selectedButtons = "none_monteCarlo"; } else if (abstraction.isSelected() && ODE.isSelected()) { selectedButtons = "abs_ODE"; } else if (abstraction.isSelected() && monteCarlo.isSelected()) { selectedButtons = "abs_monteCarlo"; } else if (nary.isSelected() && monteCarlo.isSelected()) { selectedButtons = "nary_monteCarlo"; } else if (nary.isSelected() && markov.isSelected()) { selectedButtons = "nary_markov"; } else if (none.isSelected() && sbml.isSelected()) { selectedButtons = "none_sbml"; } else if (abstraction.isSelected() && sbml.isSelected()) { selectedButtons = "abs_sbml"; } else if (nary.isSelected() && sbml.isSelected()) { selectedButtons = "nary_sbml"; } else if (none.isSelected() && dot.isSelected()) { selectedButtons = "none_dot"; } else if (abstraction.isSelected() && dot.isSelected()) { selectedButtons = "abs_dot"; } else if (nary.isSelected() && dot.isSelected()) { selectedButtons = "nary_dot"; } else if (none.isSelected() && xhtml.isSelected()) { selectedButtons = "none_xhtml"; } else if (abstraction.isSelected() && xhtml.isSelected()) { selectedButtons = "abs_xhtml"; } else if (nary.isSelected() && xhtml.isSelected()) { selectedButtons = "nary_xhtml"; } else if (nary.isSelected() && lhpn.isSelected()) { selectedButtons = "nary_lhpn"; } try { FileOutputStream out = new FileOutputStream(new File(root + separator + outDir + separator + "user-defined.dat")); int[] indecies = ssa.getSelectedIndices(); ssaList = Buttons.getList(ssaList, ssa); ssa.setSelectedIndices(indecies); String save = ""; for (int i = 0; i < ssaList.length; i++) { if (i == ssaList.length - 1) { save += ssaList[i]; } else { save += ssaList[i] + "\n"; } } byte[] output = save.getBytes(); out.write(output); out.close(); if (!usingSSA.isSelected() && save.trim().equals("")) { new File(root + separator + outDir + separator + "user-defined.dat").delete(); } } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to save user defined file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); return; } int cut = 0; String simProp = sbmlProp; boolean saveTopLevel = false; if (!direct.equals(".")) { simProp = simProp.substring(0, simProp.length() - simProp.split(separator)[simProp.split(separator).length - 1].length()) + direct + separator + simProp.substring(simProp.length() - simProp.split(separator)[simProp.split(separator).length - 1] .length()); saveTopLevel = true; } String[] getFilename = simProp.split(separator); for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) { if (getFilename[getFilename.length - 1].charAt(i) == '.') { cut = i; } } String propName = simProp.substring(0, simProp.length() - getFilename[getFilename.length - 1].length()) + getFilename[getFilename.length - 1].substring(0, cut) + ".properties"; String topLevelProps = null; if (saveTopLevel) { topLevelProps = sbmlProp.substring(0, sbmlProp.length() - getFilename[getFilename.length - 1].length()) + getFilename[getFilename.length - 1].substring(0, cut) + ".properties"; } /* * String monteLimit = ""; String monteInterval = ""; try { if (new * File(propName).exists()) { Properties getProps = new Properties(); * FileInputStream load = new FileInputStream(new File(propName)); * getProps.load(load); load.close(); if * (getProps.containsKey("monte.carlo.simulation.time.limit")) { * monteLimit = * getProps.getProperty("monte.carlo.simulation.time.limit"); * monteInterval = * getProps.getProperty("monte.carlo.simulation.print.interval"); } } } * catch (Exception e) { * JOptionPane.showMessageDialog(biomodelsim.frame(), * "Unable to add properties to property file.", "Error", * JOptionPane.ERROR_MESSAGE); } */ log.addText("Creating properties file:\n" + propName + "\n"); final JButton cancel = new JButton("Cancel"); final JFrame running = new JFrame("Progress"); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { cancel.doClick(); running.dispose(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; running.addWindowListener(w); JPanel text = new JPanel(); JPanel progBar = new JPanel(); JPanel button = new JPanel(); JPanel all = new JPanel(new BorderLayout()); JLabel label; if (!direct.equals(".")) { label = new JLabel("Running " + simName + " " + direct); } else { label = new JLabel("Running " + simName); } int steps; if (intervalLabel.getSelectedItem().equals("Print Interval")) { if (simulators.getSelectedItem().equals("mpde") || simulators.getSelectedItem().equals("mp")) { //double test = printInterval / timeStep; //double error = test - ((int) test); //if (error > 0.0001) { // JOptionPane.showMessageDialog(biomodelsim.frame(), // "Print Interval Must Be A Multiple Of Time Step.", "Error", // JOptionPane.ERROR_MESSAGE); // return; //test = timeLimit / printInterval; //error = test - ((int) test); //if (error > 0.0001) { // JOptionPane.showMessageDialog(biomodelsim.frame(), // "Time Limit Must Be A Multiple Of Print Interval.", "Error", // JOptionPane.ERROR_MESSAGE); // return; steps = (int) (timeLimit / printInterval); } else { steps = (int) ((timeLimit / printInterval) * run); } } else { if (simulators.getSelectedItem().equals("mpde") || simulators.getSelectedItem().equals("mp")) { steps = (int) (printInterval); //double interval = timeLimit / steps; //double test = interval / timeStep; //double error = test - ((int) test); //if (error > 0.0001) { // JOptionPane.showMessageDialog(biomodelsim.frame(), // "Print Interval Must Be A Multiple Of Time Step.", "Error", // JOptionPane.ERROR_MESSAGE); // return; } else { steps = (int) (printInterval * run); } } JProgressBar progress = new JProgressBar(0, steps); progress.setStringPainted(true); // progress.setString(""); // progress.setIndeterminate(true); progress.setValue(0); text.add(label); progBar.add(progress); button.add(cancel); all.add(text, "North"); all.add(progBar, "Center"); all.add(button, "South"); running.setContentPane(all); running.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = running.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; running.setLocation(x, y); running.setVisible(true); running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Run runProgram = new Run(this); cancel.addActionListener(runProgram); biomodelsim.getExitButton().addActionListener(runProgram); saveSAD(outDir); runProgram.createProperties(timeLimit, ((String) (intervalLabel.getSelectedItem())), printInterval, timeStep, absError, ".", // root + separator + outDir, rndSeed, run, termCond, intSpecies, printer_id, printer_track_quantity, simProp .split(separator), selectedButtons, this, simProp, rap1, rap2, qss, con, usingSSA, // root + separator + simName + separator + "user-defined.dat", usingSAD, new File(root + separator + outDir + separator + "termCond.sad")); int[] indecies = properties.getSelectedIndices(); props = Buttons.getList(props, properties); properties.setSelectedIndices(indecies); try { Properties getProps = new Properties(); FileInputStream load = new FileInputStream(new File(propName)); getProps.load(load); load.close(); for (int i = 0; i < props.length; i++) { String[] split = ((String) props[i]).split("="); getProps.setProperty(split[0], split[1]); } getProps.setProperty("selected.simulator", sim); if (!fileStem.getText().trim().equals("")) { getProps.setProperty("file.stem", fileStem.getText().trim()); } if (monteCarlo.isSelected() || ODE.isSelected()) { if (append.isSelected()) { String[] searchForRunFiles = new File(root + separator + outDir).list(); int start = 1; for (String s : searchForRunFiles) { if (s.length() > 3 && s.substring(0, 4).equals("run-") && new File(root + separator + outDir + separator + s).isFile()) { String getNumber = s.substring(4, s.length()); String number = ""; for (int i = 0; i < getNumber.length(); i++) { if (Character.isDigit(getNumber.charAt(i))) { number += getNumber.charAt(i); } else { break; } } start = Math.max(Integer.parseInt(number), start); } } getProps.setProperty("monte.carlo.simulation.start.index", (start + 1) + ""); } else { String[] searchForRunFiles = new File(root + separator + outDir).list(); for (String s : searchForRunFiles) { if (s.length() > 3 && s.substring(0, 4).equals("run-") && new File(root + separator + outDir + separator + s).isFile()) { new File(root + separator + outDir + separator + s).delete(); } } getProps.setProperty("monte.carlo.simulation.start.index", "1"); } } // if (getProps.containsKey("ode.simulation.time.limit")) { // if (!monteLimit.equals("")) { // getProps.setProperty("monte.carlo.simulation.time.limit", // monteLimit); // getProps.setProperty("monte.carlo.simulation.print.interval", // monteInterval); FileOutputStream store = new FileOutputStream(new File(propName)); getProps.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties"); store.close(); if (saveTopLevel) { store = new FileOutputStream(new File(topLevelProps)); getProps.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties"); store.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to add properties to property file.", "Error", JOptionPane.ERROR_MESSAGE); } if (monteCarlo.isSelected() || ODE.isSelected()) { File[] files = new File(root + separator + outDir).listFiles(); for (File f : files) { if (f.getName().contains("mean.") || f.getName().contains("standard_deviation.") || f.getName().contains("variance.")) { f.delete(); } } } int exit; if (!direct.equals(".")) { exit = runProgram.execute(simProp, sbml, dot, xhtml, lhpn, biomodelsim.frame(), ODE, monteCarlo, sim, printer_id, printer_track_quantity, root + separator + simName, nary, 1, intSpecies, log, usingSSA, root + separator + outDir + separator + "user-defined.dat", biomodelsim, simTab, root, progress, steps, simName + " " + direct, gcmEditor, direct); } else { exit = runProgram.execute(simProp, sbml, dot, xhtml, lhpn, biomodelsim.frame(), ODE, monteCarlo, sim, printer_id, printer_track_quantity, root + separator + simName, nary, 1, intSpecies, log, usingSSA, root + separator + outDir + separator + "user-defined.dat", biomodelsim, simTab, root, progress, steps, simName, gcmEditor, null); } if (nary.isSelected() && !sim.equals("markov-chain-analysis") && !lhpn.isSelected() && exit == 0) { String d = null; if (!direct.equals(".")) { d = direct; } new Nary_Run(this, amountTerm, ge, gt, eq, lt, le, simulators, simProp.split(separator), simProp, sbml, dot, xhtml, lhpn, nary, ODE, monteCarlo, timeLimit, ((String) (intervalLabel.getSelectedItem())), printInterval, timeStep, root + separator + simName, rndSeed, run, printer_id, printer_track_quantity, termCond, intSpecies, rap1, rap2, qss, con, log, usingSSA, root + separator + outDir + separator + "user-defined.dat", biomodelsim, simTab, root, d); } running.setCursor(null); running.dispose(); biomodelsim.getExitButton().removeActionListener(runProgram); String[] searchForRunFiles = new File(root + separator + outDir).list(); for (String s : searchForRunFiles) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { runFiles = true; } } if (monteCarlo.isSelected()) { overwrite.setEnabled(true); append.setEnabled(true); choose3.setEnabled(true); amounts.setEnabled(true); concentrations.setEnabled(true); report.setEnabled(true); if (overwrite.isSelected()) { limit.setEnabled(true); interval.setEnabled(true); limitLabel.setEnabled(true); intervalLabel.setEnabled(true); } else { limit.setEnabled(false); interval.setEnabled(false); limitLabel.setEnabled(false); intervalLabel.setEnabled(false); } } if (append.isSelected()) { Random rnd = new Random(); seed.setText("" + rnd.nextInt()); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getComponentAt(i) instanceof Graph) { ((Graph) biomodelsim.getTab().getComponentAt(i)).refresh(); } } } public void emptyFrames() { for (JFrame f : frames) { f.dispose(); } } /** * Invoked when the mouse is double clicked in the interesting species * JLists or termination conditions JLists. Adds or removes the selected * interesting species or termination conditions. */ public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if (e.getSource() == intSpecies) { interestingSpecies = Buttons.add(interestingSpecies, species, intSpecies, false, amountTerm, ge, gt, eq, lt, le, this); } else if (e.getSource() == species) { removeIntSpecies(); } else if (e.getSource() == termCond) { termConditions = Buttons.add(termConditions, terminations, termCond, true, amountTerm, ge, gt, eq, lt, le, this); } else if (e.getSource() == terminations) { termConditions = Buttons.remove(terminations, termConditions); } else if (e.getSource() == ssa) { editSSA.doClick(); } else if (e.getSource() == properties) { props = Buttons.remove(properties, props); } } } /** * This method currently does nothing. */ public void mousePressed(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseReleased(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseExited(MouseEvent e) { } /** * Saves the simulate options. */ public void save() { double timeLimit = 100.0; double printInterval = 1.0; double timeStep = 1.0; double absError = 1.0e-9; String outDir = "."; long rndSeed = 314159; int run = 1; try { timeLimit = Double.parseDouble(limit.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The Time Limit Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { if (intervalLabel.getSelectedItem().equals("Print Interval")) { printInterval = Double.parseDouble(interval.getText().trim()); } else { printInterval = Integer.parseInt(interval.getText().trim()); } } catch (Exception e1) { if (intervalLabel.getSelectedItem().equals("Print Interval")) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The Print Interval Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } else { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter An Integer Into The Number Of Steps Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } } if (step.getText().trim().equals("inf")) { timeStep = Double.MAX_VALUE; } else { try { timeStep = Double.parseDouble(step.getText().trim()); } catch (Exception e1) { if (step.isEnabled()) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The Time Step Field.", "Error", JOptionPane.ERROR_MESSAGE); } return; } } try { // if (absErr.isEnabled()) { absError = Double.parseDouble(absErr.getText().trim()); } catch (Exception e1) { // if (absErr.isEnabled()) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The Absolute Error Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } outDir = simName; // outDir = root + separator + simName; try { // if (seed.isEnabled()) { rndSeed = Long.parseLong(seed.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter An Integer Into The Random Seed Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { // if (runs.isEnabled()) { run = Integer.parseInt(runs.getText().trim()); if (run < 0) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Positive Integer Into The Runs Field." + "\nProceding With Default: 1", "Error", JOptionPane.ERROR_MESSAGE); run = 1; } } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Positive Integer Into The Runs Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } String printer_id = "tsd.printer"; String printer_track_quantity = "amount"; if (concentrations.isSelected()) { printer_track_quantity = "concentration"; } int[] index = terminations.getSelectedIndices(); String[] termCond = Buttons.getList(termConditions, terminations); terminations.setSelectedIndices(index); index = species.getSelectedIndices(); String[] intSpecies; // if (none.isSelected()) { // intSpecies = new String[allSpecies.length]; // for (int j = 0; j < allSpecies.length; j++) { // intSpecies[j] = (String) allSpecies[j]; // else { intSpecies = Buttons.getList(interestingSpecies, species); species.setSelectedIndices(index); String selectedButtons = ""; double rap1 = 0.1; double rap2 = 0.1; double qss = 0.1; int con = 15; try { // if (rapid1.isEnabled()) { rap1 = Double.parseDouble(rapid1.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The" + " Rapid Equilibrium Condition 1 Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { // if (rapid2.isEnabled()) { rap2 = Double.parseDouble(rapid2.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The" + " Rapid Equilibrium Condition 2 Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { // if (qssa.isEnabled()) { qss = Double.parseDouble(qssa.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The QSSA Condition Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { // if (maxCon.isEnabled()) { con = Integer.parseInt(maxCon.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter An Integer Into The Max" + " Concentration Threshold Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (none.isSelected() && ODE.isSelected()) { selectedButtons = "none_ODE"; } else if (none.isSelected() && monteCarlo.isSelected()) { selectedButtons = "none_monteCarlo"; } else if (abstraction.isSelected() && ODE.isSelected()) { selectedButtons = "abs_ODE"; } else if (abstraction.isSelected() && monteCarlo.isSelected()) { selectedButtons = "abs_monteCarlo"; } else if (nary.isSelected() && monteCarlo.isSelected()) { selectedButtons = "nary_monteCarlo"; } else if (nary.isSelected() && markov.isSelected()) { selectedButtons = "nary_markov"; } else if (none.isSelected() && sbml.isSelected()) { selectedButtons = "none_sbml"; } else if (abstraction.isSelected() && sbml.isSelected()) { selectedButtons = "abs_sbml"; } else if (nary.isSelected() && sbml.isSelected()) { selectedButtons = "nary_sbml"; } else if (none.isSelected() && dot.isSelected()) { selectedButtons = "none_dot"; } else if (abstraction.isSelected() && dot.isSelected()) { selectedButtons = "abs_dot"; } else if (nary.isSelected() && dot.isSelected()) { selectedButtons = "nary_dot"; } else if (none.isSelected() && xhtml.isSelected()) { selectedButtons = "none_xhtml"; } else if (abstraction.isSelected() && xhtml.isSelected()) { selectedButtons = "abs_xhtml"; } else if (nary.isSelected() && xhtml.isSelected()) { selectedButtons = "nary_xhtml"; } else if (nary.isSelected() && lhpn.isSelected()) { selectedButtons = "nary_lhpn"; } try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName + separator + "user-defined.dat")); int[] indecies = ssa.getSelectedIndices(); ssaList = Buttons.getList(ssaList, ssa); ssa.setSelectedIndices(indecies); String save = ""; for (int i = 0; i < ssaList.length; i++) { if (i == ssaList.length - 1) { save += ssaList[i]; } else { save += ssaList[i] + "\n"; } } byte[] output = save.getBytes(); out.write(output); out.close(); if (!usingSSA.isSelected() && save.trim().equals("")) { new File(root + separator + simName + separator + "user-defined.dat").delete(); } } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to save user defined file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); return; } Run runProgram = new Run(this); int cut = 0; String[] getFilename = sbmlProp.split(separator); for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) { if (getFilename[getFilename.length - 1].charAt(i) == '.') { cut = i; } } String propName = sbmlProp.substring(0, sbmlProp.length() - getFilename[getFilename.length - 1].length()) + getFilename[getFilename.length - 1].substring(0, cut) + ".properties"; // String monteLimit = ""; // String monteInterval = ""; // try { // if (new File(propName).exists()) { // Properties getProps = new Properties(); // FileInputStream load = new FileInputStream(new File(propName)); // getProps.load(load); // load.close(); // if (getProps.containsKey("monte.carlo.simulation.time.limit")) { // monteLimit = // getProps.getProperty("monte.carlo.simulation.time.limit"); // monteInterval = // getProps.getProperty("monte.carlo.simulation.print.interval"); // catch (Exception e) { // JOptionPane.showMessageDialog(biomodelsim.frame(), // "Unable to add properties to property file.", "Error", // JOptionPane.ERROR_MESSAGE); log.addText("Creating properties file:\n" + propName + "\n"); saveSAD(simName); runProgram.createProperties(timeLimit, ((String) (intervalLabel.getSelectedItem())), printInterval, timeStep, absError, ".", // outDir, rndSeed, run, termCond, intSpecies, printer_id, printer_track_quantity, sbmlProp .split(separator), selectedButtons, this, sbmlProp, rap1, rap2, qss, con, usingSSA, // root + separator + simName + separator + "user-defined.dat", usingSAD, new File(root + separator + outDir + separator + "termCond.sad")); int[] indecies = properties.getSelectedIndices(); props = Buttons.getList(props, properties); properties.setSelectedIndices(indecies); try { Properties getProps = new Properties(); FileInputStream load = new FileInputStream(new File(propName)); getProps.load(load); load.close(); for (int i = 0; i < props.length; i++) { String[] split = ((String) props[i]).split("="); getProps.setProperty(split[0], split[1]); } getProps.setProperty("selected.simulator", (String) simulators.getSelectedItem()); if (!fileStem.getText().trim().equals("")) { getProps.setProperty("file.stem", fileStem.getText().trim()); } // if (getProps.containsKey("ode.simulation.time.limit")) { // if (!monteLimit.equals("")) { // getProps.setProperty("monte.carlo.simulation.time.limit", // monteLimit); // getProps.setProperty("monte.carlo.simulation.print.interval", // monteInterval); FileOutputStream store = new FileOutputStream(new File(propName)); getProps.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties"); store.close(); } catch (Exception e) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to add properties to property file.", "Error", JOptionPane.ERROR_MESSAGE); } biomodelsim.refreshTree(); change = false; } public void saveSAD(String outDir) { try { int[] indecies = sad.getSelectedIndices(); sadList = Buttons.getList(sadList, sad); if (sadList.length == 0) return; FileOutputStream out = new FileOutputStream(new File(root + separator + outDir + separator + "termCond.sad")); sad.setSelectedIndices(indecies); String save = ""; for (int i = 0; i < sadList.length; i++) { String[] get = ((String) sadList[i]).split(";"); save += "term " + get[0].trim() + " {\n"; save += " desc \"" + get[1].trim() + "\";\n"; save += " cond " + get[2].trim() + ";\n"; save += "}\n"; } byte[] output = save.getBytes(); out.write(output); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to save termination conditions!", "Error Saving File", JOptionPane.ERROR_MESSAGE); return; } } /** * Loads the simulate options. */ public void open(String openFile) { Properties load = new Properties(); try { if (!openFile.equals("")) { FileInputStream in = new FileInputStream(new File(openFile)); load.load(in); in.close(); ArrayList<String> loadProperties = new ArrayList<String>(); for (Object key : load.keySet()) { if (key.equals("reb2sac.abstraction.method.0.1")) { if (!load.getProperty("reb2sac.abstraction.method.0.1").equals( "enzyme-kinetic-qssa-1")) { loadProperties.add("reb2sac.abstraction.method.0.1=" + load.getProperty("reb2sac.abstraction.method.0.1")); } } else if (key.equals("reb2sac.abstraction.method.0.2")) { if (!load.getProperty("reb2sac.abstraction.method.0.2").equals( "reversible-to-irreversible-transformer")) { loadProperties.add("reb2sac.abstraction.method.0.2=" + load.getProperty("reb2sac.abstraction.method.0.2")); } } else if (key.equals("reb2sac.abstraction.method.0.3")) { if (!load.getProperty("reb2sac.abstraction.method.0.3").equals( "multiple-products-reaction-eliminator")) { loadProperties.add("reb2sac.abstraction.method.0.3=" + load.getProperty("reb2sac.abstraction.method.0.3")); } } else if (key.equals("reb2sac.abstraction.method.0.4")) { if (!load.getProperty("reb2sac.abstraction.method.0.4").equals( "multiple-reactants-reaction-eliminator")) { loadProperties.add("reb2sac.abstraction.method.0.4=" + load.getProperty("reb2sac.abstraction.method.0.4")); } } else if (key.equals("reb2sac.abstraction.method.0.5")) { if (!load.getProperty("reb2sac.abstraction.method.0.5").equals( "single-reactant-product-reaction-eliminator")) { loadProperties.add("reb2sac.abstraction.method.0.5=" + load.getProperty("reb2sac.abstraction.method.0.5")); } } else if (key.equals("reb2sac.abstraction.method.0.6")) { if (!load.getProperty("reb2sac.abstraction.method.0.6").equals( "dimer-to-monomer-substitutor")) { loadProperties.add("reb2sac.abstraction.method.0.6=" + load.getProperty("reb2sac.abstraction.method.0.6")); } } else if (key.equals("reb2sac.abstraction.method.0.7")) { if (!load.getProperty("reb2sac.abstraction.method.0.7").equals( "inducer-structure-transformer")) { loadProperties.add("reb2sac.abstraction.method.0.7=" + load.getProperty("reb2sac.abstraction.method.0.7")); } } else if (key.equals("reb2sac.abstraction.method.1.1")) { if (!load.getProperty("reb2sac.abstraction.method.1.1").equals( "modifier-structure-transformer")) { loadProperties.add("reb2sac.abstraction.method.1.1=" + load.getProperty("reb2sac.abstraction.method.1.1")); } } else if (key.equals("reb2sac.abstraction.method.1.2")) { if (!load.getProperty("reb2sac.abstraction.method.1.2").equals( "modifier-constant-propagation")) { loadProperties.add("reb2sac.abstraction.method.1.2=" + load.getProperty("reb2sac.abstraction.method.1.2")); } } else if (key.equals("reb2sac.abstraction.method.2.1")) { if (!load.getProperty("reb2sac.abstraction.method.2.1").equals( "operator-site-forward-binding-remover")) { loadProperties.add("reb2sac.abstraction.method.2.1=" + load.getProperty("reb2sac.abstraction.method.2.1")); } } else if (key.equals("reb2sac.abstraction.method.2.3")) { if (!load.getProperty("reb2sac.abstraction.method.2.3").equals( "enzyme-kinetic-rapid-equilibrium-1")) { loadProperties.add("reb2sac.abstraction.method.2.3=" + load.getProperty("reb2sac.abstraction.method.2.3")); } } else if (key.equals("reb2sac.abstraction.method.2.4")) { if (!load.getProperty("reb2sac.abstraction.method.2.4").equals( "irrelevant-species-remover")) { loadProperties.add("reb2sac.abstraction.method.2.4=" + load.getProperty("reb2sac.abstraction.method.2.4")); } } else if (key.equals("reb2sac.abstraction.method.2.5")) { if (!load.getProperty("reb2sac.abstraction.method.2.5").equals( "inducer-structure-transformer")) { loadProperties.add("reb2sac.abstraction.method.2.5=" + load.getProperty("reb2sac.abstraction.method.2.5")); } } else if (key.equals("reb2sac.abstraction.method.2.6")) { if (!load.getProperty("reb2sac.abstraction.method.2.6").equals( "modifier-constant-propagation")) { loadProperties.add("reb2sac.abstraction.method.2.6=" + load.getProperty("reb2sac.abstraction.method.2.6")); } } else if (key.equals("reb2sac.abstraction.method.2.7")) { if (!load.getProperty("reb2sac.abstraction.method.2.7").equals( "similar-reaction-combiner")) { loadProperties.add("reb2sac.abstraction.method.2.7=" + load.getProperty("reb2sac.abstraction.method.2.7")); } } else if (key.equals("reb2sac.abstraction.method.2.8")) { if (!load.getProperty("reb2sac.abstraction.method.2.8").equals( "modifier-constant-propagation")) { loadProperties.add("reb2sac.abstraction.method.2.8=" + load.getProperty("reb2sac.abstraction.method.2.8")); } } else if (key.equals("reb2sac.abstraction.method.2.2")) { if (!load.getProperty("reb2sac.abstraction.method.2.2").equals( "dimerization-reduction") && !load.getProperty("reb2sac.abstraction.method.2.2").equals( "dimerization-reduction-level-assignment")) { loadProperties.add("reb2sac.abstraction.method.2.2=" + load.getProperty("reb2sac.abstraction.method.2.2")); } } else if (key.equals("reb2sac.abstraction.method.3.1")) { if (!load.getProperty("reb2sac.abstraction.method.3.1").equals( "kinetic-law-constants-simplifier") && !load.getProperty("reb2sac.abstraction.method.3.1").equals( "reversible-to-irreversible-transformer") && !load.getProperty("reb2sac.abstraction.method.3.1").equals( "nary-order-unary-transformer")) { loadProperties.add("reb2sac.abstraction.method.3.1=" + load.getProperty("reb2sac.abstraction.method.3.1")); } } else if (key.equals("reb2sac.abstraction.method.3.2")) { if (!load.getProperty("reb2sac.abstraction.method.3.2").equals( "kinetic-law-constants-simplifier") && !load.getProperty("reb2sac.abstraction.method.3.2").equals( "modifier-constant-propagation")) { loadProperties.add("reb2sac.abstraction.method.3.2=" + load.getProperty("reb2sac.abstraction.method.3.2")); } } else if (key.equals("reb2sac.abstraction.method.3.3")) { if (!load.getProperty("reb2sac.abstraction.method.3.3").equals( "absolute-inhibition-generator")) { loadProperties.add("reb2sac.abstraction.method.3.3=" + load.getProperty("reb2sac.abstraction.method.3.3")); } } else if (key.equals("reb2sac.abstraction.method.3.4")) { if (!load.getProperty("reb2sac.abstraction.method.3.4").equals( "final-state-generator")) { loadProperties.add("reb2sac.abstraction.method.3.4=" + load.getProperty("reb2sac.abstraction.method.3.4")); } } else if (key.equals("reb2sac.abstraction.method.3.5")) { if (!load.getProperty("reb2sac.abstraction.method.3.5").equals( "stop-flag-generator")) { loadProperties.add("reb2sac.abstraction.method.3.5=" + load.getProperty("reb2sac.abstraction.method.3.5")); } } else if (key.equals("reb2sac.nary.order.decider")) { if (!load.getProperty("reb2sac.nary.order.decider").equals("distinct")) { loadProperties.add("reb2sac.nary.order.decider=" + load.getProperty("reb2sac.nary.order.decider")); } } else if (key.equals("simulation.printer")) { if (!load.getProperty("simulation.printer").equals("tsd.printer")) { loadProperties.add("simulation.printer=" + load.getProperty("simulation.printer")); } } else if (key.equals("simulation.printer.tracking.quantity")) { if (!load.getProperty("simulation.printer.tracking.quantity").equals( "amount")) { loadProperties.add("simulation.printer.tracking.quantity=" + load.getProperty("simulation.printer.tracking.quantity")); } } else if (((String) key).length() > 27 && ((String) key).substring(0, 28).equals( "reb2sac.interesting.species.")) { } else if (key.equals("reb2sac.rapid.equilibrium.condition.1")) { } else if (key.equals("reb2sac.rapid.equilibrium.condition.2")) { } else if (key.equals("reb2sac.qssa.condition.1")) { } else if (key.equals("reb2sac.operator.max.concentration.threshold")) { } else if (key.equals("ode.simulation.time.limit")) { } else if (key.equals("ode.simulation.print.interval")) { } else if (key.equals("ode.simulation.number.steps")) { } else if (key.equals("ode.simulation.time.step")) { } else if (key.equals("ode.simulation.absolute.error")) { } else if (key.equals("ode.simulation.out.dir")) { } else if (key.equals("monte.carlo.simulation.time.limit")) { } else if (key.equals("monte.carlo.simulation.print.interval")) { } else if (key.equals("monte.carlo.simulation.number.steps")) { } else if (key.equals("monte.carlo.simulation.time.step")) { } else if (key.equals("monte.carlo.simulation.random.seed")) { } else if (key.equals("monte.carlo.simulation.runs")) { } else if (key.equals("monte.carlo.simulation.out.dir")) { } else if (key.equals("simulation.run.termination.decider")) { if (load.getProperty("simulation.run.termination.decider").equals("sad")) { sad.setEnabled(true); newSAD.setEnabled(true); usingSAD.setSelected(true); idLabel.setEnabled(true); TCid.setEnabled(true); descLabel.setEnabled(true); desc.setEnabled(true); condLabel.setEnabled(true); cond.setEnabled(true); addSAD.setEnabled(true); editSAD.setEnabled(true); removeSAD.setEnabled(true); // loadProperties.add( // "simulation.run.termination.decider=" // + load.getProperty( // "simulation.run.termination.decider")); } } else if (key.equals("computation.analysis.sad.path")) { } else if (key.equals("simulation.time.series.species.level.file")) { } else if (key.equals("reb2sac.simulation.method")) { } else if (key.equals("reb2sac.abstraction.method")) { } else if (key.equals("selected.simulator")) { } else if (key.equals("file.stem")) { } else if (((String) key).length() > 36 && ((String) key).substring(0, 37).equals( "simulation.run.termination.condition.")) { } else if (((String) key).length() > 37 && ((String) key).substring(0, 38).equals( "reb2sac.absolute.inhibition.threshold.")) { } else if (((String) key).length() > 27 && ((String) key).substring(0, 28).equals( "reb2sac.concentration.level.")) { } else if (((String) key).length() > 19 && ((String) key).substring(0, 20).equals("reb2sac.final.state.")) { } else if (key.equals("reb2sac.analysis.stop.enabled")) { } else if (key.equals("reb2sac.analysis.stop.rate")) { } else if (key.equals("monte.carlo.simulation.start.index")) { } else { loadProperties.add(key + "=" + load.getProperty((String) key)); } } props = loadProperties.toArray(props); properties.setListData(props); String[] getFilename = openFile.split(separator); int cut = 0; for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) { if (getFilename[getFilename.length - 1].charAt(i) == '.') { cut = i; } } String filename = ""; if (new File((openFile.substring(0, openFile.length() - getFilename[getFilename.length - 1].length())) + getFilename[getFilename.length - 1].substring(0, cut) + ".sbml").exists()) { filename = (openFile.substring(0, openFile.length() - getFilename[getFilename.length - 1].length())) + getFilename[getFilename.length - 1].substring(0, cut) + ".sbml"; } else if (new File((openFile.substring(0, openFile.length() - getFilename[getFilename.length - 1].length())) + getFilename[getFilename.length - 1].substring(0, cut) + ".xml").exists()) { filename = (openFile.substring(0, openFile.length() - getFilename[getFilename.length - 1].length())) + getFilename[getFilename.length - 1].substring(0, cut) + ".xml"; } try { filename = sbmlFile; ArrayList<String> listOfSpecs = new ArrayList<String>(); SBMLDocument document = BioSim.readSBML(filename); Model model = document.getModel(); if (model != null) { ListOf listOfSpecies = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { Species species = (Species) listOfSpecies.get(i); listOfSpecs.add(species.getId()); } } Object[] list = listOfSpecs.toArray(); for (int i = 1; i < list.length; i++) { String index = (String) list[i]; int j = i; while ((j > 0) && ((String) list[j - 1]).compareToIgnoreCase(index) > 0) { list[j] = list[j - 1]; j = j - 1; } list[j] = index; } intSpecies.setListData(list); termCond.setListData(list); int rem = availSpecies.getItemCount(); for (int i = 0; i < rem; i++) { availSpecies.removeItemAt(0); } for (int i = 0; i < list.length; i++) { availSpecies.addItem(((String) list[i]).replace(" ", "_")); } } catch (Exception e1) { } species.setListData(new Object[0]); terminations.setListData(new Object[0]); String check; if (load.containsKey("reb2sac.abstraction.method.3.1")) { check = load.getProperty("reb2sac.abstraction.method.3.1"); if (check.equals("kinetic-law-constants-simplifier")) { none.setSelected(true); Button_Enabling.enableNoneOrAbs(ODE, monteCarlo, markov, seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, none, intSpecies, species, spLabel, speciesLabel, addIntSpecies, removeIntSpecies, rapid1, rapid2, qssa, maxCon, rapidLabel1, rapidLabel2, qssaLabel, maxConLabel, usingSSA, clearIntSpecies, fileStem, fileStemLabel, lhpn); } } if (load.containsKey("reb2sac.abstraction.method.2.2")) { check = load.getProperty("reb2sac.abstraction.method.2.2"); if (check.equals("dimerization-reduction")) { abstraction.setSelected(true); Button_Enabling.enableNoneOrAbs(ODE, monteCarlo, markov, seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, none, intSpecies, species, spLabel, speciesLabel, addIntSpecies, removeIntSpecies, rapid1, rapid2, qssa, maxCon, rapidLabel1, rapidLabel2, qssaLabel, maxConLabel, usingSSA, clearIntSpecies, fileStem, fileStemLabel, lhpn); } else if (check.equals("dimerization-reduction-level-assignment")) { nary.setSelected(true); Button_Enabling.enableNary(ODE, monteCarlo, markov, seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, intSpecies, species, spLabel, speciesLabel, addIntSpecies, removeIntSpecies, rapid1, rapid2, qssa, maxCon, rapidLabel1, rapidLabel2, qssaLabel, maxConLabel, usingSSA, clearIntSpecies, fileStem, fileStemLabel, lhpn, gcmEditor); } } if (load.containsKey("ode.simulation.absolute.error")) { absErr.setText(load.getProperty("ode.simulation.absolute.error")); } else { absErr.setText("1.0E-9"); } if (load.containsKey("monte.carlo.simulation.time.step")) { step.setText(load.getProperty("monte.carlo.simulation.time.step")); } else { step.setText("inf"); } if (load.containsKey("monte.carlo.simulation.time.limit")) { limit.setText(load.getProperty("monte.carlo.simulation.time.limit")); } else { limit.setText("100.0"); } if (load.containsKey("monte.carlo.simulation.print.interval")) { intervalLabel.setSelectedItem("Print Interval"); interval.setText(load.getProperty("monte.carlo.simulation.print.interval")); } else if (load.containsKey("monte.carlo.simulation.number.steps")) { intervalLabel.setSelectedItem("Number Of Steps"); interval.setText(load.getProperty("monte.carlo.simulation.number.steps")); } else { interval.setText("1.0"); } if (load.containsKey("monte.carlo.simulation.random.seed")) { seed.setText(load.getProperty("monte.carlo.simulation.random.seed")); } if (load.containsKey("monte.carlo.simulation.runs")) { runs.setText(load.getProperty("monte.carlo.simulation.runs")); } if (load.containsKey("simulation.run.termination.decider") && load.getProperty("simulation.run.termination.decider").equals("sad")) { sad.setEnabled(true); newSAD.setEnabled(true); usingSAD.setSelected(true); idLabel.setEnabled(true); TCid.setEnabled(true); descLabel.setEnabled(true); desc.setEnabled(true); condLabel.setEnabled(true); cond.setEnabled(true); addSAD.setEnabled(true); editSAD.setEnabled(true); removeSAD.setEnabled(true); } if (load.containsKey("simulation.time.series.species.level.file")) { usingSSA.doClick(); } else { description.setEnabled(true); explanation.setEnabled(true); simulators.setEnabled(true); simulatorsLabel.setEnabled(true); newSSA.setEnabled(false); usingSSA.setSelected(false); ssa.setEnabled(false); timeLabel.setEnabled(false); time.setEnabled(false); availSpecies.setEnabled(false); ssaMod.setEnabled(false); ssaModNum.setEnabled(false); addSSA.setEnabled(false); editSSA.setEnabled(false); removeSSA.setEnabled(false); if (!nary.isSelected()) { ODE.setEnabled(true); } else { markov.setEnabled(true); } } if (load.containsKey("reb2sac.simulation.method")) { if (load.getProperty("reb2sac.simulation.method").equals("ODE")) { ODE.setSelected(true); if (load.containsKey("ode.simulation.time.limit")) { limit.setText(load.getProperty("ode.simulation.time.limit")); } if (load.containsKey("ode.simulation.print.interval")) { intervalLabel.setSelectedItem("Print Interval"); interval.setText(load.getProperty("ode.simulation.print.interval")); } else if (load.containsKey("ode.simulation.number.steps")) { intervalLabel.setSelectedItem("Number Of Steps"); interval.setText(load.getProperty("ode.simulation.number.steps")); } if (load.containsKey("ode.simulation.time.step")) { step.setText(load.getProperty("ode.simulation.time.step")); } Button_Enabling.enableODE(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, usingSSA, fileStem, fileStemLabel); if (load.containsKey("selected.simulator")) { simulators.setSelectedItem(load.getProperty("selected.simulator")); } if (load.containsKey("file.stem")) { fileStem.setText(load.getProperty("file.stem")); } if (load.containsKey("simulation.printer.tracking.quantity")) { if (load.getProperty("simulation.printer.tracking.quantity").equals( "amount")) { amounts.doClick(); } else if (load.getProperty("simulation.printer.tracking.quantity") .equals("concentration")) { concentrations.doClick(); } } } else if (load.getProperty("reb2sac.simulation.method").equals("monteCarlo")) { monteCarlo.setSelected(true); if (runFiles) { overwrite.setEnabled(true); append.setEnabled(true); choose3.setEnabled(true); } Button_Enabling.enableMonteCarlo(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, usingSSA, fileStem, fileStemLabel); if (load.containsKey("selected.simulator")) { simulators.setSelectedItem(load.getProperty("selected.simulator")); } if (load.containsKey("file.stem")) { fileStem.setText(load.getProperty("file.stem")); } absErr.setEnabled(false); } else if (load.getProperty("reb2sac.simulation.method").equals("markov")) { markov.setSelected(true); Button_Enabling.enableMarkov(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, usingSSA, fileStem, fileStemLabel, gcmEditor); absErr.setEnabled(false); } else if (load.getProperty("reb2sac.simulation.method").equals("SBML")) { sbml.setSelected(true); Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, fileStem, fileStemLabel); absErr.setEnabled(false); } else if (load.getProperty("reb2sac.simulation.method").equals("Network")) { dot.setSelected(true); Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, fileStem, fileStemLabel); absErr.setEnabled(false); } else if (load.getProperty("reb2sac.simulation.method").equals("Browser")) { xhtml.setSelected(true); Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, fileStem, fileStemLabel); absErr.setEnabled(false); } else if (load.getProperty("reb2sac.simulation.method").equals("LPHN")) { lhpn.setSelected(true); Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel, explanation, description, fileStem, fileStemLabel); absErr.setEnabled(false); } } if (load.containsKey("reb2sac.abstraction.method")) { if (load.getProperty("reb2sac.abstraction.method").equals("none")) { none.setSelected(true); abstraction.setSelected(false); nary.setSelected(false); } else if (load.getProperty("reb2sac.abstraction.method").equals("abs")) { none.setSelected(false); abstraction.setSelected(true); nary.setSelected(false); } else if (load.getProperty("reb2sac.abstraction.method").equals("nary")) { none.setSelected(false); abstraction.setSelected(false); nary.setSelected(true); } } ArrayList<String> getLists = new ArrayList<String>(); int i = 1; while (load.containsKey("simulation.run.termination.condition." + i)) { getLists.add(load.getProperty("simulation.run.termination.condition." + i)); i++; } termConditions = getLists.toArray(); terminations.setListData(termConditions); getLists = new ArrayList<String>(); i = 1; while (load.containsKey("reb2sac.interesting.species." + i)) { getLists.add(load.getProperty("reb2sac.interesting.species." + i)); i++; } interestingSpecies = getLists.toArray(); species.setListData(interestingSpecies); if (load.containsKey("reb2sac.rapid.equilibrium.condition.1")) { rapid1.setText(load.getProperty("reb2sac.rapid.equilibrium.condition.1")); } if (load.containsKey("reb2sac.rapid.equilibrium.condition.2")) { rapid2.setText(load.getProperty("reb2sac.rapid.equilibrium.condition.2")); } if (load.containsKey("reb2sac.qssa.condition.1")) { qssa.setText(load.getProperty("reb2sac.qssa.condition.1")); } if (load.containsKey("reb2sac.operator.max.concentration.threshold")) { maxCon .setText(load .getProperty("reb2sac.operator.max.concentration.threshold")); } } else { if (load.containsKey("selected.simulator")) { simulators.setSelectedItem(load.getProperty("selected.simulator")); } if (load.containsKey("file.stem")) { fileStem.setText(load.getProperty("file.stem")); } if (load.containsKey("simulation.printer.tracking.quantity")) { if (load.getProperty("simulation.printer.tracking.quantity").equals("amount")) { amounts.doClick(); } else if (load.getProperty("simulation.printer.tracking.quantity").equals( "concentration")) { concentrations.doClick(); } } } change = false; } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } } public Graph createGraph(String open) { String outDir = root + separator + simName; String printer_id = "tsd.printer"; String printer_track_quantity = "amount"; if (concentrations.isSelected()) { printer_track_quantity = "concentration"; } int[] index = species.getSelectedIndices(); species.setSelectedIndices(index); return new Graph(this, printer_track_quantity, simName + " simulation results", printer_id, outDir, "time", biomodelsim, open, log, null, true, false); } public JButton getRunButton() { return run; } public JButton getSaveButton() { return save; } public void setSbml(SBML_Editor sbml) { sbmlEditor = sbml; } public void setGcm(GCM2SBMLEditor gcm) { gcmEditor = gcm; if (nary.isSelected()) { lhpn.setEnabled(true); } if (markov.isSelected()) { simulators.removeAllItems(); simulators.addItem("markov-chain-analysis"); simulators.addItem("atacs"); simulators.addItem("ctmc-transient"); } change = false; } public void updateSpeciesList() { SBMLDocument document = BioSim.readSBML(sbmlFile); Model model = document.getModel(); ArrayList<String> listOfSpecs = new ArrayList<String>(); if (model != null) { ListOf listOfSpecies = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { Species species = (Species) listOfSpecies.get(i); listOfSpecs.add(species.getId()); } } Object[] list = listOfSpecs.toArray(); for (int i = 1; i < list.length; i++) { String index = (String) list[i]; int j = i; while ((j > 0) && ((String) list[j - 1]).compareToIgnoreCase(index) > 0) { list[j] = list[j - 1]; j = j - 1; } list[j] = index; } intSpecies.setListData(list); termCond.setListData(list); int rem = availSpecies.getItemCount(); for (int i = 0; i < rem; i++) { availSpecies.removeItemAt(0); } for (int i = 0; i < list.length; i++) { availSpecies.addItem(((String) list[i]).replace(" ", "_")); } } public void setSim(String newSimName) { sbmlProp = root + separator + newSimName + separator + sbmlFile.split(separator)[sbmlFile.split(separator).length - 1]; simName = newSimName; } public boolean hasChanged() { return change; } public void addToIntSpecies(String newSpecies) { JList addIntSpecies = new JList(); Object[] addObj = { newSpecies }; addIntSpecies.setListData(addObj); addIntSpecies.setSelectedIndex(0); interestingSpecies = Buttons.add(interestingSpecies, species, addIntSpecies, false, amountTerm, ge, gt, eq, lt, le, this); } public void removeIntSpecies() { String message = "These species cannot be removed.\n"; boolean displayMessage1 = false; if (usingSSA.isSelected()) { ArrayList<String> keepers = new ArrayList<String>(); for (int i = 0; i < ssaList.length; i++) { String[] get = ((String) ssaList[i]).split(" "); keepers.add(get[1]); } int[] selected = species.getSelectedIndices(); for (int i = 0; i < selected.length; i++) { for (int j = 0; j < keepers.size(); j++) { if ((keepers.get(j)).equals(interestingSpecies[selected[i]])) { species.removeSelectionInterval(selected[i], selected[i]); if (!displayMessage1) { message += "These species are used in user-defined data.\n"; displayMessage1 = true; } message += interestingSpecies[selected[i]] + "\n"; break; } } } } boolean displayMessage2 = false; if (usingSAD.isSelected()) { ArrayList<String> keepers = new ArrayList<String>(); for (int i = 0; i < sadList.length; i++) { String[] get = ((String) sadList[i]).split(";"); String cond = get[2]; cond = cond.replace('>', ' '); cond = cond.replace('<', ' '); cond = cond.replace('=', ' '); cond = cond.replace('&', ' '); cond = cond.replace('|', ' '); cond = cond.replace('+', ' '); cond = cond.replace('-', ' '); cond = cond.replace('*', ' '); cond = cond.replace('/', ' '); cond = cond.replace(' cond = cond.replace('%', ' '); cond = cond.replace('@', ' '); cond = cond.replace('(', ' '); cond = cond.replace(')', ' '); cond = cond.replace('!', ' '); get = cond.split(" "); for (int j = 0; j < get.length; j++) if (get[j].length() > 0) if ((get[j].charAt(0) != '0') && (get[j].charAt(0) != '1') && (get[j].charAt(0) != '2') && (get[j].charAt(0) != '3') && (get[j].charAt(0) != '4') && (get[j].charAt(0) != '5') && (get[j].charAt(0) != '6') && (get[j].charAt(0) != '7') && (get[j].charAt(0) != '8') && (get[j].charAt(0) != '9')) { keepers.add(get[j]); } } int[] selected = species.getSelectedIndices(); for (int i = 0; i < selected.length; i++) { for (int j = 0; j < keepers.size(); j++) { if ((keepers.get(j)).equals(interestingSpecies[selected[i]])) { species.removeSelectionInterval(selected[i], selected[i]); if (!displayMessage2) { message += "These species are used in termination conditions.\n"; displayMessage2 = true; } message += interestingSpecies[selected[i]] + "\n"; break; } } } } if (displayMessage1 || displayMessage2) { JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(biomodelsim.frame(), scroll, "Unable To Remove Species", JOptionPane.ERROR_MESSAGE); } interestingSpecies = Buttons.remove(species, interestingSpecies); } public Graph createProbGraph(String open) { String outDir = root + separator + simName; String printer_id = "tsd.printer"; String printer_track_quantity = "amount"; if (concentrations.isSelected()) { printer_track_quantity = "concentration"; } return new Graph(this, printer_track_quantity, simName + " simulation results", printer_id, outDir, "time", biomodelsim, open, log, null, false, false); } public void run() { } public JPanel getAdvanced() { JPanel constructPanel = new JPanel(new BorderLayout()); constructPanel.add(advanced, "Center"); JButton runButton = new JButton("Save and Run"); JButton saveButton = new JButton("Save Parameters"); JPanel runHolder = new JPanel(); runHolder.add(runButton); runButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { run.doClick(); } }); runButton.setMnemonic(KeyEvent.VK_R); runHolder.add(saveButton); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { save.doClick(); } }); saveButton.setMnemonic(KeyEvent.VK_S); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // runHolder, null); // splitPane.setDividerSize(0); // constructPanel.add(splitPane, "South"); return constructPanel; } public JPanel getProperties() { JPanel constructPanel = new JPanel(new BorderLayout()); constructPanel.add(propertiesPanel, "Center"); JButton runButton = new JButton("Save and Run"); JButton saveButton = new JButton("Save Parameters"); JPanel runHolder = new JPanel(); runHolder.add(runButton); runButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { run.doClick(); } }); runButton.setMnemonic(KeyEvent.VK_R); runHolder.add(saveButton); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { save.doClick(); } }); saveButton.setMnemonic(KeyEvent.VK_S); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, runHolder, null); splitPane.setDividerSize(0); constructPanel.add(splitPane, "South"); return constructPanel; } }
package com.v210.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.v210.dishes.home.model.DishBean; import com.v210.utils.ChineseToEnglish; import java.util.ArrayList; public class DBHelper extends SQLiteOpenHelper { private static final int VERSION = 1; public static final String TABLE_NAME = "DishesList"; public static final String DB_NAME = "DishesDB"; public static final String[] COLUMNS = { "id", "name", "price", "vipprice", "value", "img_path", "pinyin", "py_head" }; /** * SQLiteOpenHelper * * @param context * * @param name * * @param factory * @param version * */ public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { //super super(context, name, factory, version); } public DBHelper(Context context, String name, int version) { this(context, name, null, version); } public DBHelper(Context context) { this(context, DB_NAME, VERSION); } //SQLiteDatabase public void onCreate(SQLiteDatabase db) { //execSQLSQL db.execSQL("CREATE TABLE " + TABLE_NAME + " (id integer PRIMARY KEY AUTOINCREMENT DEFAULT NULL," + "name varchar(50) DEFAULT NULL," + "price INTEGER," + "vipprice INTEGER," + "value INTEGER," + "img_path varchar(255)," + "pinyin varchar(50) DEFAULT NULL," + "py_head varchar(50) DEFAULT NULL)"); initData(db); } public void initData(SQLiteDatabase db) { insertData(db, "", "3900", "3600"); insertData(db, "", "3900", "3600"); insertData(db, "", "3200", "2800"); insertData(db, "", "1800", "1500"); insertData(db, "", "3600", "3200"); insertData(db, "", "1800", "1500"); insertData(db, "", "3200", "2800"); insertData(db, "", "2800", "2600"); insertData(db, "", "3600", "3200"); insertData(db, "(3)", "800", "700"); insertData(db, "", "1800", "1600"); insertData(db, "", "2800", "2600"); insertData(db, "", "400", "300"); insertData(db, "", "3800", "3500"); insertData(db, "", "4200", "3800"); insertData(db, "", "900", "800"); insertData(db, "", "2600", "2200"); insertData(db, "", "2000", "1800"); insertData(db, "", "2800", "2600"); insertData(db, "", "6800", "5800"); insertData(db, "()", "3500", "2900"); insertData(db, "", "3600", "3200"); insertData(db, "", "1900", "1600"); insertData(db, "", "400", "300"); insertData(db, "", "4200", "3800"); insertData(db, "", "1900", "1600"); insertData(db, "", "2800", "2500"); insertData(db, "", "5200", "4600"); insertData(db, "", "1000", "800"); insertData(db, "", "4200", "3800"); insertData(db, "", "3200", "2900"); insertData(db, "", "5600", "4900"); insertData(db, "", "8800", "7800"); insertData(db, "", "4200", "3800"); insertData(db, "", "4600", "4200"); insertData(db, "", "7600", "6800"); insertData(db, "", "3200", "2800"); insertData(db, "", "6800", "5800"); insertData(db, "", "5600", "4800"); insertData(db, "", "3200", "2800"); insertData(db, "", "7800", "6800"); insertData(db, "", "4200", "3900"); insertData(db, "", "2500", "2200"); insertData(db, "", "4200", "3600"); insertData(db, "", "4800", "4200"); insertData(db, "", "2200", "2000"); insertData(db, "", "2900", "2600"); insertData(db, "", "5600", "4800"); insertData(db, "", "3200", "2800"); insertData(db, "", "8600", "7800"); insertData(db, "", "8800", "7800"); insertData(db, "", "3000", "2800"); insertData(db, "", "4200", "3800"); insertData(db, "", "7600", "6800"); insertData(db, "", "3200", "2900"); insertData(db, "", "2200", "1900"); insertData(db, "", "5200", "4800"); insertData(db, "", "5900", "5600"); insertData(db, "", "2800", "2500"); insertData(db, "", "3200", "2800"); insertData(db, "", "2600", "2200"); insertData(db, "", "2900", "2600"); insertData(db, "", "5600", "4800"); insertData(db, "", "8800", "7800"); insertData(db, "", "4200", "3800"); insertData(db, "", "2800", "2500"); insertData(db, "", "4800", "4500"); insertData(db, "", "6800", "5800"); insertData(db, "", "1800", "1600"); insertData(db, "", "4200", "3800"); insertData(db, "", "2200", "1900"); insertData(db, "", "5200", "4800"); insertData(db, "", "3200", "2900"); insertData(db, "", "2200", "2000"); insertData(db, "/", "900", "900"); insertData(db, "/", "6800", "6800"); insertData(db, "", "2200", "1900"); insertData(db, "", "5200", "4800"); insertData(db, "", "6200", "5800"); insertData(db, "", "2900", "2600"); insertData(db, "", "3200", "2800"); insertData(db, "", "3600", "3200"); insertData(db, "(,,)", "12800", "11800"); insertData(db, "(,,)", "8800", "7800"); insertData(db, "()/", "1600", "1200"); insertData(db, "", "12800", "11800"); insertData(db, "()", "8800", "7800"); insertData(db, "()", "8800", "7800"); insertData(db, "()", "8800", "7800"); // insertData(db, "", "7800", "6800"); insertData(db, "", "4200", "3600"); insertData(db, "", "2800", "2500"); insertData(db, "", "2800", "2600"); insertData(db, "", "2200", "1900"); insertData(db, "", "3200", "2800"); insertData(db, "", "4200", "3600"); insertData(db, "", "2600", "2200"); insertData(db, "", "2600", "2200"); insertData(db, "", "6800", "5800"); insertData(db, "", "2000", "1800"); insertData(db, "", "5600", "5200"); insertData(db, "", "5200", "4600"); insertData(db, "", "2000", "1800"); insertData(db, "", "900", "800"); insertData(db, "", "900", "800"); insertData(db, "", "900", "800"); insertData(db, "/", "600", "500"); insertData(db, "", "2600", "2200"); insertData(db, "", "2600", "2200"); insertData(db, "", "2600", "2200"); insertData(db, "", "2200", "1800"); insertData(db, "", "1800", "1500"); insertData(db, "", "2200", "2000"); insertData(db, "", "2600", "2200"); insertData(db, "", "3200", "2800"); insertData(db, "", "2200", "2000"); insertData(db, "", "2200", "2000"); insertData(db, "", "2200", "2000"); insertData(db, "2", "14800", "13800"); insertData(db, "1", "12800", "11800"); insertData(db, ",1", "7800", "6800"); insertData(db, "", "3600", "3200"); insertData(db, "", "3200", "2900"); insertData(db, "", "2600", "2200"); insertData(db, "", "3800", "2800"); insertData(db, "", "500", "400"); insertData(db, "", "6200", "5600"); insertData(db, "2/", "4800", "4500"); insertData(db, "3.8-5/", "5200", "4800"); insertData(db, "/", "1000", "1000"); insertData(db, "", "6200", "5800"); insertData(db, "", "4200", "3800"); insertData(db, "", "4200", "3900"); insertData(db, "/", "600", "500"); insertData(db, "", "1000", "800"); insertData(db, "", "3800", "3200"); insertData(db, "", "2200", "2200"); insertData(db, "", "4600", "3800"); insertData(db, "", "5600", "4800"); insertData(db, "", "3800", "3800"); insertData(db, "", "5800", "4800"); insertData(db, "", "1900", "1600"); insertData(db, "", "2200", "1900"); insertData(db, "", "4200", "3800"); insertData(db, "(100ml)", "800", "800"); insertData(db, "", "800", "800"); insertData(db, "", "1300", "1300"); insertData(db, "", "1600", "1600"); insertData(db, "", "2000", "2000"); insertData(db, "", "1600", "1600"); insertData(db, "", "1000", "1000"); insertData(db, "", "1000", "1000"); insertData(db, "", "500", "500"); insertData(db, "", "500", "500"); insertData(db, "", "600", "600"); insertData(db, "", "600", "600"); insertData(db, "", "4200", "3800"); insertData(db, "", "4200", "3800"); insertData(db, "", "900", "900"); insertData(db, "", "2500", "2500"); insertData(db, "", "300", "300"); insertData(db, "", "600", "600"); insertData(db, "", "1800", "1800"); insertData(db, "", "1000", "1000"); insertData(db, "", "1800", "900"); insertData(db, "", "1500", "1200"); insertData(db, "", "3200", "2800"); insertData(db, "", "3200", "2800"); insertData(db, "", "2900", "2600"); insertData(db, "", "5600", "2800"); insertData(db, "", "3800", "1900"); insertData(db, "", "3200", "2800"); insertData(db, "", "1900", "1600"); insertData(db, "", "2800", "2600"); insertData(db, "", "4200", "3600"); insertData(db, "", "2800", "2600"); insertData(db, "", "4800", "4200"); insertData(db, "", "8800", "7800"); insertData(db, "", "4200", "3800"); insertData(db, "", "3600", "3200"); insertData(db, "", "1800", "1600"); insertData(db, "", "2600", "2200"); insertData(db, "", "2900", "2600"); insertData(db, "", "2200", "2000"); insertData(db, "", "5200", "4600"); insertData(db, "", "4600", "3800"); insertData(db, "", "7600", "6800"); insertData(db, "", "5200", "4800"); insertData(db, "", "3200", "2800"); insertData(db, "", "2000", "1800"); insertData(db, "", "2800", "2600"); insertData(db, "", "5200", "4800"); insertData(db, "", "200", "200"); insertData(db, "", "2900", "2600"); insertData(db, "", "3900", "3900"); insertData(db, "", "5200", "4800"); insertData(db, "", "3600", "3600"); insertData(db, "", "2600", "2600"); insertData(db, "", "4200", "3800"); insertData(db, "", "2600", "2200"); insertData(db, "/", "6800", "6800"); insertData(db, "", "2600", "2200"); insertData(db, "", "2600", "2200"); insertData(db, "", "6200", "5800"); insertData(db, "", "8800", "7800"); insertData(db, "", "3800", "3600"); insertData(db, "", "7800", "6800"); insertData(db, "", "4800", "4200"); insertData(db, "", "3200", "3900"); insertData(db, "", "5600", "4800"); insertData(db, "", "5800", "5600"); insertData(db, "", "6200", "5800"); insertData(db, "", "2600", "2200"); insertData(db, "", "4200", "3200"); } public void insertData(SQLiteDatabase db, String name, String price, String vipPrice) { String insert = "insert into " + TABLE_NAME + " (name,price,vipprice,value,pinyin,py_head) values(\'" + name + "\'," + price + "," + vipPrice + "," + 0 + ",\'" + ChineseToEnglish.getPingYin(name) + "\',\'" + ChineseToEnglish.getPinYinHeadChar(name) + "\');"; db.execSQL(insert); } public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { } public void writeToDatabase(DishBean bean) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", bean.getName()); values.put("price", bean.getPrice()); values.put("vipprice", bean.getVipprice()); values.put("value", bean.getValue()); values.put("img_path", bean.getImgPath()); values.put("pinyin", bean.getPinyin()); values.put("py_head", bean.getPinyinHead()); db.insert(DBHelper.TABLE_NAME, null, values); db.close(); } public DishBean getByName(String name) { Cursor cursor=null; SQLiteDatabase db =this.getReadableDatabase(); cursor=db.rawQuery("select * from " + DBHelper.TABLE_NAME + " where name = '"+name.trim()+ "'",null); if (cursor != null && cursor.getCount() > 0) { if (cursor.moveToNext()) { DishBean bean = new DishBean(); fillBean(cursor, bean); return bean; } cursor.close(); db.close(); } return null; } /** * cursorbean * * @param pCursor * @param pBean */ private void fillBean(Cursor pCursor, DishBean pBean) { if (pCursor != null && pBean != null) { int id = pCursor.getInt(pCursor.getColumnIndex(DBHelper.COLUMNS[0])); String name = pCursor.getString(pCursor.getColumnIndex(DBHelper.COLUMNS[1])); int price = pCursor.getInt(pCursor.getColumnIndex(DBHelper.COLUMNS[2])); int vipPrice = pCursor.getInt(pCursor.getColumnIndex((DBHelper.COLUMNS[3]))); int value = pCursor.getInt(pCursor.getColumnIndex(DBHelper.COLUMNS[4])); String img_path = pCursor.getString(pCursor.getColumnIndex(DBHelper.COLUMNS[5])); String pinyin = pCursor.getString(pCursor.getColumnIndex(DBHelper.COLUMNS[6])); String py_head = pCursor.getString(pCursor.getColumnIndex(DBHelper.COLUMNS[7])); pBean.setId(id); pBean.setName(name); pBean.setPrice(price); pBean.setVipprice(vipPrice); pBean.setValue(value); pBean.setImgPath(img_path); pBean.setPinyin(pinyin); pBean.setPinyinHead(py_head); } } /** * * * @return */ public ArrayList<DishBean> getFromDatabase() { int pageSize = 20; int offVal = 0; Cursor cursor = null; SQLiteDatabase db = this.getWritableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, null, null, null, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { ArrayList<DishBean> data = new ArrayList<DishBean>(); while (cursor.moveToNext()) { DishBean bean = new DishBean(); fillBean(cursor, bean); data.add(bean); } cursor.close(); db.close(); return data; } return null; } public void updateToDatabase(ContentValues values, int id) { SQLiteDatabase database = this.getWritableDatabase(); database.update(TABLE_NAME, values, "id=?", new String[]{String.valueOf(id)}); database.close(); } }
package foam.nanos.auth; import foam.core.FObject; import foam.core.X; import foam.dao.DAO; import foam.dao.ProxyDAO; import foam.util.Password; import foam.util.SafetyUtil; import java.util.Calendar; public class UserPasswordHashingDAO extends ProxyDAO { public UserPasswordHashingDAO(X x, DAO delegate) { setX(x); setDelegate(delegate); } @Override public FObject put_(X x, FObject obj) { User user = (User) obj; User stored = (User) getDelegate().find(user.getId()); // hash desired password if provided if ( ! SafetyUtil.isEmpty(user.getDesiredPassword()) ) { user.setPassword(Password.hash(user.getDesiredPassword())); user.setPasswordLastModified(Calendar.getInstance().getTime()); // set previous password if present if ( stored != null && ! SafetyUtil.isEmpty(stored.getPassword()) ) { user.setPreviousPassword(stored.getPassword()); } } return super.put_(x, obj); } }
package com.wsfmn.habit; import java.util.Calendar; public class Date { int year; int month; int day; public Date(){ Calendar cal = Calendar.getInstance(); year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH) + 1; day = cal.get(Calendar.DAY_OF_MONTH); } public Date(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public int getDaysinMonth() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); return calendar.getActualMaximum(Calendar.DATE); } public int getDayOfWeek(){ int d = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); switch (d){ case 1: return 7; case 2: return 1; case 3: return 2; case 4: return 3; case 5: return 4; case 6: return 5; default: return 6; } } public boolean equalDate(Date date){ return this.getYear() == date.getYear() && this.getMonth() == date.getMonth() && this.getDay() == date.getDay(); } public int compareDate(Date date){ if(this.getYear() < date.getYear()) return -1; else if(this.getYear() > date.getYear()) return 1; else if(this.getMonth() < date.getMonth()) return -1; else if(this.getMonth() > date.getMonth()) return 1; else if(this.getDay() < date.getDay()) return -1; else if(this.getDay() > date.getDay()) return 1; else return 0; } public String toString(){ return year + " / " + month + " / " + day; } }
package it.faerb.crond; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Build; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.text.style.TypefaceSpan; import android.util.Log; import com.cronutils.descriptor.CronDescriptor; import com.cronutils.model.CronType; import com.cronutils.model.definition.CronDefinitionBuilder; import com.cronutils.model.time.ExecutionTime; import com.cronutils.parser.CronParser; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Locale; import java.util.MissingResourceException; import static it.faerb.crond.Constants.INTENT_EXTRA_LINE_NAME; import static it.faerb.crond.Constants.INTENT_EXTRA_LINE_NO_NAME; import static it.faerb.crond.Constants.PREFERENCES_FILE; import static it.faerb.crond.Constants.PREF_CRONTAB_HASH; import static it.faerb.crond.Constants.PREF_ENABLED; class Crond { private static final String TAG = "Crond"; private final CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX)); private CronDescriptor descriptor = null; private Context context = null; private AlarmManager alarmManager = null; private SharedPreferences sharedPrefs = null; private String crontab = ""; private static final String PREF_CRONTAB_LINE_COUNT = "old_tab_line_count"; private static final String HASH_ALGO = "sha-256"; public Crond(Context context) { this.context = context; alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); sharedPrefs = context.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE); try { descriptor = CronDescriptor.instance(Locale.getDefault()); } catch (MissingResourceException e) { Log.w(TAG, "Cannot find locale \"" + Locale.getDefault().toString() + "\". Switching to default locale."); descriptor = CronDescriptor.instance(); } } public SpannableStringBuilder processCrontab() { SpannableStringBuilder ret = new SpannableStringBuilder(); String hashedTab = ""; try { MessageDigest messageDigest = MessageDigest.getInstance(HASH_ALGO); messageDigest.update(crontab.getBytes()); hashedTab = new String(messageDigest.digest()); } catch (NoSuchAlgorithmException e) { Log.e(TAG, String.format("Algorithm %s not found:", HASH_ALGO)); e.printStackTrace(); } if (!hashedTab.equals(sharedPrefs.getString(PREF_CRONTAB_HASH, "")) && !crontab.equals("")) { // only schedule when enabled if (sharedPrefs.getBoolean(PREF_ENABLED, false)) { IO.logToLogFile(context.getString(R.string.log_crontab_change_detected)); scheduleCrontab(); } // save in any case such that on installation the crontab is not "new" sharedPrefs.edit().putString(PREF_CRONTAB_HASH, hashedTab).apply(); } if (crontab.equals("")) { return ret; } for (String line : crontab.split("\n")){ ret.append(line + "\n", new TypefaceSpan("monospace"), Spanned.SPAN_COMPOSING); ret.append(describeLine(line)); } return ret; } public void setCrontab(String crontab) { this.crontab = crontab; } public void scheduleCrontab() { cancelAllAlarms(sharedPrefs.getInt(PREF_CRONTAB_LINE_COUNT, 0)); // check here, because this can get called directly if (!sharedPrefs.getBoolean(PREF_ENABLED, false)) { return; } int i = 0; for (String line : crontab.split("\n")) { scheduleLine(line, i); i++; } sharedPrefs.edit().putInt(PREF_CRONTAB_LINE_COUNT, crontab.split("\n").length).apply(); } public void scheduleLine(String line, int lineNo) { ParsedLine parsedLine = parseLine(line); if (parsedLine == null) { return; } ExecutionTime time = ExecutionTime.forCron(parser.parse(parsedLine.cronExpr)); DateTime next = time.nextExecution(DateTime.now()); Intent intent = new Intent(context, AlarmReceiver.class); intent.putExtra(INTENT_EXTRA_LINE_NAME, line); intent.putExtra(INTENT_EXTRA_LINE_NO_NAME, lineNo); PendingIntent alarmIntent = PendingIntent.getBroadcast(context, lineNo, intent, PendingIntent.FLAG_UPDATE_CURRENT); // update current to replace the one used // for cancelling any previous set alarms alarmManager.set(AlarmManager.RTC_WAKEUP, next.getMillis(), alarmIntent); IO.logToLogFile(context.getString(R.string.log_scheduled, lineNo, DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSSS").print(next))); } public void executeLine(String line, int lineNo) { ParsedLine parsedLine = parseLine(line); if (parsedLine == null) { return; } IO.logToLogFile(context.getString(R.string.log_execute_pre, lineNo)); IO.executeCommand(parsedLine.runExpr); IO.logToLogFile(context.getString(R.string.log_execute_post, lineNo)); } private SpannableStringBuilder describeLine(String line) { SpannableStringBuilder ret = new SpannableStringBuilder(); ParsedLine parsedLine = parseLine(line); if (parsedLine == null) { ret.append(context.getResources().getString(R.string.invalid_cron) + "\n", new StyleSpan(Typeface.ITALIC), Spanned.SPAN_COMPOSING); } else { ret.append(context.getResources().getString(R.string.run) + " ", new StyleSpan(Typeface.ITALIC), Spanned.SPAN_COMPOSING); ret.append(parsedLine.runExpr + " ", new TypefaceSpan("monospace"), Spanned.SPAN_COMPOSING); ret.append(descriptor.describe(parser.parse(parsedLine.cronExpr)) + "\n", new StyleSpan(Typeface.ITALIC), Spanned.SPAN_COMPOSING); } if (Build.VERSION.SDK_INT >= 23) { ret.setSpan(new ForegroundColorSpan( context.getColor(R.color.colorPrimaryDark)), 0, ret.length(), Spanned.SPAN_COMPOSING); } else { ret.setSpan(new ForegroundColorSpan( context.getResources().getColor(R.color.colorPrimaryDark)), 0, ret.length(), Spanned.SPAN_COMPOSING); } return ret; } private void cancelAllAlarms(int oldTabLineCount) { Intent intent = new Intent(context, AlarmReceiver.class); for (int i = 0; i<oldTabLineCount; i++) { PendingIntent alarmIntent = PendingIntent.getBroadcast(context, i, intent, 0); alarmManager.cancel(alarmIntent); } } private ParsedLine parseLine(String line) { line = line.trim(); if (line.equals("")) { return null; } if (line.charAt(0) != '*' && !Character.isDigit(line.charAt(0))) { return null; } String [] splitLine = line.split(" "); if (splitLine.length < 6) { return null; } String[] cronExpr = Arrays.copyOfRange(splitLine, 0, 5); String[] runExpr = Arrays.copyOfRange(splitLine, 5, splitLine.length); String joinedCronExpr = TextUtils.join(" ", cronExpr); String joinedRunExpr = TextUtils.join(" ", runExpr); return new ParsedLine(joinedCronExpr, joinedRunExpr); } private class ParsedLine { final String cronExpr; final String runExpr; ParsedLine(String cronExpr, String runExpr) { this.cronExpr = cronExpr; this.runExpr = runExpr; } } }
package com.krishagni.catissueplus.core.biospecimen.services.impl; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import com.krishagni.catissueplus.core.administrative.domain.StorageContainer; import com.krishagni.catissueplus.core.administrative.domain.factory.StorageContainerErrorCode; import com.krishagni.catissueplus.core.administrative.events.StorageLocationSummary; import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenErrorCode; import com.krishagni.catissueplus.core.biospecimen.events.ContainerSpecimenDetail; import com.krishagni.catissueplus.core.biospecimen.events.SpecimenDetail; import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory; import com.krishagni.catissueplus.core.biospecimen.services.SpecimenService; import com.krishagni.catissueplus.core.common.Pair; import com.krishagni.catissueplus.core.common.PlusTransactional; import com.krishagni.catissueplus.core.common.TransactionalThreadLocals; import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException; import com.krishagni.catissueplus.core.common.events.RequestEvent; import com.krishagni.catissueplus.core.common.events.ResponseEvent; import com.krishagni.catissueplus.core.importer.events.ImportObjectDetail; import com.krishagni.catissueplus.core.importer.services.ObjectImporter; public class ContainerSpecimensImporter implements ObjectImporter<ContainerSpecimenDetail, ContainerSpecimenDetail> { private ThreadLocal<Map<String, StorageContainer>> containersByName = new ThreadLocal<Map<String, StorageContainer>>() { protected Map<String, StorageContainer> initialValue() { TransactionalThreadLocals.getInstance().register(this); return new HashMap<>(); } }; private ThreadLocal<Map<String, String>> barcodeToName = new ThreadLocal<Map<String, String>>() { protected Map<String, String> initialValue() { TransactionalThreadLocals.getInstance().register(this); return new HashMap<>(); } }; private DaoFactory daoFactory; private SpecimenService spmnSvc; public void setDaoFactory(DaoFactory daoFactory) { this.daoFactory = daoFactory; } public void setSpmnSvc(SpecimenService spmnSvc) { this.spmnSvc = spmnSvc; } @Override @PlusTransactional public ResponseEvent<ContainerSpecimenDetail> importObject(RequestEvent<ImportObjectDetail<ContainerSpecimenDetail>> req) { try { ImportObjectDetail<ContainerSpecimenDetail> importObj = req.getPayload(); StorageLocationSummary location = importObj.getObject().getLocation(); SpecimenDetail spmn = importObj.getObject().getSpecimen(); StorageContainer container = null; if (location == null) { return ResponseEvent.userError(SpecimenErrorCode.LOC_NOT_SPECIFIED); } else if (StringUtils.isNotBlank(location.getName())) { String name = location.getName().toLowerCase(); container = containersByName.get().get(name); if (container == null && !containersByName.get().containsKey(name)) { container = daoFactory.getStorageContainerDao().getByName(location.getName()); containersByName.get().put(name, container); } if (container == null) { return ResponseEvent.userError(StorageContainerErrorCode.NOT_FOUND, location.getName(), 1); } } else if (StringUtils.isNotBlank(location.getBarcode())) { String barcode = location.getBarcode().toLowerCase(); String name = barcodeToName.get().get(barcode); if (name != null) { container = containersByName.get().get(name); } else if (!barcodeToName.get().containsKey(barcode)) { container = daoFactory.getStorageContainerDao().getByBarcode(location.getBarcode()); barcodeToName.get().put(barcode, container != null ? container.getName().toLowerCase() : null); containersByName.get().put(container.getName().toLowerCase(), container); } if (container == null) { return ResponseEvent.userError(StorageContainerErrorCode.NOT_FOUND, location.getBarcode(), 1); } } if (container == null) { return ResponseEvent.userError(StorageContainerErrorCode.NAME_REQUIRED); } if (container.isDimensionless()) { return ResponseEvent.userError(SpecimenErrorCode.DIMLESS_CONTAINER); } String row = location.getPositionY(); String column = location.getPositionX(); if ((StringUtils.isBlank(row) || StringUtils.isBlank(column)) && location.getPosition() != null) { Pair<Integer, Integer> pos = container.getPositionAssigner().fromPosition(container, location.getPosition()); row = container.toRowLabelingScheme(pos.first()); column = container.toColumnLabelingScheme(pos.second()); } if (StringUtils.isBlank(row) || StringUtils.isBlank(column)) { return ResponseEvent.userError(SpecimenErrorCode.LOC_NOT_SPECIFIED); } if (!container.areValidPositions(column, row)) { return ResponseEvent.userError(StorageContainerErrorCode.INV_POS, container.getName(), column, row); } Long specimenId = daoFactory.getStorageContainerPositionDao() .getSpecimenIdByPosition(container.getId(), row, column); if (specimenId == null) { return ResponseEvent.userError(SpecimenErrorCode.NO_SPMN_AT_LOC); } spmn.setId(specimenId); SpecimenDetail result = ResponseEvent.unwrap(spmnSvc.updateSpecimen(RequestEvent.wrap(spmn))); return ResponseEvent.response(new ContainerSpecimenDetail(result.getStorageLocation(), result)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } }
package net.sf.taverna.t2.servicedescriptions; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.swing.Icon; import net.sf.taverna.t2.workflowmodel.processor.activity.Activity; public abstract class AbstractTemplateService<ConfigType> implements ServiceDescriptionProvider { protected TemplateServiceDescription templateService = new TemplateServiceDescription(); public void findServiceDescriptionsAsync( FindServiceDescriptionsCallBack callBack) { callBack.partialResults(Collections.singleton(templateService)); callBack.finished(); } public abstract Icon getIcon(); public abstract Class<? extends Activity<ConfigType>> getActivityClass(); public abstract ConfigType getActivityConfiguration(); public class TemplateServiceDescription extends ServiceDescription<ConfigType> { public Icon getIcon() { return AbstractTemplateService.this.getIcon(); } public String getName() { return AbstractTemplateService.this.getName(); } public List<String> getPath() { return Arrays.asList(SERVICE_TEMPLATES); } public boolean isTemplateService() { return true; } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return AbstractTemplateService.this.hashCode(); } @Override public Class<? extends Activity<ConfigType>> getActivityClass() { return AbstractTemplateService.this.getActivityClass(); } @Override public ConfigType getActivityConfiguration() { return AbstractTemplateService.this.getActivityConfiguration(); } } @Override public String toString() { return "Template service " + getName(); } }
package com.handstandsam.httpmocking.tests.wiremock; import android.content.Context; import android.support.test.InstrumentationRegistry; import com.github.tomakehurst.wiremock.WireMockServer; import com.joshskeen.weatherview.BuildConfig; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.handstandsam.httpmocking.util.AssetReaderUtil.asset; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class WireMockApplicationTestCase { Logger logger = LoggerFactory.getLogger(WireMockApplicationTestCase.class); private Context applicationContext; WireMockServer wireMockServer = new WireMockServer(BuildConfig.PORT); @Before public void setUp() { applicationContext = InstrumentationRegistry.getTargetContext().getApplicationContext(); wireMockServer.start(); } @After public void tearDown() throws Exception { wireMockServer.stop(); } /** * Test WireMock, but just the Http Call. Make sure the response matches the mock we want. */ @Test public void testWiremockPlusOkHttp() throws IOException { logger.debug("testWiremockPlusOkHttp"); String uri = "/api/840dbdf2737a7ff9/conditions/q/CA/atlanta.json"; String jsonBody = asset(applicationContext, "atlanta-conditions.json"); assertFalse(jsonBody.isEmpty()); wireMockServer.stubFor(get(urlMatching(uri)) .willReturn(aResponse() .withStatus(200) .withBody(jsonBody))); String serviceEndpoint = "http://127.0.0.1:" + BuildConfig.PORT; logger.debug("WireMock Endpoint: " + serviceEndpoint); OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .url(serviceEndpoint + uri) .build(); Response response = okHttpClient.newCall(request).execute(); assertEquals(jsonBody, response.body().string()); } }
package aQute.bnd.osgi; import static java.util.Objects.requireNonNull; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.ElementType; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators.AbstractSpliterator; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import aQute.bnd.osgi.Descriptors.Descriptor; import aQute.bnd.osgi.Descriptors.PackageRef; import aQute.bnd.osgi.Descriptors.TypeRef; import aQute.bnd.signatures.FieldSignature; import aQute.bnd.signatures.MethodSignature; import aQute.bnd.signatures.Signature; import aQute.lib.exceptions.Exceptions; import aQute.lib.io.ByteBufferDataInput; import aQute.lib.utf8properties.UTF8Properties; import aQute.libg.generics.Create; public class Clazz { private final static Logger logger = LoggerFactory.getLogger(Clazz.class); public class ClassConstant { final int cname; public boolean referred; public ClassConstant(int class_index) { this.cname = class_index; } public String getName() { return (String) pool[cname]; } @Override public String toString() { return "ClassConstant[" + getName() + "]"; } } public static enum JAVA { JDK1_1(45, "JRE-1.1", "(&(osgi.ee=JavaSE)(version=1.1))"), JDK1_2(46, "J2SE-1.2", "(&(osgi.ee=JavaSE)(version=1.2))"), JDK1_3(47, "J2SE-1.3", "(&(osgi.ee=JavaSE)(version=1.3))"), JDK1_4(48, "J2SE-1.4", "(&(osgi.ee=JavaSE)(version=1.4))"), J2SE5(49, "J2SE-1.5", "(&(osgi.ee=JavaSE)(version=1.5))"), J2SE6(50, "JavaSE-1.6", "(&(osgi.ee=JavaSE)(version=1.6))"), OpenJDK7(51, "JavaSE-1.7", "(&(osgi.ee=JavaSE)(version=1.7))"), OpenJDK8(52, "JavaSE-1.8", "(&(osgi.ee=JavaSE)(version=1.8))") { Map<String, Set<String>> profiles; @Override public Map<String, Set<String>> getProfiles() throws IOException { if (profiles == null) { Properties p = new UTF8Properties(); try (InputStream in = Clazz.class.getResourceAsStream("profiles-" + this + ".properties")) { p.load(in); } profiles = new HashMap<>(); for (Map.Entry<Object, Object> prop : p.entrySet()) { String list = (String) prop.getValue(); Set<String> set = new HashSet<>(); Collections.addAll(set, list.split("\\s*,\\s*")); profiles.put((String) prop.getKey(), set); } } return profiles; } }, OpenJDK9(53, "JavaSE-9", "(&(osgi.ee=JavaSE)(version=9))"), OpenJDK10(54, "JavaSE-10", "(&(osgi.ee=JavaSE)(version=10))"), OpenJDK11(55, "JavaSE-11", "(&(osgi.ee=JavaSE)(version=11))"), UNKNOWN(Integer.MAX_VALUE, "<UNKNOWN>", "(osgi.ee=UNKNOWN)"); final int major; final String ee; final String filter; JAVA(int major, String ee, String filter) { this.major = major; this.ee = ee; this.filter = filter; } static JAVA format(int n) { for (JAVA e : JAVA.values()) if (e.major == n) return e; return UNKNOWN; } public int getMajor() { return major; } public boolean hasAnnotations() { return major >= J2SE5.major; } public boolean hasGenerics() { return major >= J2SE5.major; } public boolean hasEnums() { return major >= J2SE5.major; } public static JAVA getJava(int major, @SuppressWarnings("unused") int minor) { for (JAVA j : JAVA.values()) { if (j.major == major) return j; } return UNKNOWN; } public String getEE() { return ee; } public String getFilter() { return filter; } public Map<String, Set<String>> getProfiles() throws IOException { return null; } } public static enum QUERY { IMPLEMENTS, EXTENDS, IMPORTS, NAMED, ANY, VERSION, CONCRETE, ABSTRACT, PUBLIC, ANNOTATED, INDIRECTLY_ANNOTATED, HIERARCHY_ANNOTATED, HIERARCHY_INDIRECTLY_ANNOTATED, RUNTIMEANNOTATIONS, CLASSANNOTATIONS, DEFAULT_CONSTRUCTOR; } interface ConstantInfo { void accept(Clazz c, CONSTANT tag, DataInput in, int poolIndex) throws IOException; } static enum CONSTANT { Zero(CONSTANT::invalid), Utf8(Clazz::doUtf8_info), Two(CONSTANT::invalid), Integer(Clazz::doInteger_info), Float(Clazz::doFloat_info), Long(Clazz::doLong_info), Double(Clazz::doDouble_info), Class(Clazz::doClass_info), String(Clazz::doString_info), Fieldref(Clazz::doFieldref_info), Methodref(Clazz::doMethodref_info), InterfaceMethodref(Clazz::doInterfaceMethodref_info), NameAndType(Clazz::doNameAndType_info), Thirteen(CONSTANT::invalid), Fourteen(CONSTANT::invalid), MethodHandle(Clazz::doMethodHandle_info), MethodType(Clazz::doMethodType_info), Dynamic(Clazz::doDynamic_info), InvokeDynamic(Clazz::doInvokeDynamic_info), Module(Clazz::doModule_info), Package(Clazz::doPackage_info); private final ConstantInfo info; private final int width; CONSTANT(ConstantInfo info) { this.info = requireNonNull(info); // For some insane optimization reason, // the Long(5) and Double(6) entries take two slots in the // constant pool. See 4.4.5 int value = ordinal(); width = ((value == 5) || (value == 6)) ? 2 : 1; } int parse(Clazz c, DataInput in, int poolIndex) throws IOException { info.accept(c, this, in, poolIndex); return width; } private static void invalid(Clazz c, CONSTANT tag, DataInput in, int poolIndex) throws IOException { throw new IOException("Invalid constant pool tag " + tag.ordinal()); } } public final static EnumSet<QUERY> HAS_ARGUMENT = EnumSet.of(QUERY.IMPLEMENTS, QUERY.EXTENDS, QUERY.IMPORTS, QUERY.NAMED, QUERY.VERSION, QUERY.ANNOTATED, QUERY.INDIRECTLY_ANNOTATED, QUERY.HIERARCHY_ANNOTATED, QUERY.HIERARCHY_INDIRECTLY_ANNOTATED); // Declared public; may be accessed from outside its package. final static int ACC_PUBLIC = 0x0001; // Declared final; no subclasses allowed. final static int ACC_FINAL = 0x0010; // Treat superclass methods specially when invoked by the invokespecial // instruction. final static int ACC_SUPER = 0x0020; // Is an interface, not a class final static int ACC_INTERFACE = 0x0200; // Declared a thing not in the source code final static int ACC_ABSTRACT = 0x0400; final static int ACC_SYNTHETIC = 0x1000; final static int ACC_BRIDGE = 0x0040; final static int ACC_ANNOTATION = 0x2000; final static int ACC_ENUM = 0x4000; final static int ACC_MODULE = 0x8000; static protected class Assoc { final CONSTANT tag; final int a; final int b; Assoc(CONSTANT tag, int a, int b) { this.tag = tag; this.a = a; this.b = b; } @Override public String toString() { return "Assoc[" + tag + ", " + a + "," + b + "]"; } } public abstract class Def { final int access; Set<TypeRef> annotations; public Def(int access) { this.access = access; } public int getAccess() { return access; } public boolean isEnum() { return (access & ACC_ENUM) != 0; } public boolean isPublic() { return Modifier.isPublic(access); } public boolean isAbstract() { return Modifier.isAbstract(access); } public boolean isProtected() { return Modifier.isProtected(access); } public boolean isFinal() { return Modifier.isFinal(access) || Clazz.this.isFinal(); } public boolean isStatic() { return Modifier.isStatic(access); } public boolean isPrivate() { return Modifier.isPrivate(access); } public boolean isNative() { return Modifier.isNative(access); } public boolean isTransient() { return Modifier.isTransient(access); } public boolean isVolatile() { return Modifier.isVolatile(access); } public boolean isInterface() { return Modifier.isInterface(access); } public boolean isSynthetic() { return (access & ACC_SYNTHETIC) != 0; } void addAnnotation(Annotation a) { if (annotations == null) annotations = Create.set(); annotations.add(analyzer.getTypeRef(a.getName() .getBinary())); } public Collection<TypeRef> getAnnotations() { return annotations; } public TypeRef getOwnerType() { return className; } public abstract String getName(); public abstract TypeRef getType(); public abstract TypeRef[] getPrototype(); public Object getClazz() { return Clazz.this; } } public class FieldDef extends Def { final String name; final Descriptor descriptor; String signature; Object constant; boolean deprecated; public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public FieldDef(int access, String name, String descriptor) { super(access); this.name = name; this.descriptor = analyzer.getDescriptor(descriptor); } @Override public String getName() { return name; } @Override public TypeRef getType() { return descriptor.getType(); } public TypeRef getContainingClass() { return getClassName(); } public Descriptor getDescriptor() { return descriptor; } public void setConstant(Object o) { this.constant = o; } public Object getConstant() { return this.constant; } public String getGenericReturnType() { FieldSignature sig = analyzer.getFieldSignature((signature != null) ? signature : descriptor.toString()); return sig.type.toString(); } @Override public TypeRef[] getPrototype() { return null; } public String getSignature() { return signature; } @Override public String toString() { return name; } } public static class MethodParameter { final String name; final int access_flags; MethodParameter(String name, int access_flags) { this.name = name; this.access_flags = access_flags; } public String getName() { return name; } public int getAccess() { return access_flags; } @Override public String toString() { return getName(); } } public class MethodDef extends FieldDef { MethodParameter[] parameters; public MethodDef(int access, String method, String descriptor) { super(access, method, descriptor); } public boolean isConstructor() { return name.equals("<init>") || name.equals("<clinit>"); } @Override public TypeRef[] getPrototype() { return descriptor.getPrototype(); } public boolean isBridge() { return (access & ACC_BRIDGE) != 0; } @Override public String getGenericReturnType() { MethodSignature sig = analyzer.getMethodSignature((signature != null) ? signature : descriptor.toString()); return sig.resultType.toString(); } public MethodParameter[] getParameters() { return parameters; } } public class TypeDef extends Def { final TypeRef type; final boolean interf; public TypeDef(TypeRef type, boolean interf) { super(Modifier.PUBLIC); this.type = type; this.interf = interf; } public TypeRef getReference() { return type; } public boolean getImplements() { return interf; } @Override public String getName() { if (interf) return "<implements>"; return "<extends>"; } @Override public TypeRef getType() { return type; } @Override public TypeRef[] getPrototype() { return null; } } public static final Comparator<Clazz> NAME_COMPARATOR = (Clazz a, Clazz b) -> a.className.compareTo(b.className); boolean hasRuntimeAnnotations; boolean hasClassAnnotations; boolean hasDefaultConstructor; int depth = 0; Deque<ClassDataCollector> cds = new LinkedList<>(); TypeRef className; Object[] pool; int[] intPool; Set<PackageRef> imports = Create.set(); String path; int minor_version = 0; int major_version = 0; int innerAccess = -1; int accessx = 0; String sourceFile; Set<TypeRef> xref; Set<TypeRef> annotations; int forName = 0; int class$ = 0; TypeRef[] interfaces; TypeRef zuper; ClassDataCollector cd = null; Resource resource; FieldDef last = null; boolean deprecated; Set<PackageRef> api; final Analyzer analyzer; String classSignature; private Map<String, Object> defaults; public static final int TYPEUSE_INDEX_NONE = -1; public static final int TYPEUSE_TARGET_INDEX_EXTENDS = 65535; public Clazz(Analyzer analyzer, String path, Resource resource) { this.path = path; this.resource = resource; this.analyzer = analyzer; } public Set<TypeRef> parseClassFile() throws Exception { return parseClassFileWithCollector(null); } public Set<TypeRef> parseClassFile(InputStream in) throws Exception { return parseClassFile(in, null); } public Set<TypeRef> parseClassFileWithCollector(ClassDataCollector cd) throws Exception { ByteBuffer bb = resource.buffer(); if (bb != null) { return parseClassFileData(ByteBufferDataInput.wrap(bb), cd); } return parseClassFile(resource.openInputStream(), cd); } public Set<TypeRef> parseClassFile(InputStream in, ClassDataCollector cd) throws Exception { try (DataInputStream din = new DataInputStream(in)) { return parseClassFileData(din, cd); } } Set<TypeRef> parseClassFileData(DataInput in, ClassDataCollector cd) throws Exception { cds.push(this.cd); this.cd = cd; try { return parseClassFileData(in); } finally { this.cd = cds.pop(); } } Set<TypeRef> parseClassFileData(DataInput in) throws Exception { logger.debug("parseClassFile(): path={} resource={}", path, resource); ++depth; xref = new HashSet<>(); int magic = in.readInt(); if (magic != 0xCAFEBABE) { throw new IOException("Not a valid class file (no CAFEBABE header)"); } minor_version = in.readUnsignedShort(); // minor version major_version = in.readUnsignedShort(); // major version int constant_pool_count = in.readUnsignedShort(); pool = new Object[constant_pool_count]; intPool = new int[constant_pool_count]; CONSTANT[] tags = CONSTANT.values(); for (int poolIndex = 1; poolIndex < constant_pool_count;) { int tagValue = in.readUnsignedByte(); if (tagValue >= tags.length) { throw new IOException("Unrecognized constant pool tag value " + tagValue); } CONSTANT tag = tags[tagValue]; poolIndex += tag.parse(this, in, poolIndex); } /* * Parse after the constant pool, code thanks to Hans Christian * Falkenberg */ accessx = in.readUnsignedShort(); // access if (isPublic()) { api = new HashSet<>(); } int this_class = in.readUnsignedShort(); className = analyzer.getTypeRef((String) pool[intPool[this_class]]); int super_class = in.readUnsignedShort(); if (super_class == 0) { if (!(className.isObject() || isModule())) { throw new IOException("Class does not have a super class and is not java.lang.Object or module-info"); } } else { String superName = (String) pool[intPool[super_class]]; zuper = analyzer.getTypeRef(superName); } int interfaces_count = in.readUnsignedShort(); if (interfaces_count > 0) { interfaces = new TypeRef[interfaces_count]; for (int i = 0; i < interfaces_count; i++) { String interfaceName = (String) pool[intPool[in.readUnsignedShort()]]; interfaces[i] = analyzer.getTypeRef(interfaceName); } } ClassDataCollectorRecorder recorder; if (cd != null) { if (!cd.classStart(this)) { return null; } cds.push(cd); cd = recorder = new ClassDataCollectorRecorder(); } else { recorder = null; } try { if (cd != null) { cd.version(minor_version, major_version); } // All name&type and class constant records contain descriptors we // must treat as references, though not API for (Object o : pool) { if (o instanceof Assoc) { Assoc assoc = (Assoc) o; switch (assoc.tag) { case Fieldref : case Methodref : case InterfaceMethodref : classConstRef(assoc.a); break; case NameAndType : referTo(assoc.b, 0); // field or method descriptor break; case MethodType : referTo(assoc.b, 0); // method descriptor break; default : break; } } } if (!isModule()) { referTo(className, Modifier.PUBLIC); } if (zuper != null) { referTo(zuper, accessx); if (cd != null) { cd.extendsClass(zuper); } } if (interfaces_count > 0) { for (TypeRef i : interfaces) { referTo(i, accessx); } if (cd != null) { cd.implementsInterfaces(interfaces); } } boolean crawl = cd != null; // Crawl the byte code if we have a // collector int fieldsCount = in.readUnsignedShort(); for (int i = 0; i < fieldsCount; i++) { int access_flags = in.readUnsignedShort(); // skip access flags int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); // Java prior to 1.5 used a weird // static variable to hold the com.X.class // result construct. If it did not find it // it would create a variable class$com$X // that would be used to hold the class // object gotten with Class.forName ... // Stupidly, they did not actively use the // class name for the field type, so bnd // would not see a reference. We detect // this case and add an artificial descriptor String name = pool[name_index].toString(); // name_index String descriptor = pool[descriptor_index].toString(); if (name.startsWith("class$") || name.startsWith("$class$")) { crawl = true; } if (cd != null) { FieldDef fdef = new FieldDef(access_flags, name, descriptor); last = fdef; cd.field(fdef); } referTo(descriptor_index, access_flags); // field descriptor doAttributes(in, ElementType.FIELD, false, access_flags); } // Check if we have to crawl the code to find // the ldc(_w) <string constant> invokestatic Class.forName // if so, calculate the method ref index so we // can do this efficiently if (crawl) { forName = findMethodReference("java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); class$ = findMethodReference(className.getBinary(), "class$", "(Ljava/lang/String;)Ljava/lang/Class;"); } else if (major_version == JAVA.JDK1_4.major) { forName = findMethodReference("java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); if (forName > 0) { crawl = true; class$ = findMethodReference(className.getBinary(), "class$", "(Ljava/lang/String;)Ljava/lang/Class;"); } } // There are some serious changes in the // class file format. So we do not do any crawling // it has also become less important // however, jDK8 has a bug that leaves an orphan ClassConstnat // so if we have those, we need to also crawl the byte codes. if (!crawl) { // This loop is overeager since we have not processed exceptions // and bootstrap method arguments, so we may crawl when we do // not need to. for (Object o : pool) { if (o instanceof ClassConstant) { ClassConstant cc = (ClassConstant) o; if (cc.referred == false) { crawl = true; break; } } } } // Handle the methods int methodCount = in.readUnsignedShort(); for (int i = 0; i < methodCount; i++) { int access_flags = in.readUnsignedShort(); int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); String name = pool[name_index].toString(); String descriptor = pool[descriptor_index].toString(); if (cd != null) { MethodDef mdef = new MethodDef(access_flags, name, descriptor); last = mdef; cd.method(mdef); } referTo(descriptor_index, access_flags); // method descriptor if ("<init>".equals(name)) { if (Modifier.isPublic(access_flags) && "()V".equals(descriptor)) { hasDefaultConstructor = true; } doAttributes(in, ElementType.CONSTRUCTOR, crawl, access_flags); } else { doAttributes(in, ElementType.METHOD, crawl, access_flags); } } if (cd != null) { cd.memberEnd(); } last = null; ElementType member; if (isAnnotation()) { member = ElementType.ANNOTATION_TYPE; } else if (className.getBinary() .endsWith("/package-info")) { member = ElementType.PACKAGE; } else { member = ElementType.TYPE; } doAttributes(in, member, false, accessx); Set<TypeRef> xref = this.xref; reset(); return xref; } finally { if (recorder != null) { cd = cds.pop(); try { recorder.play(cd); } finally { cd.classEnd(); } } } } void doUtf8_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { String name = in.readUTF(); pool[poolIndex] = name; } void doInteger_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int i = in.readInt(); intPool[poolIndex] = i; if (cd != null) { pool[poolIndex] = Integer.valueOf(i); } } void doFloat_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { if (cd != null) { pool[poolIndex] = Float.valueOf(in.readFloat()); // ALU } else { in.skipBytes(4); } } void doLong_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { if (cd != null) { pool[poolIndex] = Long.valueOf(in.readLong()); } else { in.skipBytes(8); } } void doDouble_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { if (cd != null) { pool[poolIndex] = Double.valueOf(in.readDouble()); } else { in.skipBytes(8); } } void doClass_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int class_index = in.readUnsignedShort(); intPool[poolIndex] = class_index; ClassConstant c = new ClassConstant(class_index); pool[poolIndex] = c; } void doString_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int string_index = in.readUnsignedShort(); intPool[poolIndex] = string_index; } void doFieldref_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int class_index = in.readUnsignedShort(); int name_and_type_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc(tag, class_index, name_and_type_index); } void doMethodref_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int class_index = in.readUnsignedShort(); int name_and_type_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc(tag, class_index, name_and_type_index); } void doInterfaceMethodref_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int class_index = in.readUnsignedShort(); int name_and_type_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc(tag, class_index, name_and_type_index); } void doNameAndType_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc(tag, name_index, descriptor_index); } void doMethodHandle_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int reference_kind = in.readUnsignedByte(); int reference_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc(tag, reference_kind, reference_index); } void doMethodType_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int descriptor_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc(tag, 0, descriptor_index); } void doDynamic_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int bootstrap_method_attr_index = in.readUnsignedShort(); int name_and_type_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc(tag, bootstrap_method_attr_index, name_and_type_index); } void doInvokeDynamic_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { int bootstrap_method_attr_index = in.readUnsignedShort(); int name_and_type_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc(tag, bootstrap_method_attr_index, name_and_type_index); } void doModule_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { in.skipBytes(2); } void doPackage_info(CONSTANT tag, DataInput in, int poolIndex) throws IOException { in.skipBytes(2); } /** * Find a method reference in the pool that points to the given class, * methodname and descriptor. * * @param clazz * @param methodname * @param descriptor * @return index in constant pool */ private int findMethodReference(String clazz, String methodname, String descriptor) { for (int i = 1; i < pool.length; i++) { if (pool[i] instanceof Assoc) { Assoc methodref = (Assoc) pool[i]; switch (methodref.tag) { case Methodref : case InterfaceMethodref : { // Method ref int class_index = methodref.a; int class_name_index = intPool[class_index]; if (clazz.equals(pool[class_name_index])) { int name_and_type_index = methodref.b; Assoc name_and_type = (Assoc) pool[name_and_type_index]; if (name_and_type.tag == CONSTANT.NameAndType) { // Name and Type int name_index = name_and_type.a; int type_index = name_and_type.b; if (methodname.equals(pool[name_index])) { if (descriptor.equals(pool[type_index])) { return i; } } } } break; } default : break; } } } return -1; } /** * Called for each attribute in the class, field, or method. * * @param in The stream * @param access_flags * @throws Exception */ private void doAttributes(DataInput in, ElementType member, boolean crawl, int access_flags) throws Exception { int attributesCount = in.readUnsignedShort(); for (int j = 0; j < attributesCount; j++) { doAttribute(in, member, crawl, access_flags); } } /** * Process a single attribute, if not recognized, skip it. * * @param in the data stream * @param access_flags * @throws Exception */ private void doAttribute(DataInput in, ElementType member, boolean crawl, int access_flags) throws Exception { final int attribute_name_index = in.readUnsignedShort(); final String attributeName = (String) pool[attribute_name_index]; final int attribute_length = in.readInt(); switch (attributeName) { case "Deprecated" : doDeprecated(in, member); break; case "RuntimeVisibleAnnotations" : doAnnotations(in, member, RetentionPolicy.RUNTIME, access_flags); break; case "RuntimeInvisibleAnnotations" : doAnnotations(in, member, RetentionPolicy.CLASS, access_flags); break; case "RuntimeVisibleParameterAnnotations" : doParameterAnnotations(in, ElementType.PARAMETER, RetentionPolicy.RUNTIME, access_flags); break; case "RuntimeInvisibleParameterAnnotations" : doParameterAnnotations(in, ElementType.PARAMETER, RetentionPolicy.CLASS, access_flags); break; case "RuntimeVisibleTypeAnnotations" : doTypeAnnotations(in, ElementType.TYPE_USE, RetentionPolicy.RUNTIME, access_flags); break; case "RuntimeInvisibleTypeAnnotations" : doTypeAnnotations(in, ElementType.TYPE_USE, RetentionPolicy.CLASS, access_flags); break; case "InnerClasses" : doInnerClasses(in); break; case "EnclosingMethod" : doEnclosingMethod(in); break; case "SourceFile" : doSourceFile(in); break; case "Code" : doCode(in, crawl); break; case "Signature" : doSignature(in, member, access_flags); break; case "ConstantValue" : doConstantValue(in); break; case "AnnotationDefault" : doAnnotationDefault(in, member, access_flags); break; case "Exceptions" : doExceptions(in, access_flags); break; case "BootstrapMethods" : doBootstrapMethods(in); break; case "StackMapTable" : doStackMapTable(in); break; case "NestHost" : doNestHost(in); break; case "NestMembers" : doNestMembers(in); break; case "MethodParameters" : doMethodParameters(in); break; default : if (attribute_length < 0) { throw new IllegalArgumentException("Attribute > 2Gb"); } in.skipBytes(attribute_length); break; } } /** * <pre> * EnclosingMethod_attribute { u2 attribute_name_index; u4 * attribute_length; u2 class_index u2 method_index; } * </pre> * * @param in * @throws IOException */ private void doEnclosingMethod(DataInput in) throws IOException { int cIndex = in.readUnsignedShort(); int mIndex = in.readUnsignedShort(); classConstRef(cIndex); if (cd != null) { int nameIndex = intPool[cIndex]; TypeRef cName = analyzer.getTypeRef((String) pool[nameIndex]); String mName = null; String mDescriptor = null; if (mIndex != 0) { Assoc nameAndType = (Assoc) pool[mIndex]; mName = (String) pool[nameAndType.a]; mDescriptor = (String) pool[nameAndType.b]; } cd.enclosingMethod(cName, mName, mDescriptor); } } /** * <pre> * InnerClasses_attribute { u2 attribute_name_index; u4 * attribute_length; u2 number_of_classes; { u2 inner_class_info_index; u2 * outer_class_info_index; u2 inner_name_index; u2 inner_class_access_flags; * } classes[number_of_classes]; } * </pre> * * @param in * @throws Exception */ private void doInnerClasses(DataInput in) throws Exception { int number_of_classes = in.readUnsignedShort(); for (int i = 0; i < number_of_classes; i++) { int inner_class_info_index = in.readUnsignedShort(); int outer_class_info_index = in.readUnsignedShort(); int inner_name_index = in.readUnsignedShort(); int inner_class_access_flags = in.readUnsignedShort(); if (cd != null) { TypeRef innerClass = null; TypeRef outerClass = null; String innerName = null; if (inner_class_info_index != 0) { int nameIndex = intPool[inner_class_info_index]; innerClass = analyzer.getTypeRef((String) pool[nameIndex]); } if (outer_class_info_index != 0) { int nameIndex = intPool[outer_class_info_index]; outerClass = analyzer.getTypeRef((String) pool[nameIndex]); } if (inner_name_index != 0) innerName = (String) pool[inner_name_index]; cd.innerClass(innerClass, outerClass, innerName, inner_class_access_flags); } } } /** * Handle a signature * * <pre> * Signature_attribute { u2 attribute_name_index; * u4 attribute_length; u2 signature_index; } * </pre> * * @param member * @param access_flags */ void doSignature(DataInput in, ElementType member, int access_flags) throws IOException { int signature_index = in.readUnsignedShort(); String signature = (String) pool[signature_index]; try { Signature sig; switch (member) { case ANNOTATION_TYPE : case TYPE : case PACKAGE : classSignature = signature; sig = analyzer.getClassSignature(signature); break; case FIELD : sig = analyzer.getFieldSignature(signature); break; case CONSTRUCTOR : case METHOD : sig = analyzer.getMethodSignature(signature); break; default : throw new IllegalArgumentException( "Signature \"" + signature + "\" found for unknown element type: " + member); } Set<String> binaryRefs = sig.erasedBinaryReferences(); for (String binary : binaryRefs) { TypeRef ref = analyzer.getTypeRef(binary); if (cd != null) { cd.addReference(ref); } referTo(ref, access_flags); } if (last != null) { last.signature = signature; } if (cd != null) { cd.signature(signature); } } catch (Exception e) { throw new RuntimeException("Signature failed for " + signature, e); } } /** * Handle Deprecated attribute */ void doDeprecated(DataInput in, ElementType member) throws Exception { switch (member) { case ANNOTATION_TYPE : case TYPE : case PACKAGE : deprecated = true; break; case FIELD : case CONSTRUCTOR : case METHOD : if (last != null) { last.deprecated = true; } break; default : break; } if (cd != null) { cd.deprecated(); } } /** * Handle annotation member default value */ void doAnnotationDefault(DataInput in, ElementType member, int access_flags) throws IOException { Object value = doElementValue(in, member, RetentionPolicy.RUNTIME, cd != null, access_flags); if (last instanceof MethodDef) { last.constant = value; cd.annotationDefault((MethodDef) last, value); } } /** * Handle a constant value call the data collector with it */ void doConstantValue(DataInput in) throws IOException { int constantValue_index = in.readUnsignedShort(); if (cd == null) return; Object object = pool[constantValue_index]; if (object == null) object = pool[intPool[constantValue_index]]; last.constant = object; cd.constant(object); } void doExceptions(DataInput in, int access_flags) throws IOException { int exception_count = in.readUnsignedShort(); for (int i = 0; i < exception_count; i++) { int index = in.readUnsignedShort(); ClassConstant cc = (ClassConstant) pool[index]; TypeRef clazz = analyzer.getTypeRef(cc.getName()); referTo(clazz, access_flags); } } void doMethodParameters(DataInput in) throws IOException { int parameters_count = in.readUnsignedByte(); MethodParameter[] parameters = new MethodParameter[parameters_count]; for (int i = 0; i < parameters_count; i++) { int name_index = in.readUnsignedShort(); int access_flags = in.readUnsignedShort(); String name = (String) pool[name_index]; parameters[i] = new MethodParameter(name, access_flags); } if (last instanceof MethodDef) { MethodDef method = (MethodDef) last; method.parameters = parameters; cd.methodParameters(method, parameters); } } /** * <pre> * Code_attribute { u2 attribute_name_index; u4 attribute_length; u2 * max_stack; u2 max_locals; u4 code_length; u1 code[code_length]; u2 * exception_table_length; { u2 start_pc; u2 end_pc; u2 handler_pc; u2 * catch_type; } exception_table[exception_table_length]; u2 * attributes_count; attribute_info attributes[attributes_count]; } * </pre> * * @param in * @param pool * @throws Exception */ private void doCode(DataInput in, boolean crawl) throws Exception { /* int max_stack = */in.readUnsignedShort(); /* int max_locals = */in.readUnsignedShort(); int code_length = in.readInt(); if (crawl) { ByteBuffer code = slice(in, code_length); crawl(code); } else { in.skipBytes(code_length); } int exception_table_length = in.readUnsignedShort(); for (int i = 0; i < exception_table_length; i++) { int start_pc = in.readUnsignedShort(); int end_pc = in.readUnsignedShort(); int handler_pc = in.readUnsignedShort(); int catch_type = in.readUnsignedShort(); classConstRef(catch_type); } doAttributes(in, ElementType.METHOD, false, 0); } private ByteBuffer slice(DataInput in, int length) throws Exception { if (in instanceof ByteBufferDataInput) { ByteBufferDataInput bbin = (ByteBufferDataInput) in; return bbin.slice(length); } byte array[] = new byte[length]; in.readFully(array, 0, length); return ByteBuffer.wrap(array, 0, length); } /** * We must find Class.forName references ... * * @param code */ private void crawl(ByteBuffer bb) { int lastReference = -1; while (bb.hasRemaining()) { int instruction = Byte.toUnsignedInt(bb.get()); switch (instruction) { case OpCodes.ldc : { lastReference = Byte.toUnsignedInt(bb.get()); classConstRef(lastReference); break; } case OpCodes.ldc_w : { lastReference = Short.toUnsignedInt(bb.getShort()); classConstRef(lastReference); break; } case OpCodes.anewarray : case OpCodes.checkcast : case OpCodes.instanceof_ : case OpCodes.new_ : { int cref = Short.toUnsignedInt(bb.getShort()); classConstRef(cref); lastReference = -1; break; } case OpCodes.multianewarray : { int cref = Short.toUnsignedInt(bb.getShort()); classConstRef(cref); bb.get(); lastReference = -1; break; } case OpCodes.invokespecial : { int mref = Short.toUnsignedInt(bb.getShort()); if (cd != null) referenceMethod(0, mref); break; } case OpCodes.invokevirtual : { int mref = Short.toUnsignedInt(bb.getShort()); if (cd != null) referenceMethod(0, mref); break; } case OpCodes.invokeinterface : { int mref = Short.toUnsignedInt(bb.getShort()); if (cd != null) referenceMethod(0, mref); bb.get(); // read past the 'count' operand bb.get(); // read past the reserved space for future operand break; } case OpCodes.invokestatic : { int methodref = Short.toUnsignedInt(bb.getShort()); if (cd != null) referenceMethod(0, methodref); if ((methodref == forName || methodref == class$) && lastReference != -1 && pool[intPool[lastReference]] instanceof String) { String fqn = (String) pool[intPool[lastReference]]; if (!fqn.equals("class") && fqn.indexOf('.') > 0) { TypeRef clazz = analyzer.getTypeRefFromFQN(fqn); referTo(clazz, 0); } lastReference = -1; } break; } /* * 3/5: opcode, indexbyte1, indexbyte2 or iinc, indexbyte1, * indexbyte2, countbyte1, countbyte2 */ case OpCodes.wide : { int opcode = Byte.toUnsignedInt(bb.get()); bb.position(bb.position() + (opcode == OpCodes.iinc ? 4 : 2)); break; } case OpCodes.tableswitch : { // Skip to place divisible by 4 int rem = bb.position() % 4; if (rem != 0) { bb.position(bb.position() + 4 - rem); } int deflt = bb.getInt(); int low = bb.getInt(); int high = bb.getInt(); bb.position(bb.position() + (high - low + 1) * 4); lastReference = -1; break; } case OpCodes.lookupswitch : { // Skip to place divisible by 4 int rem = bb.position() % 4; if (rem != 0) { bb.position(bb.position() + 4 - rem); } int deflt = bb.getInt(); int npairs = bb.getInt(); bb.position(bb.position() + npairs * 8); lastReference = -1; break; } default : { lastReference = -1; bb.position(bb.position() + OpCodes.OFFSETS[instruction]); } } } } private void doSourceFile(DataInput in) throws IOException { int sourcefile_index = in.readUnsignedShort(); this.sourceFile = pool[sourcefile_index].toString(); } private void doParameterAnnotations(DataInput in, ElementType member, RetentionPolicy policy, int access_flags) throws Exception { boolean collect = cd != null; int num_parameters = in.readUnsignedByte(); for (int p = 0; p < num_parameters; p++) { int num_annotations = in.readUnsignedShort(); // # of annotations if (num_annotations > 0) { if (collect) { cd.parameter(p); } for (int a = 0; a < num_annotations; a++) { Annotation annotation = doAnnotation(in, member, policy, collect, access_flags); if (collect) { cd.annotation(annotation); } } } } } private void doTypeAnnotations(DataInput in, ElementType member, RetentionPolicy policy, int access_flags) throws Exception { int num_annotations = in.readUnsignedShort(); for (int p = 0; p < num_annotations; p++) { // type_annotation { // u1 target_type; // union { // type_parameter_target; // supertype_target; // type_parameter_bound_target; // empty_target; // method_formal_parameter_target; // throws_target; // localvar_target; // catch_target; // offset_target; // type_argument_target; // } target_info; // type_path target_path; // u2 type_index; // u2 num_element_value_pairs; // { u2 element_name_index; // element_value value; // } element_value_pairs[num_element_value_pairs]; // Table 4.7.20-A. Interpretation of target_type values (Part 1) int target_type = in.readUnsignedByte(); byte[] target_info; int target_index; switch (target_type) { case 0x00 : // type parameter declaration of generic class or // interface case 0x01 : // type parameter declaration of generic method or // constructor // type_parameter_target { // u1 type_parameter_index; target_info = new byte[1]; in.readFully(target_info); target_index = Byte.toUnsignedInt(target_info[0]); break; case 0x10 : // type in extends clause of class or interface // declaration (including the direct superclass of // an anonymous class declaration), or in implements // clause of interface declaration // supertype_target { // u2 supertype_index; target_info = new byte[2]; in.readFully(target_info); target_index = (Byte.toUnsignedInt(target_info[0]) << 8) | Byte.toUnsignedInt(target_info[1]); break; case 0x11 : // type in bound of type parameter declaration of // generic class or interface case 0x12 : // type in bound of type parameter declaration of // generic method or constructor // type_parameter_bound_target { // u1 type_parameter_index; // u1 bound_index; target_info = new byte[2]; in.readFully(target_info); target_index = Byte.toUnsignedInt(target_info[0]); break; case 0x13 : // type in field declaration case 0x14 : // return type of method, or type of newly // constructed object case 0x15 : // receiver type of method or constructor target_info = new byte[0]; target_index = TYPEUSE_INDEX_NONE; break; case 0x16 : // type in formal parameter declaration of method, // constructor, or lambda expression // formal_parameter_target { // u1 formal_parameter_index; target_info = new byte[1]; in.readFully(target_info); target_index = Byte.toUnsignedInt(target_info[0]); break; case 0x17 : // type in throws clause of method or constructor // throws_target { // u2 throws_type_index; target_info = new byte[2]; in.readFully(target_info); target_index = (Byte.toUnsignedInt(target_info[0]) << 8) | Byte.toUnsignedInt(target_info[1]); break; case 0x40 : // type in local variable declaration case 0x41 : // type in resource variable declaration // localvar_target { // u2 table_length; // { u2 start_pc; // u2 length; // u2 index; // } table[table_length]; int table_length = in.readUnsignedShort(); target_info = new byte[table_length * 6]; in.readFully(target_info); target_index = TYPEUSE_INDEX_NONE; break; case 0x42 : // type in exception parameter declaration // catch_target { // u2 exception_table_index; target_info = new byte[2]; in.readFully(target_info); target_index = (Byte.toUnsignedInt(target_info[0]) << 8) | Byte.toUnsignedInt(target_info[1]); break; case 0x43 : // type in instanceof expression case 0x44 : // type in new expression case 0x45 : // type in method reference expression using ::new case 0x46 : // type in method reference expression using // ::Identifier // offset_target { // u2 offset; target_info = new byte[2]; in.readFully(target_info); target_index = TYPEUSE_INDEX_NONE; break; case 0x47 : // type in cast expression case 0x48 : // type argument for generic constructor in new // expression or explicit constructor invocation // statement case 0x49 : // type argument for generic method in method // invocation expression case 0x4A : // type argument for generic constructor in method // reference expression using ::new case 0x4B : // type argument for generic method in method // reference expression using ::Identifier // type_argument_target { // u2 offset; // u1 type_argument_index; target_info = new byte[3]; in.readFully(target_info); target_index = Byte.toUnsignedInt(target_info[2]); break; default : throw new IllegalArgumentException("Unknown target_type: " + target_type); } // The value of the target_path item denotes precisely which part of // the type indicated by target_info is annotated. The format of the // type_path { // u1 path_length; // { u1 type_path_kind; // u1 type_argument_index; // } path[path_length]; int path_length = in.readUnsignedByte(); byte[] type_path = new byte[path_length * 2]; in.readFully(type_path); // Rest is identical to the normal annotations if (cd != null) { cd.typeuse(target_type, target_index, target_info, type_path); Annotation annotation = doAnnotation(in, member, policy, true, access_flags); cd.annotation(annotation); } else { doAnnotation(in, member, policy, false, access_flags); } } } private void doAnnotations(DataInput in, ElementType member, RetentionPolicy policy, int access_flags) throws Exception { int num_annotations = in.readUnsignedShort(); // # of annotations for (int a = 0; a < num_annotations; a++) { if (cd == null) doAnnotation(in, member, policy, false, access_flags); else { Annotation annotation = doAnnotation(in, member, policy, true, access_flags); cd.annotation(annotation); } } } // annotation { // u2 type_index; // u2 num_element_value_pairs; { // u2 element_name_index; // element_value value; // element_value_pairs[num_element_value_pairs]; private Annotation doAnnotation(DataInput in, ElementType member, RetentionPolicy policy, boolean collect, int access_flags) throws IOException { int type_index = in.readUnsignedShort(); if (annotations == null) annotations = new HashSet<>(); String typeName = (String) pool[type_index]; TypeRef typeRef = analyzer.getTypeRef(typeName); annotations.add(typeRef); if (typeRef.getFQN() .equals("java.lang.Deprecated")) { switch (member) { case ANNOTATION_TYPE : case TYPE : case PACKAGE : deprecated = true; break; case FIELD : case CONSTRUCTOR : case METHOD : if (last != null) { last.deprecated = true; } break; default : break; } } if (policy == RetentionPolicy.RUNTIME) { referTo(typeRef, 0); hasRuntimeAnnotations = true; if (api != null && (Modifier.isPublic(access_flags) || Modifier.isProtected(access_flags))) api.add(typeRef.getPackageRef()); } else { hasClassAnnotations = true; } int num_element_value_pairs = in.readUnsignedShort(); Map<String, Object> elements = null; for (int v = 0; v < num_element_value_pairs; v++) { int element_name_index = in.readUnsignedShort(); String element = (String) pool[element_name_index]; Object value = doElementValue(in, member, policy, collect, access_flags); if (collect) { if (elements == null) elements = new LinkedHashMap<>(); elements.put(element, value); } } if (collect) return new Annotation(typeRef, elements, member, policy); return null; } private Object doElementValue(DataInput in, ElementType member, RetentionPolicy policy, boolean collect, int access_flags) throws IOException { int tag = in.readUnsignedByte(); switch (tag) { case 'B' : // Byte case 'C' : // Character case 'I' : // Integer case 'S' : // Short int const_value_index = in.readUnsignedShort(); return Integer.valueOf(intPool[const_value_index]); case 'D' : // Double case 'F' : // Float case 's' : // String case 'J' : // Long const_value_index = in.readUnsignedShort(); return pool[const_value_index]; case 'Z' : // Boolean const_value_index = in.readUnsignedShort(); return Boolean.valueOf(intPool[const_value_index] != 0); case 'e' : // enum constant int type_name_index = in.readUnsignedShort(); if (policy == RetentionPolicy.RUNTIME) { referTo(type_name_index, 0); // field descriptor if (api != null && (Modifier.isPublic(access_flags) || Modifier.isProtected(access_flags))) { TypeRef name = analyzer.getTypeRef((String) pool[type_name_index]); api.add(name.getPackageRef()); } } int const_name_index = in.readUnsignedShort(); return pool[const_name_index]; case 'c' : // Class int class_info_index = in.readUnsignedShort(); TypeRef name = analyzer.getTypeRef((String) pool[class_info_index]); if (policy == RetentionPolicy.RUNTIME) { referTo(name, 0); if (api != null && (Modifier.isPublic(access_flags) || Modifier.isProtected(access_flags))) { api.add(name.getPackageRef()); } } return name; case '@' : // Annotation type return doAnnotation(in, member, policy, collect, access_flags); case '[' : // Array int num_values = in.readUnsignedShort(); Object[] result = new Object[num_values]; for (int i = 0; i < num_values; i++) { result[i] = doElementValue(in, member, policy, collect, access_flags); } return result; default : throw new IllegalArgumentException("Invalid value for Annotation ElementValue tag " + tag); } } /* * Bootstrap method arguments can be class constants. */ private void doBootstrapMethods(DataInput in) throws IOException { final int num_bootstrap_methods = in.readUnsignedShort(); for (int v = 0; v < num_bootstrap_methods; v++) { final int bootstrap_method_ref = in.readUnsignedShort(); final int num_bootstrap_arguments = in.readUnsignedShort(); for (int a = 0; a < num_bootstrap_arguments; a++) { final int bootstrap_argument = in.readUnsignedShort(); classConstRef(bootstrap_argument); } } } /* * The verifier can require access to types only referenced in StackMapTable * attributes. */ private void doStackMapTable(DataInput in) throws IOException { final int number_of_entries = in.readUnsignedShort(); for (int v = 0; v < number_of_entries; v++) { final int frame_type = in.readUnsignedByte(); if (frame_type <= 63) { // same_frame // nothing else to do } else if (frame_type <= 127) { // same_locals_1_stack_item_frame verification_type_info(in); } else if (frame_type <= 246) { // RESERVED // nothing else to do } else if (frame_type <= 247) { // same_locals_1_stack_item_frame_extended final int offset_delta = in.readUnsignedShort(); verification_type_info(in); } else if (frame_type <= 250) { // chop_frame final int offset_delta = in.readUnsignedShort(); } else if (frame_type <= 251) { // same_frame_extended final int offset_delta = in.readUnsignedShort(); } else if (frame_type <= 254) { // append_frame final int offset_delta = in.readUnsignedShort(); final int number_of_locals = frame_type - 251; for (int n = 0; n < number_of_locals; n++) { verification_type_info(in); } } else if (frame_type <= 255) { // full_frame final int offset_delta = in.readUnsignedShort(); final int number_of_locals = in.readUnsignedShort(); for (int n = 0; n < number_of_locals; n++) { verification_type_info(in); } final int number_of_stack_items = in.readUnsignedShort(); for (int n = 0; n < number_of_stack_items; n++) { verification_type_info(in); } } } } private void verification_type_info(DataInput in) throws IOException { final int tag = in.readUnsignedByte(); switch (tag) { case 7 :// Object_variable_info final int cpool_index = in.readUnsignedShort(); classConstRef(cpool_index); break; case 8 :// ITEM_Uninitialized final int offset = in.readUnsignedShort(); break; } } /* * Nest class references are only used during access checks. So we do not * need to record them as class references here. */ private void doNestHost(DataInput in) throws IOException { final int host_class_index = in.readUnsignedShort(); } /* * Nest class references are only used during access checks. So we do not * need to record them as class references here. */ private void doNestMembers(DataInput in) throws IOException { final int number_of_classes = in.readUnsignedShort(); for (int v = 0; v < number_of_classes; v++) { final int member_class_index = in.readUnsignedShort(); } } /** * Add a new package reference. * * @param packageRef A '.' delimited package name */ void referTo(TypeRef typeRef, int modifiers) { if (xref != null) xref.add(typeRef); if (typeRef.isPrimitive()) return; PackageRef packageRef = typeRef.getPackageRef(); if (packageRef.isPrimitivePackage()) return; imports.add(packageRef); if (api != null && (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers))) api.add(packageRef); if (cd != null) cd.referTo(typeRef, modifiers); } void referTo(int index, int modifiers) { String descriptor = (String) pool[index]; parseDescriptor(descriptor, modifiers); } public void parseDescriptor(String descriptor, int modifiers) { char c = descriptor.charAt(0); if (c != '(' && c != 'L' && c != '[' && c != '<' && c != 'T') { return; } Signature sig = (c == '(' || c == '<') ? analyzer.getMethodSignature(descriptor) : analyzer.getFieldSignature(descriptor); Set<String> binaryRefs = sig.erasedBinaryReferences(); for (String binary : binaryRefs) { TypeRef ref = analyzer.getTypeRef(binary); if (cd != null) { cd.addReference(ref); } referTo(ref, modifiers); } } public Set<PackageRef> getReferred() { return imports; } public String getAbsolutePath() { return path; } public String getSourceFile() { return sourceFile; } /** * .class construct for different compilers sun 1.1 Detect static variable * class$com$acme$MyClass 1.2 " 1.3 " 1.4 " 1.5 ldc_w (class) 1.6 " eclipse * 1.1 class$0, ldc (string), invokestatic Class.forName 1.2 " 1.3 " 1.5 ldc * (class) 1.6 " 1.5 and later is not an issue, sun pre 1.5 is easy to * detect the static variable that decodes the class name. For eclipse, the * class$0 gives away we have a reference encoded in a string. * compilerversions/compilerversions.jar contains test versions of all * versions/compilers. */ public void reset() { if (--depth == 0) { pool = null; intPool = null; xref = null; } } private Stream<Clazz> hierarchyStream(Analyzer analyzer) { requireNonNull(analyzer); Spliterator<Clazz> spliterator = new AbstractSpliterator<Clazz>(Long.MAX_VALUE, Spliterator.DISTINCT | Spliterator.ORDERED | Spliterator.NONNULL) { private Clazz clazz = Clazz.this; @Override public boolean tryAdvance(Consumer<? super Clazz> action) { requireNonNull(action); if (clazz == null) { return false; } action.accept(clazz); TypeRef type = clazz.zuper; if (type == null) { clazz = null; } else { try { clazz = analyzer.findClass(type); } catch (Exception e) { throw Exceptions.duck(e); } if (clazz == null) { analyzer.warning("While traversing the type tree for %s cannot find class %s", Clazz.this, type); } } return true; } }; return StreamSupport.stream(spliterator, false); } private Stream<TypeRef> typeStream(Analyzer analyzer, Function<? super Clazz, Collection<? extends TypeRef>> func, Set<TypeRef> visited) { requireNonNull(analyzer); requireNonNull(func); Spliterator<TypeRef> spliterator = new AbstractSpliterator<TypeRef>(Long.MAX_VALUE, Spliterator.DISTINCT | Spliterator.ORDERED | Spliterator.NONNULL) { private final Deque<TypeRef> queue = new ArrayDeque<>(func.apply(Clazz.this)); private final Set<TypeRef> seen = (visited != null) ? visited : new HashSet<>(); @Override public boolean tryAdvance(Consumer<? super TypeRef> action) { requireNonNull(action); TypeRef type; do { type = queue.poll(); if (type == null) { return false; } } while (seen.contains(type)); seen.add(type); action.accept(type); if (visited != null) { Clazz clazz; try { clazz = analyzer.findClass(type); } catch (Exception e) { throw Exceptions.duck(e); } if (clazz == null) { analyzer.warning("While traversing the type tree for %s cannot find class %s", Clazz.this, type); } else { queue.addAll(func.apply(clazz)); } } return true; } }; return StreamSupport.stream(spliterator, false); } public boolean is(QUERY query, Instruction instr, Analyzer analyzer) throws Exception { switch (query) { case ANY : return true; case NAMED : return instr.matches(getClassName().getDottedOnly()) ^ instr.isNegated(); case VERSION : { String v = major_version + "." + minor_version; return instr.matches(v) ^ instr.isNegated(); } case IMPLEMENTS : { Set<TypeRef> visited = new HashSet<>(); return hierarchyStream(analyzer) .flatMap(c -> c.typeStream(analyzer, Clazz::interfaces, visited)) .map(TypeRef::getDottedOnly) .anyMatch(instr::matches) ^ instr.isNegated(); } case EXTENDS : return hierarchyStream(analyzer).skip(1) // skip this class .map(Clazz::getClassName) .map(TypeRef::getDottedOnly) .anyMatch(instr::matches) ^ instr.isNegated(); case PUBLIC : return isPublic(); case CONCRETE : return !isAbstract(); case ANNOTATED : return typeStream(analyzer, Clazz::annotations, null) .map(TypeRef::getFQN) .anyMatch(instr::matches) ^ instr.isNegated(); case INDIRECTLY_ANNOTATED : return typeStream(analyzer, Clazz::annotations, new HashSet<>()) .map(TypeRef::getFQN) .anyMatch(instr::matches) ^ instr.isNegated(); case HIERARCHY_ANNOTATED : return hierarchyStream(analyzer) .flatMap(c -> c.typeStream(analyzer, Clazz::annotations, null)) .map(TypeRef::getFQN) .anyMatch(instr::matches) ^ instr.isNegated(); case HIERARCHY_INDIRECTLY_ANNOTATED : { Set<TypeRef> visited = new HashSet<>(); return hierarchyStream(analyzer) .flatMap(c -> c.typeStream(analyzer, Clazz::annotations, visited)) .map(TypeRef::getFQN) .anyMatch(instr::matches) ^ instr.isNegated(); } case RUNTIMEANNOTATIONS : return hasRuntimeAnnotations; case CLASSANNOTATIONS : return hasClassAnnotations; case ABSTRACT : return isAbstract(); case IMPORTS : return hierarchyStream(analyzer) .map(Clazz::getReferred) .flatMap(Set::stream) .distinct() .map(PackageRef::getFQN) .anyMatch(instr::matches) ^ instr.isNegated(); case DEFAULT_CONSTRUCTOR : return hasPublicNoArgsConstructor(); } return instr == null ? false : instr.isNegated(); } @Override public String toString() { if (className != null) { return className.getFQN(); } return resource.toString(); } /** * Called when crawling the byte code and a method reference is found */ private void referenceMethod(int access, int methodRefPoolIndex) { if (methodRefPoolIndex == 0) return; Object o = pool[methodRefPoolIndex]; if (o instanceof Assoc) { Assoc assoc = (Assoc) o; switch (assoc.tag) { case Methodref : case InterfaceMethodref : { int string_index = intPool[assoc.a]; TypeRef class_name = analyzer.getTypeRef((String) pool[string_index]); int name_and_type_index = assoc.b; Assoc name_and_type = (Assoc) pool[name_and_type_index]; if (name_and_type.tag == CONSTANT.NameAndType) { // Name and Type int name_index = name_and_type.a; int type_index = name_and_type.b; String method = (String) pool[name_index]; String descriptor = (String) pool[type_index]; cd.referenceMethod(access, class_name, method, descriptor); } else { throw new IllegalArgumentException( "Invalid class file (or parsing is wrong), assoc is not type + name (12)"); } break; } default : throw new IllegalArgumentException( "Invalid class file (or parsing is wrong), Assoc is not method ref! (10)"); } } else throw new IllegalArgumentException( "Invalid class file (or parsing is wrong), Not an assoc at a method ref"); } public boolean isPublic() { return Modifier.isPublic(accessx); } public boolean isProtected() { return Modifier.isProtected(accessx); } public boolean isEnum() { return zuper != null && zuper.getBinary() .equals("java/lang/Enum"); } public boolean isSynthetic() { return (ACC_SYNTHETIC & accessx) != 0; } public boolean isModule() { return (ACC_MODULE & accessx) != 0; } public JAVA getFormat() { return JAVA.format(major_version); } public static String objectDescriptorToFQN(String string) { if ((string.startsWith("L") || string.startsWith("T")) && string.endsWith(";")) return string.substring(1, string.length() - 1) .replace('/', '.'); switch (string.charAt(0)) { case 'V' : return "void"; case 'B' : return "byte"; case 'C' : return "char"; case 'I' : return "int"; case 'S' : return "short"; case 'D' : return "double"; case 'F' : return "float"; case 'J' : return "long"; case 'Z' : return "boolean"; case '[' : // Array return objectDescriptorToFQN(string.substring(1)) + "[]"; } throw new IllegalArgumentException("Invalid type character in descriptor " + string); } public static String unCamel(String id) { StringBuilder out = new StringBuilder(); for (int i = 0; i < id.length(); i++) { char c = id.charAt(i); if (c == '_' || c == '$' || c == '-' || c == '.') { if (out.length() > 0 && !Character.isWhitespace(out.charAt(out.length() - 1))) out.append(' '); continue; } int n = i; while (n < id.length() && Character.isUpperCase(id.charAt(n))) { n++; } if (n == i) out.append(id.charAt(i)); else { boolean tolower = (n - i) == 1; if (i > 0 && !Character.isWhitespace(out.charAt(out.length() - 1))) out.append(' '); for (; i < n;) { if (tolower) out.append(Character.toLowerCase(id.charAt(i))); else out.append(id.charAt(i)); i++; } i } } if (id.startsWith(".")) out.append(" *"); out.replace(0, 1, Character.toUpperCase(out.charAt(0)) + ""); return out.toString(); } public boolean isInterface() { return Modifier.isInterface(accessx); } public boolean isAbstract() { return Modifier.isAbstract(accessx); } public boolean hasPublicNoArgsConstructor() { return hasDefaultConstructor; } public int getAccess() { if (innerAccess == -1) return accessx; return innerAccess; } public TypeRef getClassName() { return className; } /** * To provide an enclosing instance * * @param access * @param name * @param descriptor */ public MethodDef getMethodDef(int access, String name, String descriptor) { return new MethodDef(access, name, descriptor); } public TypeRef getSuper() { return zuper; } public String getFQN() { return className.getFQN(); } public TypeRef[] getInterfaces() { return interfaces; } public List<TypeRef> interfaces() { return (interfaces != null) ? Arrays.asList(interfaces) : Collections.emptyList(); } public Set<TypeRef> annotations() { return (annotations != null) ? annotations : Collections.emptySet(); } public void setInnerAccess(int access) { innerAccess = access; } public boolean isFinal() { return Modifier.isFinal(accessx); } public void setDeprecated(boolean b) { deprecated = b; } public boolean isDeprecated() { return deprecated; } public boolean isAnnotation() { return (accessx & ACC_ANNOTATION) != 0; } public Set<PackageRef> getAPIUses() { if (api == null) return Collections.emptySet(); return api; } public Clazz.TypeDef getExtends(TypeRef type) { return new TypeDef(type, false); } public Clazz.TypeDef getImplements(TypeRef type) { return new TypeDef(type, true); } private void classConstRef(int index) { Object o = pool[index]; if (o == null) { return; } if (o instanceof ClassConstant) { ClassConstant cc = (ClassConstant) o; if (cc.referred) { return; } cc.referred = true; String name = cc.getName(); if (name != null) { TypeRef tr = analyzer.getTypeRef(name); referTo(tr, 0); } } } public String getClassSignature() { return classSignature; } public Map<String, Object> getDefaults() throws Exception { if (defaults == null) { Map<String, Object> map = defaults = new HashMap<>(); parseClassFileWithCollector(new ClassDataCollector() { @Override public void annotationDefault(MethodDef last, Object value) { map.put(last.name, value); } }); } return defaults; } }
package com.atlassian.selenium.visualcomparison; import com.atlassian.selenium.visualcomparison.utils.BoundingBox; import com.atlassian.selenium.visualcomparison.utils.ScreenResolution; import com.atlassian.selenium.visualcomparison.utils.Screenshot; import com.atlassian.selenium.visualcomparison.utils.ScreenshotDiff; import junit.framework.Assert; import javax.imageio.ImageIO; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class VisualComparer { private ScreenResolution[] resolutions = new ScreenResolution[] { new ScreenResolution(1280, 1024) }; private VisualComparableClient client; private boolean refreshAfterResize = false; private boolean reportingEnabled = false; private String reportOutputPath; private String imageSubDirName = "report_images"; private String tempPath = System.getProperty("java.io.tmpdir"); private Map<String, String> uiStringReplacements = null; private long waitforJQueryTimeout = 0; private List<BoundingBox> ignoreAreas = null; private boolean ignoreSingleLineDiffs = false; public long getWaitforJQueryTimeout() { return waitforJQueryTimeout; } public void setWaitforJQueryTimeout(long waitforJQueryTimeout) { this.waitforJQueryTimeout = waitforJQueryTimeout; } public VisualComparer(VisualComparableClient client) { this.client = client; } public void setScreenResolutions(ScreenResolution[] resolutions) { this.resolutions = resolutions; } public ScreenResolution[] getScreenResolutions() { return this.resolutions; } public void setRefreshAfterResize(boolean refreshAfterResize) { this.refreshAfterResize = refreshAfterResize; } public boolean getRefreshAfterResize() { return this.refreshAfterResize; } public void setUIStringReplacements(Map<String,String> uiStringReplacements) { this.uiStringReplacements = uiStringReplacements; } public Map<String,String> getUIStringReplacements() { return this.uiStringReplacements; } public void enableReportGeneration(String reportOutputPath) { this.reportingEnabled = true; this.reportOutputPath = reportOutputPath; File file = new File(reportOutputPath + "/" + imageSubDirName); file.mkdirs(); } public void disableReportGeneration() { this.reportingEnabled = false; } public void setTempPath(String tempPath) { File file = new File(tempPath); file.mkdirs(); this.tempPath = tempPath; } public String getTempPath() { return this.tempPath; } public List<BoundingBox> getIgnoreAreas() { return ignoreAreas; } public boolean getIgnoreSingleLineDiffs() { return ignoreSingleLineDiffs; } public void setIgnoreSingleLineDiffs(boolean ignoreSingleLineDiffs) { this.ignoreSingleLineDiffs = ignoreSingleLineDiffs; } public void setIgnoreAreas(List<BoundingBox> ignoreAreas) { this.ignoreAreas = ignoreAreas; } public void assertUIMatches(String id, String baselineImagePath) { try { Assert.assertTrue("Screenshots were not equal", uiMatches(id, baselineImagePath)); } catch (Exception e) { throw new RuntimeException(e); } } public boolean uiMatches(final String id, final String baselineImagePath) throws Exception { ArrayList<Screenshot> currentScreenshots = takeScreenshots(id); ArrayList<Screenshot> baselineScreenshots = loadBaselineScreenshots(id, baselineImagePath); return compareScreenshots(baselineScreenshots, currentScreenshots); } public ArrayList<Screenshot> takeScreenshots(final String id) throws IOException { // Capture a series of screenshots in all the valid screen resolutions. ArrayList<Screenshot> screenshots = new ArrayList<Screenshot>(); for (ScreenResolution res : resolutions) { client.resizeScreen(res, refreshAfterResize); if (waitforJQueryTimeout > 0) { if (!client.waitForJQuery (waitforJQueryTimeout)) { Assert.fail("Timed out while waiting for jQuery to complete"); } } if (uiStringReplacements != null) { // Remove strings from the UI that we are expecting will change // (such as the build number in the JIRA footer) for (String key : uiStringReplacements.keySet()) { replaceUIHtml(key, uiStringReplacements.get(key)); } } screenshots.add(new Screenshot(client, id, tempPath, res)); } Collections.sort(screenshots); return screenshots; } public ArrayList<Screenshot> loadBaselineScreenshots(final String id, final String baselineImagePath) throws IOException { File screenshotDir = new File(baselineImagePath); File[] screenshotFiles = screenshotDir.listFiles( new FileFilter() { public boolean accept(File file) { return file.getName().startsWith(id);} }); ArrayList<Screenshot> screenshots = new ArrayList<Screenshot>(); for (File screenshotFile : screenshotFiles) { screenshots.add(new Screenshot(screenshotFile)); } Collections.sort(screenshots); return screenshots; } protected void replaceUIHtml(String id, String newContent) { final String script = "var content, el = window.document.getElementById('" + id + "');" + "if (el) { content = el.innerHTML; el.innerHTML = \"" + newContent + "\"; } content;"; final Object result = client.execute(script); final String value = String.valueOf(result); } public boolean compareScreenshots(ArrayList<Screenshot> oldScreenshots, ArrayList<Screenshot> newScreenshots) throws Exception { if (oldScreenshots.size() != newScreenshots.size()) { if (oldScreenshots.size() == 0) { if (reportingEnabled) { String imageOutputDir = ScreenshotDiff.getImageOutputDir(reportOutputPath, imageSubDirName); for (Screenshot newScreenshot : newScreenshots) { // Copy the new image to the output directory. ImageIO.write(newScreenshot.getImage(), "png", new File(imageOutputDir + newScreenshot.getFileName())); } } throw new IllegalArgumentException("There were new screenshots, but no baseline images. Is this a new test?" + " If reporting is enabled, the new screenshots will be output in the report."); } else { throw new IllegalArgumentException("Incorrect number of images." + " There were " + oldScreenshots.size() + " baseline images," + " but only " + newScreenshots.size() + " new images."); } } boolean matches = true; for (int i = 0; i < oldScreenshots.size(); i++) { ScreenshotDiff diff = getScreenshotDiff(oldScreenshots.get(i), newScreenshots.get(i)); if (reportingEnabled) { diff.writeDiffReport(reportOutputPath, imageSubDirName); } matches = !diff.hasDifferences() && matches; } return matches; } public ScreenshotDiff getScreenshotDiff(Screenshot oldScreenshot, Screenshot newScreenshot) throws Exception { return oldScreenshot.getDiff(newScreenshot, ignoreAreas, ignoreSingleLineDiffs); } }
package krasa.grepconsole.gui; import com.centerkey.utils.BareBonesBrowserLaunch; import com.intellij.ide.DataManager; import com.intellij.ide.actions.CopyAction; import com.intellij.ide.actions.CutAction; import com.intellij.ide.actions.PasteAction; import com.intellij.ide.plugins.PluginManager; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.ui.JBMenuItem; import com.intellij.openapi.ui.JBPopupMenu; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginsAdvertiser; import com.intellij.ui.CheckedTreeNode; import com.intellij.ui.JBColor; import com.intellij.ui.treeStructure.treetable.TreeTableTree; import com.intellij.util.ArrayUtil; import com.intellij.util.ui.tree.TreeUtil; import krasa.grepconsole.gui.table.*; import krasa.grepconsole.model.GrepColor; import krasa.grepconsole.model.GrepExpressionGroup; import krasa.grepconsole.model.GrepExpressionItem; import krasa.grepconsole.model.Profile; import krasa.grepconsole.plugin.DefaultState; import krasa.grepconsole.plugin.MyConfigurable; import krasa.grepconsole.plugin.ServiceManager; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.text.NumberFormatter; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.*; import static krasa.grepconsole.Cloner.deepClone; public class ProfileDetail { private static final String DIVIDER = "GrepConsole.ProfileDetail"; private static final Logger log = Logger.getInstance(ProfileDetail.class); private JPanel rootComponent; private CheckboxTreeTable grepTable; private JButton addNewButton; private JButton resetToDefaultButton; private JCheckBox enableHighlightingCheckBox; private JFormattedTextField maxLengthToMatch; private JCheckBox enableMaxLength; private JCheckBox enableFiltering; private JCheckBox multilineOutput; private JButton DONATEButton; private JCheckBox showStatsInConsole; private JCheckBox showStatsInStatusBar; private JButton addNewGroup; private JLabel contextSpecificText; private JCheckBox enableFoldings; private JFormattedTextField maxProcessingTime; private JCheckBox filterOutBeforeGreppingToASubConsole; private JButton web; private JCheckBox alwaysPinGrepConsoles; private JFormattedTextField maxLengthToGrep; private JCheckBox enableMaxLengthGrep; private JButton rehighlightAll; private JButton help; private JCheckBox multilineInputFilter; private CheckboxTreeTable inputTable; private JButton tranformationHelp; private JButton installLivePlugin; private JButton addLivePluginScript; private JPanel highlightersPanel; private JPanel transfrormersPanel; private JPanel settings; private JSplitPane splitPane; private JButton resetHighlighters; private JCheckBox testHighlightersFirst; private JButton addNewInputFilterGroup; // private JCheckBox synchronous; public Profile profile; public ProfileDetail(MyConfigurable myConfigurable, SettingsContext settingsContext) { String value = PropertiesComponent.getInstance().getValue(DIVIDER); if (value != null) { try { splitPane.setDividerLocation(Integer.parseInt(value)); } catch (NumberFormatException e) { } } splitPane.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent pce) { Object newValue = pce.getNewValue(); PropertiesComponent.getInstance().setValue(DIVIDER, String.valueOf(newValue)); } } ); DONATEButton.setBorder(null); DONATEButton.setContentAreaFilled(false); DONATEButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { BareBonesBrowserLaunch.openURL("https: } }); web.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { BareBonesBrowserLaunch.openURL("https://plugins.jetbrains.com/plugin/7125-grep-console"); } }); rehighlightAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myConfigurable.apply(null); ServiceManager.getInstance().rehighlight(); } }); resetToDefaultButton.addActionListener(new ResetAllToDefaultAction()); addNewButton.addActionListener(new AddNewItemAction(grepTable, false)); addNewGroup.addActionListener(new AddNewGroupAction(grepTable)); addNewInputFilterGroup.addActionListener(new AddNewGroupAction(inputTable)); grepTable.addMouseListener(rightClickMenu(grepTable, false)); grepTable.addKeyListener(new DeleteListener(grepTable)); inputTable.addMouseListener(rightClickMenu(inputTable, true)); inputTable.addKeyListener(new DeleteListener(inputTable)); if (settingsContext == SettingsContext.CONSOLE) { contextSpecificText.setText("Select items for which statistics should be displayed ('" + GrepTableBuilder.CONSOLE_COUNT + "' column)"); } else if (settingsContext == SettingsContext.STATUS_BAR) { contextSpecificText.setText("Select items for which statistics should be displayed ('" + GrepTableBuilder.STATUS_BAR_COUNT + "' column)"); } else { contextSpecificText.setVisible(false); } help.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Messages.showInfoMessage(rootComponent, "Whole line - Matches a whole line, otherwise finds a matching substrings - 'Unless expression' works only for whole lines.\n" + "Continue matching - Matches a line against the next configured items to apply multiple highlights.\n" , "Columns Caveats"); } }); tranformationHelp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Messages.showInfoMessage(rootComponent, "You can manipulate output text or execute any custom actions (e.g. notifications) by making your own extension plugin or by scripting via LivePlugin - https://github.com/dkandalov/live-plugin\n\n" + "Whole line - Matches a whole line, otherwise finds a matching substrings - 'Unless expression' works only for whole lines.\n" + "Continue matching - Matches a line against the next configured items.\n" , "Input filtering"); } }); boolean livePlugin = PluginManager.isPluginInstalled(PluginId.getId("LivePlugin")); installLivePlugin.setEnabled(!livePlugin); addLivePluginScript.setEnabled(livePlugin); installLivePlugin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { HashSet<String> pluginIds = new HashSet<>(); pluginIds.add("LivePlugin"); PluginsAdvertiser.installAndEnablePlugins(pluginIds, new Runnable() { @Override public void run() { installLivePlugin.setEnabled(false); } }); } }); addLivePluginScript.addActionListener(new LivePluginExampleAction(addLivePluginScript)); resetHighlighters.addActionListener(new ResetHighlightersToDefaultAction()); } public MouseAdapter rightClickMenu(CheckboxTreeTable table, boolean input) { return new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { } else if (SwingUtilities.isRightMouseButton(e)) { boolean somethingSelected = getSelectedNode(table) != null; JPopupMenu popup = new JBPopupMenu(); GrepExpressionItem selectedGrepExpressionItem = getSelectedGrepExpressionItem(table); if (selectedGrepExpressionItem != null) { popup.add(getConvertAction(selectedGrepExpressionItem, table)); popup.add(new JPopupMenu.Separator()); } popup.add(newMenuItem("Add New Item", new AddNewItemAction(table, input))); if (somethingSelected) { popup.add(newMenuItem("Duplicate", new DuplicateAction(table))); } popup.add(new JPopupMenu.Separator()); CopyAction copyAction = (CopyAction) ActionManager.getInstance().getAction("$Copy"); if (somethingSelected) { popup.add(newMenuItem("Copy (" + KeymapUtil.getFirstKeyboardShortcutText(copyAction) + ")", new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyAction.actionPerformed(new AnActionEvent(null, DataManager.getInstance().getDataContext(table), ActionPlaces.UNKNOWN, new Presentation(""), ActionManager.getInstance(), 0)); } })); CutAction cutAction = (CutAction) ActionManager.getInstance().getAction("$Cut"); popup.add(newMenuItem("Cut (" + KeymapUtil.getFirstKeyboardShortcutText(cutAction) + ")", new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cutAction.actionPerformed(new AnActionEvent(null, DataManager.getInstance().getDataContext(table), ActionPlaces.UNKNOWN, new Presentation(""), ActionManager.getInstance(), 0)); } })); } PasteAction pasteAction = (PasteAction) ActionManager.getInstance().getAction("$Paste"); popup.add(newMenuItem("Paste (" + KeymapUtil.getFirstKeyboardShortcutText(pasteAction) + ")", new ActionListener() { @Override public void actionPerformed(ActionEvent e) { pasteAction.actionPerformed(new AnActionEvent(null, DataManager.getInstance().getDataContext(table), ActionPlaces.UNKNOWN, new Presentation(""), ActionManager.getInstance(), 0)); } })); if (somethingSelected) { popup.add(newMenuItem("Delete (Del)", new DeleteAction(table))); } popup.show(e.getComponent(), e.getX(), e.getY()); } } private JBMenuItem newMenuItem(String name, ActionListener l) { final JBMenuItem item = new JBMenuItem(name); item.addActionListener(l); return item; } private JBMenuItem getConvertAction(final GrepExpressionItem item, CheckboxTreeTable table) { final boolean highlightOnlyMatchingText = item.isHighlightOnlyMatchingText(); final JBMenuItem convert = new JBMenuItem(highlightOnlyMatchingText ? "Convert to whole line" : "Convert to words only"); try { convert.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!highlightOnlyMatchingText) { getSelectedGrepExpressionItem(table).setHighlightOnlyMatchingText(true); getSelectedGrepExpressionItem(table).setContinueMatching(true); if (item.getGrepExpression().startsWith(".*")) { item.grepExpression(item.getGrepExpression().substring(2)); } if (item.getGrepExpression().endsWith(".*")) { item.grepExpression(item.getGrepExpression().substring(0, item.getGrepExpression().length() - 2)); } } else { getSelectedGrepExpressionItem(table).setHighlightOnlyMatchingText(false); getSelectedGrepExpressionItem(table).setContinueMatching(false); if (!item.getGrepExpression().startsWith(".*")) { item.grepExpression(".*" + item.getGrepExpression()); } if (!item.getGrepExpression().endsWith(".*")) { item.grepExpression(item.getGrepExpression() + ".*"); } } reloadNode(ProfileDetail.this.getSelectedNode(table), table); } }); } catch (Exception e) { e.printStackTrace(); } return convert; } }; } private void reloadNode(final DefaultMutableTreeNode selectedNode, CheckboxTreeTable grepTable) { DefaultTreeModel model = (DefaultTreeModel) grepTable.getTree().getModel(); model.nodeChanged(selectedNode); } private GrepExpressionItem getSelectedGrepExpressionItem(CheckboxTreeTable grepTable) { DefaultMutableTreeNode selectedNode = getSelectedNode(grepTable); GrepExpressionItem item = null; if (selectedNode instanceof GrepExpressionItemTreeNode) { item = (GrepExpressionItem) selectedNode.getUserObject(); } return item; } public DefaultMutableTreeNode getSelectedNode(CheckboxTreeTable table) { return (DefaultMutableTreeNode) table.getTree().getLastSelectedPathComponent(); } public JPanel getRootComponent() { return rootComponent; } public Profile getSettings() { getData(profile); return profile; } public void importFrom(@NotNull Profile profile) { if (this.profile != null) {//keep changes when switching to another profile getData(this.profile); } this.profile = profile; setData(profile); resetTreeModel(profile.isDefaultProfile()); } public void resetTreeModel(boolean foldingsEnabled) { ((GrepTableBuilder.MyCheckboxTreeTable) grepTable).foldingsEnabled(foldingsEnabled); resetTable(grepTable, this.profile.getGrepExpressionGroups()); enableFoldings.setEnabled(foldingsEnabled); resetTable(inputTable, this.profile.getInputFilterGroups()); } protected void resetTable(CheckboxTreeTable grepTable, List<GrepExpressionGroup> grepExpressionGroups) { CheckedTreeNode root = (CheckedTreeNode) grepTable.getTree().getModel().getRoot(); root.removeAllChildren(); for (GrepExpressionGroup group : grepExpressionGroups) { GrepExpressionGroupTreeNode newChild = new GrepExpressionGroupTreeNode(group); root.add(newChild); } TableUtils.reloadTree(grepTable); TreeUtil.expandAll(grepTable.getTree()); } private void createUIComponents() { NumberFormatter numberFormatter = new NumberFormatter(); numberFormatter.setMinimum(0); maxLengthToMatch = new JFormattedTextField(numberFormatter); maxLengthToGrep = new JFormattedTextField(numberFormatter); maxProcessingTime = new JFormattedTextField(numberFormatter); grepTable = new GrepTableBuilder(this).getTable(); inputTable = new TransformerTableBuilder(this).getTable(); } public void rebuildProfile() { List<GrepExpressionGroup> grepExpressionGroups = profile.getGrepExpressionGroups(); grepExpressionGroups.clear(); fillProfileFromTable(grepExpressionGroups, grepTable); List<GrepExpressionGroup> inputFilterGroups = profile.getInputFilterGroups(); inputFilterGroups.clear(); fillProfileFromTable(inputFilterGroups, inputTable); } protected void fillProfileFromTable(List<GrepExpressionGroup> grepExpressionGroups, CheckboxTreeTable table) { DefaultMutableTreeNode model = (DefaultMutableTreeNode) table.getTree().getModel().getRoot(); Enumeration children = model.children(); while (children.hasMoreElements()) { DefaultMutableTreeNode o = (DefaultMutableTreeNode) children.nextElement(); if (o instanceof GrepExpressionGroupTreeNode) { GrepExpressionGroup grepExpressionGroup = ((GrepExpressionGroupTreeNode) o).getObject(); grepExpressionGroup.getGrepExpressionItems().clear(); Enumeration children1 = o.children(); while (children1.hasMoreElements()) { Object o1 = children1.nextElement(); if (o1 instanceof GrepExpressionItemTreeNode) { GrepExpressionItem grepExpressionItem = ((GrepExpressionItemTreeNode) o1).getGrepExpressionItem(); grepExpressionGroup.add(grepExpressionItem); } else { throw new IllegalStateException("unexpected tree node" + o1); } } grepExpressionGroups.add(grepExpressionGroup); } else { throw new IllegalStateException("unexpected tree node" + o); } } } public void setData(Profile data) { multilineInputFilter.setSelected(data.isMultilineInputFilter()); testHighlightersFirst.setSelected(data.isTestHighlightersInInputFilter()); multilineOutput.setSelected(data.isMultiLineOutput()); enableMaxLength.setSelected(data.isEnableMaxLengthLimit()); maxProcessingTime.setText(data.getMaxProcessingTime()); enableMaxLengthGrep.setSelected(data.isEnableMaxLengthGrepLimit()); maxLengthToMatch.setText(data.getMaxLengthToMatch()); maxLengthToGrep.setText(data.getMaxLengthToGrep()); enableHighlightingCheckBox.setSelected(data.isEnabledHighlighting()); enableFiltering.setSelected(data.isEnabledInputFiltering()); enableFoldings.setSelected(data.isEnableFoldings()); filterOutBeforeGreppingToASubConsole.setSelected(data.isFilterOutBeforeGrep()); showStatsInStatusBar.setSelected(data.isShowStatsInStatusBarByDefault()); showStatsInConsole.setSelected(data.isShowStatsInConsoleByDefault()); alwaysPinGrepConsoles.setSelected(data.isAlwaysPinGrepConsoles()); } public void getData(Profile data) { data.setMultilineInputFilter(multilineInputFilter.isSelected()); data.setTestHighlightersInInputFilter(testHighlightersFirst.isSelected()); data.setMultiLineOutput(multilineOutput.isSelected()); data.setEnableMaxLengthLimit(enableMaxLength.isSelected()); data.setMaxProcessingTime(maxProcessingTime.getText()); data.setEnableMaxLengthGrepLimit(enableMaxLengthGrep.isSelected()); data.setMaxLengthToMatch(maxLengthToMatch.getText()); data.setMaxLengthToGrep(maxLengthToGrep.getText()); data.setEnabledHighlighting(enableHighlightingCheckBox.isSelected()); data.setEnabledInputFiltering(enableFiltering.isSelected()); data.setEnableFoldings(enableFoldings.isSelected()); data.setFilterOutBeforeGrep(filterOutBeforeGreppingToASubConsole.isSelected()); data.setShowStatsInStatusBarByDefault(showStatsInStatusBar.isSelected()); data.setShowStatsInConsoleByDefault(showStatsInConsole.isSelected()); data.setAlwaysPinGrepConsoles(alwaysPinGrepConsoles.isSelected()); } public boolean isModified(Profile data) { if (multilineInputFilter.isSelected() != data.isMultilineInputFilter()) return true; if (testHighlightersFirst.isSelected() != data.isTestHighlightersInInputFilter()) return true; if (multilineOutput.isSelected() != data.isMultiLineOutput()) return true; if (enableMaxLength.isSelected() != data.isEnableMaxLengthLimit()) return true; if (maxProcessingTime.getText() != null ? !maxProcessingTime.getText().equals(data.getMaxProcessingTime()) : data.getMaxProcessingTime() != null) return true; if (enableMaxLengthGrep.isSelected() != data.isEnableMaxLengthGrepLimit()) return true; if (maxLengthToMatch.getText() != null ? !maxLengthToMatch.getText().equals(data.getMaxLengthToMatch()) : data.getMaxLengthToMatch() != null) return true; if (maxLengthToGrep.getText() != null ? !maxLengthToGrep.getText().equals(data.getMaxLengthToGrep()) : data.getMaxLengthToGrep() != null) return true; if (enableHighlightingCheckBox.isSelected() != data.isEnabledHighlighting()) return true; if (enableFiltering.isSelected() != data.isEnabledInputFiltering()) return true; if (enableFoldings.isSelected() != data.isEnableFoldings()) return true; if (filterOutBeforeGreppingToASubConsole.isSelected() != data.isFilterOutBeforeGrep()) return true; if (showStatsInStatusBar.isSelected() != data.isShowStatsInStatusBarByDefault()) return true; if (showStatsInConsole.isSelected() != data.isShowStatsInConsoleByDefault()) return true; if (alwaysPinGrepConsoles.isSelected() != data.isAlwaysPinGrepConsoles()) return true; return false; } private class DeleteListener extends KeyAdapter { private CheckboxTreeTable myTable; public DeleteListener(CheckboxTreeTable table) { myTable = table; } @Override public void keyPressed(KeyEvent e) { final int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_DELETE) { delete(myTable); } } } private void delete(CheckboxTreeTable table) { TreeNode selectNode = null; TreeTableTree tree = table.getTree(); int[] selectionRows = tree.getSelectionRows(); if (selectionRows == null) { return; } Arrays.sort(selectionRows); selectionRows = ArrayUtil.reverseArray(selectionRows); for (int selectionRow : selectionRows) { TreePath treePath = tree.getPathForRow(selectionRow); DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent(); if (selectNode == null || selectNode == selectedNode || selectNode.getParent() == selectedNode) { int index = parent.getIndex(selectedNode); if (index + 1 < parent.getChildCount()) { selectNode = parent.getChildAt(index + 1); } else if (index > 0) { selectNode = parent.getChildAt(index - 1); } else { selectNode = parent; } } parent.remove(selectedNode); } rebuildProfile(); TableUtils.reloadTree(table); TableUtils.selectNode((DefaultMutableTreeNode) selectNode, table); } private class AddNewItemAction implements ActionListener { private CheckboxTreeTable myTable; private final boolean input; public AddNewItemAction(CheckboxTreeTable table, boolean input) { myTable = table; this.input = input; } @Override public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode selectedNode = getSelectedNode(myTable); GrepExpressionItem userObject; if (input) { GrepExpressionItem item = new GrepExpressionItem(); item.setInputFilter(true); item.action(GrepExpressionItem.ACTION_REMOVE); item.setGrepExpression(".*unwanted line.*"); item.setEnabled(true); userObject = item; } else { GrepExpressionItem item = new GrepExpressionItem(); item.setGrepExpression("foo"); item.setEnabled(true); item.setContinueMatching(true); item.setHighlightOnlyMatchingText(true); item.getStyle().setBackgroundColor(new GrepColor(true, JBColor.CYAN)); userObject = item; } final CheckedTreeNode newChild = new GrepExpressionItemTreeNode(userObject); if (selectedNode == null) { DefaultMutableTreeNode root = (DefaultMutableTreeNode) myTable.getTree().getModel().getRoot(); DefaultMutableTreeNode lastChild = getLastChild(root); if (lastChild == null) { GrepExpressionGroupTreeNode aNew = new GrepExpressionGroupTreeNode(new GrepExpressionGroup("new")); aNew.add(newChild); root.add(aNew); } else { lastChild.add(newChild); } } else if (selectedNode.getUserObject() instanceof GrepExpressionGroup) { selectedNode.add(newChild); } else { GrepExpressionGroupTreeNode parent = (GrepExpressionGroupTreeNode) selectedNode.getParent(); parent.insert(newChild, parent.getIndex(selectedNode) + 1); } rebuildProfile(); TableUtils.reloadTree(myTable); TableUtils.selectNode(newChild, myTable); myTable.requestFocus(); } } protected DefaultMutableTreeNode getLastChild(DefaultMutableTreeNode root) { try { return (DefaultMutableTreeNode) root.getLastChild(); } catch (NoSuchElementException e) { return null; } } private class AddNewGroupAction implements ActionListener { private CheckboxTreeTable myTable; public AddNewGroupAction(CheckboxTreeTable table) { this.myTable = table; } @Override public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode root = (DefaultMutableTreeNode) myTable.getTree().getModel().getRoot(); GrepExpressionGroupTreeNode aNew = new GrepExpressionGroupTreeNode(new GrepExpressionGroup("new")); root.add(aNew); rebuildProfile(); TableUtils.reloadTree(myTable); TableUtils.selectNode(aNew, myTable); myTable.requestFocus(); } } private class ResetAllToDefaultAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { Profile profile = ProfileDetail.this.profile; ProfileDetail.this.profile = null; profile.resetToDefault(); importFrom(profile); } } private class ResetHighlightersToDefaultAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { Profile profile = ProfileDetail.this.profile; List<GrepExpressionGroup> grepExpressionGroups = profile.getGrepExpressionGroups(); grepExpressionGroups.clear(); grepExpressionGroups.add(new GrepExpressionGroup("default", DefaultState.createDefaultItems())); importFrom(profile); } } private class DuplicateAction implements ActionListener { private CheckboxTreeTable myTable; public DuplicateAction(CheckboxTreeTable table) { this.myTable = table; } @Override public void actionPerformed(ActionEvent e) { CheckboxTreeTable table = this.myTable; DefaultMutableTreeNode selectedNode = getSelectedNode(this.myTable); if (selectedNode instanceof GrepExpressionItemTreeNode) { GrepExpressionItemTreeNode newChild = new GrepExpressionItemTreeNode(deepClone((GrepExpressionItem) selectedNode.getUserObject())); DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent(); parent.insert(newChild, parent.getIndex(selectedNode) + 1); TableUtils.reloadTree(table); TableUtils.selectNode(newChild, table); } else if (selectedNode instanceof GrepExpressionGroupTreeNode) { GrepExpressionGroup group = deepClone((GrepExpressionGroup) selectedNode.getUserObject()); GrepExpressionGroupTreeNode newChild = new GrepExpressionGroupTreeNode(group); DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent(); parent.insert(newChild, parent.getIndex(selectedNode) + 1); TableUtils.reloadTree(table); TableUtils.expand(newChild, table); TableUtils.selectNode(newChild, table); } rebuildProfile(); } } private class DeleteAction implements ActionListener { private CheckboxTreeTable myTable; public DeleteAction(CheckboxTreeTable grepTable) { myTable = grepTable; } @Override public void actionPerformed(ActionEvent e) { delete(myTable); } } }
package org.ovirt.engine.core.bll.hostdeploy; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import javax.inject.Inject; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.QueriesCommandBase; import org.ovirt.engine.core.bll.VdsHandler; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.utils.RpmVersionUtils; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.RpmVersion; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.core.dao.VdsDynamicDao; /** * The {@code GetoVirtISOsQuery} is responsible to detect all available oVirt images installed on engine server. It detects * the available ISOs files by there associated version files, read the iSOs' version from within the version files, * verifies image files exist, and returns list of ISOs sorted by their version. */ public class GetoVirtISOsQuery<P extends IdQueryParameters> extends QueriesCommandBase<P> { private static final String OVIRT_ISO_VERSION_PREFIX = "version"; private static final String OVIRT_ISO_VDSM_COMPATIBILITY_PREFIX = "vdsm-compatibility"; @Inject private VdsDynamicDao hostDynamicDao; public GetoVirtISOsQuery(P parameters) { super(parameters); } @Override protected void executeCommand() { super.executeCommand(); } @Override protected void executeQueryCommand() { List<RpmVersion> availableISOsList = new ArrayList<>(); VDS vds = getVdsByVdsId(getParameters().getId()); if (vds == null) { getQueryReturnValue().setReturnValue(availableISOsList); return; } RpmVersion vdsOsVersion = VdsHandler.getOvirtHostOsVersion(vds); String nodeOS = vds.getHostOs(); if (nodeOS == null) { getQueryReturnValue().setReturnValue(new ArrayList<RpmVersion>()); return; } for (OVirtNodeInfo.Entry info : OVirtNodeInfo.getInstance().get()) { log.debug( "nodeOS [{}] | osPattern [{}] | minimumVersion [{}]", nodeOS, info.osPattern, info.minimumVersion ); Matcher matcher = info.osPattern.matcher(nodeOS); if (matcher.matches() && info.path.isDirectory()) { log.debug("Looking for list of ISOs in [{}], regex [{}]", info.path, info.isoPattern); File[] files = info.path.listFiles(); if (files != null) { for (File file : files) { matcher = info.isoPattern.matcher(file.getName()); if (matcher.matches()) { log.debug("ISO Found [{}]", file); String version = matcher.group(1); log.debug("ISO Version [{}]", version); File versionFile = new File(info.path, String.format("version-%s.txt", version)); log.debug("versionFile [{}]", versionFile); // Setting IsoData Class to get further [version] and [vdsm compatibility version] data IsoData isoData = new IsoData(); isoData.setVersion(readIsoVersion(versionFile)); String isoVersionText = isoData.getVersion(); isoData.setVdsmCompitibilityVersion(readVdsmCompatibiltyVersion(( versionFile.getAbsolutePath().replace(OVIRT_ISO_VERSION_PREFIX, OVIRT_ISO_VDSM_COMPATIBILITY_PREFIX)))); if (StringUtils.isEmpty(isoVersionText)) { log.debug("Iso version file '{}' is empty.", versionFile.getAbsolutePath()); continue; } String[] versionParts = isoVersionText.split(","); if (versionParts.length < 2) { log.debug("Iso version file '{}' contains invalid content. Expected: <major-version>,<release> format.", versionFile.getAbsolutePath()); continue; } RpmVersion isoVersion = new RpmVersion(file.getName()); if (isoData.getVdsmCompatibilityVersion() != null && isIsoCompatibleForUpgradeByClusterVersion(isoData) || vdsOsVersion != null && VdsHandler.isIsoVersionCompatibleForUpgrade(vdsOsVersion, isoVersion) ) { availableISOsList.add(isoVersion); } } } } } } Collections.sort(availableISOsList); getQueryReturnValue().setReturnValue(availableISOsList); updateUpdatesAvailableForHost(availableISOsList, vds); } public void updateUpdatesAvailableForHost(List<RpmVersion> availableIsos, VDS vds) { boolean updateAvailable = RpmVersionUtils.isUpdateAvailable(availableIsos, vds.getHostOs()); if (updateAvailable != vds.isUpdateAvailable()) { hostDynamicDao.updateUpdateAvailable(vds.getId(), updateAvailable); } } private boolean isIsoCompatibleForUpgradeByClusterVersion(IsoData isoData) { for (String v : isoData.getVdsmCompatibilityVersion()) { Version isoClusterVersion = new Version(v); if (isNewerVersion(isoClusterVersion)) { return true; } } return false; } private boolean isNewerVersion(Version isoClusterVersion) { VDS vds = getVdsByVdsId(getParameters().getId()); Version vdsClusterVersion = vds.getVdsGroupCompatibilityVersion(); log.debug( "vdsClusterVersion '{}' isoClusterVersion '{}'", vdsClusterVersion, isoClusterVersion ); return (vdsClusterVersion.getMajor() == isoClusterVersion.getMajor() && vdsClusterVersion.getMinor() <= isoClusterVersion.getMinor()); } private String[] readVdsmCompatibiltyVersion(String fileName) { File file = new File(fileName); String[] versions = null; if (file.exists()) { BufferedReader input = null; try { input = new BufferedReader(new FileReader(file)); String lineRead = input.readLine(); if (lineRead != null) { versions = lineRead.split(","); } } catch (FileNotFoundException e) { log.error("Failed to open version file '{}': {}", file.getParent(), e.getMessage()); log.debug("Exception", e); } catch (IOException e) { log.error("Failed to read version from '{}': {}", file.getAbsolutePath(), e.getMessage()); log.debug("Exception", e); } finally { if (input != null) { try { input.close(); } catch (IOException ignored) { // Ignore exception on closing a file } } } } return versions; } private String readIsoVersion(File versionFile) { String isoVersionText = null; BufferedReader input = null; try { input = new BufferedReader(new FileReader(versionFile)); isoVersionText = input.readLine(); } catch (FileNotFoundException e) { log.error("Failed to open version file '{}': {}", versionFile.getAbsolutePath(), e.getMessage()); log.debug("Exception", e); } catch (IOException e) { log.error("Failed to read version from '{}': {}", versionFile.getAbsolutePath(), e.getMessage()); log.debug("Exception", e); } finally { if (input != null) { try { input.close(); } catch (IOException ignored) { // Ignore exception on closing a file } } } return isoVersionText; } public VDS getVdsByVdsId(Guid vdsId) { VDS vds = null; if (vdsId != null) { vds = getDbFacade().getVdsDao().get(vdsId); } return vds; } private class IsoData { private String version; private String[] vdsmCompatibilityVersion; public void setVersion(String version) { this.version = version; } public String getVersion() { return version; } public void setVdsmCompitibilityVersion(String[] supportedClusterVersion) { this.vdsmCompatibilityVersion = supportedClusterVersion; } public String[] getVdsmCompatibilityVersion() { return vdsmCompatibilityVersion; } } }
package org.ovirt.engine.core.bll.network.host; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.CommandBase; import org.ovirt.engine.core.bll.network.NetworkParametersBuilder; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.LabelNicParameters; import org.ovirt.engine.core.common.action.SetupNetworksParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.businessentities.Entities; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface; import org.ovirt.engine.core.common.errors.VdcBLLException; import org.ovirt.engine.core.common.errors.VdcBllErrors; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.common.utils.ValidationUtils; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.utils.NetworkUtils; public class LabelNicCommand<T extends LabelNicParameters> extends CommandBase<T> { private VdsNetworkInterface nic; private List<Network> labeledNetworks; private List<VdsNetworkInterface> hostNics; public LabelNicCommand(T parameters) { super(parameters); setVdsId(getNic() == null ? null : getNic().getVdsId()); } @Override protected void executeCommand() { VdcReturnValueBase result = getBackend().runInternalAction(VdcActionType.PersistentSetupNetworks, new AddNetworksByLabelParametersBuilder().buildParameters(getNic(), getLabel(), getClusterNetworksByLabel())); if (result.getSucceeded()) { getReturnValue().setActionReturnValue(getLabel()); } else { propagateFailure(result); } setSucceeded(result.getSucceeded()); } @Override protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__LABEL); } @Override protected boolean canDoAction() { if (getNic() == null) { return failCanDoAction(VdcBllMessages.HOST_NETWORK_INTERFACE_NOT_EXIST); } if (NetworkUtils.isLabeled(getNic()) && getNic().getLabels().contains(getLabel())) { return failCanDoAction(VdcBllMessages.INTERFACE_ALREADY_LABELED); } if (!ValidationUtils.validateInputs(getValidationGroups(), getNic()).isEmpty()) { return failCanDoAction(VdcBllMessages.IMPROPER_INTERFACE_IS_LABELED); } if (Boolean.TRUE.equals(getNic().getBonded())) { int slavesCount = 0; for (VdsNetworkInterface nic : getHostInterfaces()) { if (StringUtils.equals(getNic().getName(), nic.getBondName())) { slavesCount++; if (slavesCount == 2) { break; } } } if (slavesCount < 2) { return failCanDoAction(VdcBllMessages.IMPROPER_INTERFACE_IS_LABELED); } } for (VdsNetworkInterface nic : getHostInterfaces()) { if (!StringUtils.equals(nic.getName(), getNicName()) && NetworkUtils.isLabeled(nic) && nic.getLabels().contains(getLabel())) { return failCanDoAction(VdcBllMessages.OTHER_INTERFACE_ALREADY_LABELED, "$LabeledNic " + nic.getName()); } } List<String> assignedNetworks = validateNetworksNotAssignedToIncorrectNics(); if (!assignedNetworks.isEmpty()) { return failCanDoAction(VdcBllMessages.LABELED_NETWORK_ATTACHED_TO_WRONG_INTERFACE, "$AssignedNetworks " + StringUtils.join(assignedNetworks, ", ")); } return true; } private List<VdsNetworkInterface> getHostInterfaces() { if (hostNics == null) { hostNics = getDbFacade().getInterfaceDao().getAllInterfacesForVds(getVdsId()); } return hostNics; } public List<String> validateNetworksNotAssignedToIncorrectNics() { Map<String, VdsNetworkInterface> nicsByNetworkName = Entities.hostInterfacesByNetworkName(getHostInterfaces()); List<String> badlyAssignedNetworks = new ArrayList<>(); for (Network network : getClusterNetworksByLabel()) { if (nicsByNetworkName.containsKey(network.getName())) { VdsNetworkInterface assignedNic = nicsByNetworkName.get(network.getName()); if (!StringUtils.equals(getNicName(), NetworkUtils.stripVlan(assignedNic.getName()))) { badlyAssignedNetworks.add(network.getName()); } } } return badlyAssignedNetworks; } private List<Network> getClusterNetworksByLabel() { if (labeledNetworks == null) { labeledNetworks = getNetworkDAO().getAllByLabelForCluster(getLabel(), getVds().getVdsGroupId()); } return labeledNetworks; } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.LABEL_NIC : AuditLogType.LABEL_NIC_FAILED; } private VdsNetworkInterface getNic() { if (nic == null) { nic = getDbFacade().getInterfaceDao().get(getParameters().getNicId()); } return nic; } public String getNicName() { return getNic().getName(); } public String getLabel() { return getParameters().getLabel(); } @Override public List<PermissionSubject> getPermissionCheckSubjects() { Guid hostId = getNic() == null ? null : getNic().getVdsId(); return Collections.singletonList(new PermissionSubject(hostId, VdcObjectType.VDS, getActionType().getActionGroup())); } private class AddNetworksByLabelParametersBuilder extends NetworkParametersBuilder { public SetupNetworksParameters buildParameters(VdsNetworkInterface nic, String label, List<Network> labeledNetworks) { SetupNetworksParameters parameters = createSetupNetworksParameters(nic.getVdsId()); Set<Network> networkToAdd = getNetworksToConfigure(parameters.getInterfaces(), labeledNetworks); VdsNetworkInterface nicToConfigure = getNicToConfigure(parameters.getInterfaces(), nic.getId()); if (nicToConfigure == null) { throw new VdcBLLException(VdcBllErrors.LABELED_NETWORK_INTERFACE_NOT_FOUND); } // add label to nic to be passed to setup-networks labelConfiguredNic(label, nicToConfigure); // configure networks on the nic parameters.getInterfaces().addAll(configureNetworks(nicToConfigure, networkToAdd)); return parameters; } public void labelConfiguredNic(String label, VdsNetworkInterface nicToConfigure) { if (nicToConfigure.getLabels() == null) { nicToConfigure.setLabels(new HashSet<String>()); } nicToConfigure.getLabels().add(label); } public Set<Network> getNetworksToConfigure(List<VdsNetworkInterface> nics, List<Network> labeledNetworks) { Map<String, VdsNetworkInterface> nicsByNetworkName = Entities.hostInterfacesByNetworkName(nics); Set<Network> networkToAdd = new HashSet<>(); for (Network network : labeledNetworks) { if (!nicsByNetworkName.containsKey(network.getName())) { networkToAdd.add(network); } } return networkToAdd; } /** * Configure the networks on a specific nic and/or returns a list of vlans as new added interfaces configured * with vlan networks * * @param nic * the underlying interface to configure * @param networks * the networks to configure on the nic * @return a list of vlan devices or an empty list */ public List<VdsNetworkInterface> configureNetworks(VdsNetworkInterface nic, Set<Network> networks) { List<VdsNetworkInterface> vlans = new ArrayList<>(); for (Network network : networks) { configureNetwork(nic, vlans, network); } return vlans; } } }
package com.opengamma.util; import java.io.File; import java.io.InputStream; import org.apache.commons.io.IOUtils; import com.opengamma.OpenGammaRuntimeException; // NOTE kirk 2013-12-10 -- Before adding anything to this, check to see if // the functionality you require is in another class or project // (in particular IOUtils). /** * A collection of utility methods for working with files. */ public final class FileUtils { private static final File TEMP_DIR = new File(System.getProperty("java.io.tmpdir")); private FileUtils() { } public static File copyResourceToTempFile(InputStream resource) { return copyResourceToTempFile(null, resource); } public static File copyResourceToTempFile(InputStream resource, String fileName) { return copyResourceToTempFile((String) null, resource, fileName); } public static File copyResourceToTempFile(String subdirName, InputStream resource) { return copyResourceToTempFile(subdirName, resource, null); } public static File copyResourceToTempFile(String subdirName, InputStream resource, String fileName) { File tempDir = TEMP_DIR; if (!(subdirName == null)) { tempDir = new File(TEMP_DIR, subdirName); if (tempDir.exists()) { if (!tempDir.isDirectory()) { throw new IllegalStateException("" + tempDir + " already exists and is not a directory."); } } else { tempDir.mkdirs(); } } return copyResourceToTempFile(tempDir, resource, fileName); } public static File copyResourceToTempFile(File tempDir, InputStream resource, String fileName) { ArgumentChecker.notNull(resource, "resource"); File tempFile = null; if (fileName == null) { tempFile = new File(tempDir, "test-" + System.nanoTime()); } else { tempFile = new File(tempDir, fileName); } if (tempFile.exists()) { tempFile.delete(); } try { org.apache.commons.io.FileUtils.copyInputStreamToFile(resource, tempFile); IOUtils.closeQuietly(resource); } catch (Exception e) { throw new OpenGammaRuntimeException("Unable to copy resource to " + tempFile, e); } tempFile.deleteOnExit(); return tempFile; } }
package com.bluesnap.androidapi.views.activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import com.bluesnap.androidapi.R; import com.bluesnap.androidapi.models.BillingInfo; import com.bluesnap.androidapi.models.CreditCardInfo; import com.bluesnap.androidapi.models.PriceDetails; import com.bluesnap.androidapi.models.SDKConfiguration; import com.bluesnap.androidapi.models.SdkRequest; import com.bluesnap.androidapi.models.Shopper; import com.bluesnap.androidapi.models.SupportedPaymentMethods; import com.bluesnap.androidapi.services.BSPaymentRequestException; import com.bluesnap.androidapi.services.BlueSnapService; import com.bluesnap.androidapi.services.BluesnapAlertDialog; import com.bluesnap.androidapi.services.BluesnapServiceCallback; import com.bluesnap.androidapi.views.adapters.OneLineCCViewAdapter; import org.json.JSONObject; import java.util.ArrayList; public class BluesnapCheckoutActivity extends AppCompatActivity { public static final String SDK_ERROR_MSG = "SDK_ERROR_MESSAGE"; public static final String EXTRA_PAYMENT_RESULT = "com.bluesnap.intent.BSNAP_PAYMENT_RESULT"; public static final String EXTRA_SHIPPING_DETAILS = "com.bluesnap.intent.BSNAP_SHIPPING_DETAILS"; public static final String EXTRA_BILLING_DETAILS = "com.bluesnap.intent.BSNAP_BILLING_DETAILS"; public static final int REQUEST_CODE_DEFAULT = 1; static final int RESULT_SDK_FAILED = -2; private static final String TAG = BluesnapCheckoutActivity.class.getSimpleName(); public static String FRAGMENT_TYPE = "FRAGMENT_TYPE"; public static String NEW_CC = "NEW_CC"; public static String RETURNING_CC = "RETURNING_CC"; public static String PAY_PAL = "PAY_PAL"; private LinearLayout payPalButton, newCardButton; private ProgressBar progressBar; private ListView oneLineCCViewComponentsListView; private SdkRequest sdkRequest; private SDKConfiguration sdkConfiguration; private Shopper shopper; private OneLineCCViewAdapter oneLineCCViewAdapter; private final BlueSnapService blueSnapService = BlueSnapService.getInstance(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.choose_payment_method); sdkRequest = blueSnapService.getSdkRequest(); sdkConfiguration = blueSnapService.getsDKConfiguration(); if (verifySDKRequest()) { loadShopperFromSDKConfiguration(); newCardButton = (LinearLayout) findViewById(R.id.newCardButton); newCardButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startCreditCardActivityForResult(FRAGMENT_TYPE, NEW_CC); } }); payPalButton = (LinearLayout) findViewById(R.id.payPalButton); progressBar = (ProgressBar) findViewById(R.id.progressBar); if (!sdkConfiguration.getSupportedPaymentMethods().isPaymentMethodActive(SupportedPaymentMethods.PAYPAL)) { payPalButton.setVisibility(View.GONE); } else { payPalButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String payPalToken = BlueSnapService.getPayPalToken(); if ("".equals(payPalToken)) { Log.d(TAG, "create payPalToken"); startPayPal(); } else { Log.d(TAG, "startWebViewActivity"); startWebViewActivity(payPalToken); } } }); } } } @Override protected void onStart() { super.onStart(); verifySDKRequest(); } /** * start Credit Card Activity For Result * * @param intentExtraName - The name of the extra data, with package prefix. * @param intentExtravalue - The String data value. */ private void startCreditCardActivityForResult(String intentExtraName, String intentExtravalue) { Intent intent = new Intent(getApplicationContext(), CreditCardActivity.class); intent.putExtra(intentExtraName, intentExtravalue); startActivityForResult(intent, CreditCardActivity.CREDIT_CARD_ACTIVITY_REQUEST_CODE); } /** * gets Shopper from SDK configuration and populate returning shopper cards (from populateFromCard function) or create a new shopper if shopper object does not exists */ private void loadShopperFromSDKConfiguration() { final Shopper shopper = sdkConfiguration.getShopper(); if (shopper == null) { Log.d(TAG, "SDK configurations contains no shopper, creating new."); sdkConfiguration.setShopper(new Shopper()); return; } this.shopper = shopper; updateShopperCCViews(shopper); } private void updateShopperCCViews(@NonNull final Shopper shopper) { if (null == shopper.getPreviousPaymentSources() || null == shopper.getPreviousPaymentSources().getPreviousCreditCardInfos()) { Log.d(TAG, "Existing shopper contains no previous paymentSources or Previous card info"); return; } //create an ArrayList<CreditCardInfo> for the ListView. ArrayList<CreditCardInfo> returningShopperCreditCardInfoArray = shopper.getPreviousPaymentSources().getPreviousCreditCardInfos(); //create an adapter to describe how the items are displayed. oneLineCCViewComponentsListView = (ListView) findViewById(R.id.oneLineCCViewComponentsListView); oneLineCCViewAdapter = new OneLineCCViewAdapter(this, returningShopperCreditCardInfoArray); oneLineCCViewComponentsListView.setAdapter(oneLineCCViewAdapter); oneLineCCViewComponentsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { shopper.setNewCreditCardInfo((CreditCardInfo) oneLineCCViewAdapter.getItem(position)); if (!sdkRequest.isEmailRequired()) shopper.getNewCreditCardInfo().getBillingContactInfo().setEmail(null); if (!sdkRequest.isBillingRequired()) { BillingInfo billingInfo = shopper.getNewCreditCardInfo().getBillingContactInfo(); billingInfo.setAddress(null); billingInfo.setCity(null); billingInfo.setState(null); } startCreditCardActivityForResult(FRAGMENT_TYPE, RETURNING_CC); } }); oneLineCCViewComponentsListView.setVisibility(View.VISIBLE); } /** * verify SDK Request * * @return boolean */ private boolean verifySDKRequest() { if (sdkRequest == null) { Log.e(TAG, "sdkrequest is null"); setResult(RESULT_SDK_FAILED, new Intent().putExtra(SDK_ERROR_MSG, "Activity has been aborted.")); finish(); return false; } else try { return sdkRequest.verify(); } catch (BSPaymentRequestException e) { String errorMsg = "payment request not validated:" + e.getMessage(); e.printStackTrace(); Log.d(TAG, errorMsg); setResult(RESULT_SDK_FAILED, new Intent().putExtra(SDK_ERROR_MSG, errorMsg)); finish(); return false; } } /** * start PayPal * createsPayPal Token and redirects to Web View Activity */ private void startPayPal() { progressBar.setVisibility(View.VISIBLE); final PriceDetails priceDetails = sdkRequest.getPriceDetails(); BlueSnapService.getInstance().createPayPalToken(priceDetails.getAmount(), priceDetails.getCurrencyCode(), new BluesnapServiceCallback() { @Override public void onSuccess() { try { startWebViewActivity(BlueSnapService.getPayPalToken()); } catch (Exception e) { Log.w(TAG, "Unable to start webview activity", e); } } @Override public void onFailure() { try { JSONObject errorDescription = BlueSnapService.getErrorDescription(); Log.e(TAG, errorDescription.toString()); String message; String title; if (errorDescription.getString("code").equals("20027")) { // ToDo change to string.xml for translations, use string palceholders //message = errorDescription.getString("description") + " please change to a PayPal supported Currency or contact Support for additional assistance"; message = getString(R.string.CURRENCY_NOT_SUPPORTED_PART_1) + " " + sdkRequest.getPriceDetails().getCurrencyCode() + " " + getString(R.string.CURRENCY_NOT_SUPPORTED_PART_2) + " " + getString(R.string.SUPPORT_PLEASE) + " " + getString(R.string.CURRENCY_NOT_SUPPORTED_PART_3) + " " + getString(R.string.SUPPORT_OR) + " " + getString(R.string.SUPPORT); title = getString(R.string.CURRENCY_NOT_SUPPORTED_PART_TITLE); } else { message = getString(R.string.SUPPORT_PLEASE) + " " + getString(R.string.SUPPORT); title = getString(R.string.ERROR); } BluesnapAlertDialog.setDialog(getParent(), message, title); } catch (Exception e) { Log.e(TAG, "json parsing exception", e); BluesnapAlertDialog.setDialog(getParent(), "Paypal service error", "Error"); //TODO: friendly error } finally { progressBar.setVisibility(View.INVISIBLE); } } }); } /** * start WebView Activity for PayPal Checkout * * @param payPalUrl - received from createPayPalToken {@link com.bluesnap.androidapi.services.BlueSnapAPI} */ private void startWebViewActivity(String payPalUrl) { Intent newIntent; newIntent = new Intent(getApplicationContext(), WebViewActivity.class); // Todo change paypal header name to merchant name from payment request newIntent.putExtra(getString(R.string.WEBVIEW_STRING), "PayPal"); newIntent.putExtra(getString(R.string.WEBVIEW_URL), payPalUrl); newIntent.putExtra(getString(R.string.SET_JAVA_SCRIPT_ENABLED), true); startActivityForResult(newIntent, WebViewActivity.PAYPAL_REQUEST_CODE); progressBar.setVisibility(View.INVISIBLE); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "got result " + resultCode); Log.d(TAG, "got request " + requestCode); if (resultCode == Activity.RESULT_OK) { if (requestCode == CreditCardActivity.CREDIT_CARD_ACTIVITY_REQUEST_CODE) { setResult(Activity.RESULT_OK, data); finish(); } else if (requestCode == WebViewActivity.PAYPAL_REQUEST_CODE) { setResult(Activity.RESULT_OK, data); finish(); } } } }
package com.yahoo.jdisc.http.server.jetty; import com.google.inject.AbstractModule; import com.google.inject.Module; import com.yahoo.container.logging.ConnectionLog; import com.yahoo.container.logging.ConnectionLogEntry; import com.yahoo.container.logging.ConnectionLogEntry.SslHandshakeFailure.ExceptionEntry; import com.yahoo.container.logging.RequestLog; import com.yahoo.container.logging.RequestLogEntry; import com.yahoo.jdisc.References; import com.yahoo.jdisc.Request; import com.yahoo.jdisc.Response; import com.yahoo.jdisc.application.BindingSetSelector; import com.yahoo.jdisc.application.MetricConsumer; import com.yahoo.jdisc.handler.AbstractRequestHandler; import com.yahoo.jdisc.handler.CompletionHandler; import com.yahoo.jdisc.handler.ContentChannel; import com.yahoo.jdisc.handler.NullContent; import com.yahoo.jdisc.handler.RequestHandler; import com.yahoo.jdisc.handler.ResponseDispatch; import com.yahoo.jdisc.handler.ResponseHandler; import com.yahoo.jdisc.http.ConnectorConfig; import com.yahoo.jdisc.http.ConnectorConfig.Throttling; import com.yahoo.jdisc.http.Cookie; import com.yahoo.jdisc.http.HttpRequest; import com.yahoo.jdisc.http.HttpResponse; import com.yahoo.jdisc.http.ServerConfig; import com.yahoo.jdisc.http.server.jetty.JettyTestDriver.TlsClientAuth; import com.yahoo.jdisc.service.BindingSetNotFoundException; import com.yahoo.security.KeyUtils; import com.yahoo.security.Pkcs10Csr; import com.yahoo.security.Pkcs10CsrBuilder; import com.yahoo.security.SslContextBuilder; import com.yahoo.security.X509CertificateBuilder; import com.yahoo.security.X509CertificateUtils; import com.yahoo.security.tls.TlsContext; import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder; import org.apache.hc.client5.http.entity.mime.FormBodyPart; import org.apache.hc.client5.http.entity.mime.FormBodyPartBuilder; import org.apache.hc.client5.http.entity.mime.StringBody; import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; import org.apache.hc.client5.http.impl.async.H2AsyncClientBuilder; import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder; import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder; import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.nio.ssl.TlsStrategy; import org.apache.hc.core5.http2.HttpVersionPolicy; import org.assertj.core.api.Assertions; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.ProxyProtocolClientConnectionFactory.V1; import org.eclipse.jetty.client.ProxyProtocolClientConnectionFactory.V2; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.server.handler.AbstractHandlerContainer; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.security.auth.x500.X500Principal; import java.io.IOException; import java.math.BigInteger; import java.net.BindException; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyPair; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import static com.yahoo.jdisc.Response.Status.GATEWAY_TIMEOUT; import static com.yahoo.jdisc.Response.Status.INTERNAL_SERVER_ERROR; import static com.yahoo.jdisc.Response.Status.NOT_FOUND; import static com.yahoo.jdisc.Response.Status.OK; import static com.yahoo.jdisc.Response.Status.REQUEST_URI_TOO_LONG; import static com.yahoo.jdisc.Response.Status.UNAUTHORIZED; import static com.yahoo.jdisc.Response.Status.UNSUPPORTED_MEDIA_TYPE; import static com.yahoo.jdisc.http.HttpHeaders.Names.CONNECTION; import static com.yahoo.jdisc.http.HttpHeaders.Names.CONTENT_TYPE; import static com.yahoo.jdisc.http.HttpHeaders.Names.COOKIE; import static com.yahoo.jdisc.http.HttpHeaders.Names.X_DISABLE_CHUNKING; import static com.yahoo.jdisc.http.HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED; import static com.yahoo.jdisc.http.HttpHeaders.Values.CLOSE; import static com.yahoo.jdisc.http.server.jetty.SimpleHttpClient.ResponseValidator; import static com.yahoo.security.KeyAlgorithm.EC; import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA; import static org.cthul.matchers.CthulMatchers.containsPattern; import static org.cthul.matchers.CthulMatchers.matchesPattern; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Oyvind Bakksjo * @author Simon Thoresen Hult * @author bjorncs */ public class HttpServerTest { private static final Logger log = Logger.getLogger(HttpServerTest.class.getName()); @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); @Test public void requireThatServerCanListenToRandomPort() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(mockRequestHandler()); assertNotEquals(0, driver.server().getListenPort()); assertTrue(driver.close()); } @Test public void requireThatServerCanNotListenToBoundPort() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(mockRequestHandler()); try { JettyTestDriver.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder() .listenPort(driver.server().getListenPort()) ); } catch (final Throwable t) { assertThat(t.getCause(), instanceOf(BindException.class)); } assertTrue(driver.close()); } @Test public void requireThatBindingSetNotFoundReturns404() throws Exception { final JettyTestDriver driver = JettyTestDriver.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder() .developerMode(true), new ConnectorConfig.Builder(), newBindingSetSelector("unknown")); driver.client().get("/status.html") .expectStatusCode(is(NOT_FOUND)) .expectContent(containsPattern(Pattern.compile( Pattern.quote(BindingSetNotFoundException.class.getName()) + ": No binding set named &apos;unknown&apos;\\.\n\tat .+", Pattern.DOTALL | Pattern.MULTILINE))); assertTrue(driver.close()); } @Test public void requireThatTooLongInitLineReturns414() throws Exception { final JettyTestDriver driver = JettyTestDriver.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder() .requestHeaderSize(1)); driver.client().get("/status.html") .expectStatusCode(is(REQUEST_URI_TOO_LONG)); assertTrue(driver.close()); } @Test public void requireThatAccessLogIsCalledForRequestRejectedByJetty() throws Exception { BlockingQueueRequestLog requestLogMock = new BlockingQueueRequestLog(); final JettyTestDriver driver = JettyTestDriver.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder().requestHeaderSize(1), binder -> binder.bind(RequestLog.class).toInstance(requestLogMock)); driver.client().get("/status.html") .expectStatusCode(is(REQUEST_URI_TOO_LONG)); RequestLogEntry entry = requestLogMock.poll(Duration.ofSeconds(5)); assertEquals(414, entry.statusCode().getAsInt()); assertThat(driver.close(), is(true)); } @Test public void requireThatServerCanEcho() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoRequestHandler()); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatServerCanEchoCompressed() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoRequestHandler()); SimpleHttpClient client = driver.newClient(true); client.get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatServerCanHandleMultipleRequests() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoRequestHandler()); driver.client().get("/status.html") .expectStatusCode(is(OK)); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatFormPostWorks() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler()); final String requestContent = generateContent('a', 30); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent(requestContent) .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith('{' + requestContent + "=[]}")); assertTrue(driver.close()); } @Test public void requireThatFormPostDoesNotRemoveContentByDefault() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{foo=[bar]}foo=bar")); assertTrue(driver.close()); } @Test public void requireThatFormPostKeepsContentWhenConfiguredTo() throws Exception { final JettyTestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), false); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{foo=[bar]}foo=bar")); assertTrue(driver.close()); } @Test public void requireThatFormPostRemovesContentWhenConfiguredTo() throws Exception { final JettyTestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), true); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{foo=[bar]}")); assertTrue(driver.close()); } @Test public void requireThatFormPostWithCharsetSpecifiedWorks() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler()); final String requestContent = generateContent('a', 30); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(X_DISABLE_CHUNKING, "true") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=UTF-8") .setContent(requestContent) .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith('{' + requestContent + "=[]}")); assertTrue(driver.close()); } @Test public void requireThatEmptyFormPostWorks() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{}")); assertTrue(driver.close()); } @Test public void requireThatFormParametersAreParsed() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("a=b&c=d") .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith("{a=[b], c=[d]}")); assertTrue(driver.close()); } @Test public void requireThatUriParametersAreParsed() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html?a=b&c=d") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{a=[b], c=[d]}")); assertTrue(driver.close()); } @Test public void requireThatFormAndUriParametersAreMerged() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html?a=b&c=d1") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("c=d2&e=f") .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith("{a=[b], c=[d1, d2], e=[f]}")); assertTrue(driver.close()); } @Test public void requireThatFormCharsetIsHonored() throws Exception { final JettyTestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), true); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=ISO-8859-1") .setBinaryContent(new byte[]{66, (byte) 230, 114, 61, 98, 108, (byte) 229}) .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{B\u00e6r=[bl\u00e5]}")); assertTrue(driver.close()); } @Test public void requireThatUnknownFormCharsetIsTreatedAsBadRequest() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=FLARBA-GARBA-7") .setContent("a=b") .execute(); response.expectStatusCode(is(UNSUPPORTED_MEDIA_TYPE)); assertTrue(driver.close()); } @Test public void requireThatFormPostWithPercentEncodedContentIsDecoded() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("%20%3D%C3%98=%22%25+") .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith("{ =\u00d8=[\"% ]}")); assertTrue(driver.close()); } @Test public void requireThatFormPostWithThrowingHandlerIsExceptionSafe() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ThrowingHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("a=b") .execute(); response.expectStatusCode(is(INTERNAL_SERVER_ERROR)); assertTrue(driver.close()); } @Test public void requireThatMultiPostWorks() throws Exception { // This is taken from tcpdump of bug 5433352 and reassembled here to see that httpserver passes things on. final String startTxtContent = "this is a test for POST."; final String updaterConfContent = "identifier = updater\n" + "server_type = gds\n"; final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .setMultipartContent( newFileBody("start.txt", startTxtContent), newFileBody("updater.conf", updaterConfContent)) .execute(); response.expectStatusCode(is(OK)) .expectContent(containsString(startTxtContent)) .expectContent(containsString(updaterConfContent)); } @Test public void requireThatRequestCookiesAreReceived() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new CookiePrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(COOKIE, "foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(containsString("[foo=bar]")); assertTrue(driver.close()); } @Test public void requireThatSetCookieHeaderIsCorrect() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new CookieSetterRequestHandler( new Cookie("foo", "bar") .setDomain(".localhost") .setHttpOnly(true) .setPath("/foopath") .setSecure(true))); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectHeader("Set-Cookie", is("foo=bar; Path=/foopath; Domain=.localhost; Secure; HttpOnly")); assertTrue(driver.close()); } @Test public void requireThatTimeoutWorks() throws Exception { final UnresponsiveHandler requestHandler = new UnresponsiveHandler(); final JettyTestDriver driver = JettyTestDriver.newInstance(requestHandler); driver.client().get("/status.html") .expectStatusCode(is(GATEWAY_TIMEOUT)); ResponseDispatch.newInstance(OK).dispatch(requestHandler.responseHandler); assertTrue(driver.close()); } // Header with no value is disallowed by https://tools.ietf.org/html/rfc7230#section-3.2 @Test public void requireThatHeaderWithNullValueIsOmitted() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoWithHeaderRequestHandler("X-Foo", null)); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectNoHeader("X-Foo"); assertTrue(driver.close()); } // Header with empty value is allowed by https://tools.ietf.org/html/rfc7230#section-3.2 @Test public void requireThatHeaderWithEmptyValueIsAllowed() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoWithHeaderRequestHandler("X-Foo", "")); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectHeader("X-Foo", is("")); assertTrue(driver.close()); } @Test public void requireThatNoConnectionHeaderMeansKeepAliveInHttp11KeepAliveDisabled() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoWithHeaderRequestHandler(CONNECTION, CLOSE)); driver.client().get("/status.html") .expectHeader(CONNECTION, is(CLOSE)); assertThat(driver.close(), is(true)); } @Test public void requireThatConnectionIsClosedAfterXRequests() throws Exception { final int MAX_KEEPALIVE_REQUESTS = 100; final JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(new EchoRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder().maxRequestsPerConnection(MAX_KEEPALIVE_REQUESTS)); for (int i = 0; i < MAX_KEEPALIVE_REQUESTS - 1; i++) { driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectNoHeader(CONNECTION); } driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectHeader(CONNECTION, is(CLOSE)); assertTrue(driver.close()); } @Test public void requireThatServerCanRespondToSslRequest() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); final JettyTestDriver driver = JettyTestDriver.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatServerCanRespondToHttp2Request() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); MetricConsumerMock metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); JettyTestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); try (CloseableHttpAsyncClient client = createHttp2Client(driver)) { String uri = "https://localhost:" + driver.server().getListenPort() + "/status.html"; SimpleHttpResponse response = client.execute(SimpleRequestBuilder.get(uri).build(), null).get(); assertNull(response.getBodyText()); assertEquals(OK, response.getCode()); } assertTrue(driver.close()); ConnectionLogEntry entry = connectionLog.logEntries().get(0); assertEquals("HTTP/2.0", entry.httpProtocol().get()); } @Test public void requireThatTlsClientAuthenticationEnforcerRejectsRequestsForNonWhitelistedPaths() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); JettyTestDriver driver = createSslWithTlsClientAuthenticationEnforcer(certificateFile, privateKeyFile); SSLContext trustStoreOnlyCtx = new SslContextBuilder() .withTrustStore(certificateFile) .build(); new SimpleHttpClient(trustStoreOnlyCtx, driver.server().getListenPort(), false) .get("/dummy.html") .expectStatusCode(is(UNAUTHORIZED)); assertTrue(driver.close()); } @Test public void requireThatTlsClientAuthenticationEnforcerAllowsRequestForWhitelistedPaths() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); JettyTestDriver driver = JettyTestDriver.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT); SSLContext trustStoreOnlyCtx = new SslContextBuilder() .withTrustStore(certificateFile) .build(); new SimpleHttpClient(trustStoreOnlyCtx, driver.server().getListenPort(), false) .get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatConnectedAtReturnsNonZero() throws Exception { final JettyTestDriver driver = JettyTestDriver.newInstance(new ConnectedAtRequestHandler()); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectContent(matchesPattern("\\d{13,}")); assertThat(driver.close(), is(true)); } @Test public void requireThatGzipEncodingRequestsAreAutomaticallyDecompressed() throws Exception { JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler()); String requestContent = generateContent('a', 30); ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setGzipContent(requestContent) .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith('{' + requestContent + "=[]}")); assertTrue(driver.close()); } @Test public void requireThatResponseStatsAreCollected() throws Exception { RequestTypeHandler handler = new RequestTypeHandler(); JettyTestDriver driver = JettyTestDriver.newInstance(handler); HttpResponseStatisticsCollector statisticsCollector = ((AbstractHandlerContainer) driver.server().server().getHandler()) .getChildHandlerByClass(HttpResponseStatisticsCollector.class); { List<HttpResponseStatisticsCollector.StatisticsEntry> stats = statisticsCollector.takeStatistics(); assertEquals(0, stats.size()); } { driver.client().newPost("/status.html").execute(); var entry = waitForStatistics(statisticsCollector); assertEquals("http", entry.scheme); assertEquals("POST", entry.method); assertEquals("http.status.2xx", entry.name); assertEquals("write", entry.requestType); assertEquals(1, entry.value); } { driver.client().newGet("/status.html").execute(); var entry = waitForStatistics(statisticsCollector); assertEquals("http", entry.scheme); assertEquals("GET", entry.method); assertEquals("http.status.2xx", entry.name); assertEquals("read", entry.requestType); assertEquals(1, entry.value); } { handler.setRequestType(Request.RequestType.READ); driver.client().newPost("/status.html").execute(); var entry = waitForStatistics(statisticsCollector); assertEquals("Handler overrides request type", "read", entry.requestType); } assertTrue(driver.close()); } private HttpResponseStatisticsCollector.StatisticsEntry waitForStatistics(HttpResponseStatisticsCollector statisticsCollector) { List<HttpResponseStatisticsCollector.StatisticsEntry> entries = Collections.emptyList(); int tries = 0; while (entries.isEmpty() && tries < 10000) { entries = statisticsCollector.takeStatistics(); if (entries.isEmpty()) try {Thread.sleep(100); } catch (InterruptedException e) {} tries++; } assertEquals(1, entries.size()); return entries.get(0); } @Test public void requireThatConnectionThrottleDoesNotBlockConnectionsBelowThreshold() throws Exception { JettyTestDriver driver = JettyTestDriver.newConfiguredInstance( new EchoRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder() .throttling(new Throttling.Builder() .enabled(true) .maxAcceptRate(10) .maxHeapUtilization(1.0) .maxConnections(10))); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatMetricIsIncrementedWhenClientIsMissingCertificateOnHandshake() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); JettyTestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(certificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, null, "Received fatal alert: bad_certificate"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_MISSING_CLIENT_CERT, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.MISSING_CLIENT_CERT.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesIncompatibleTlsVersion() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); JettyTestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(certificateFile) .withKeyStore(privateKeyFile, certificateFile) .build(); boolean tlsv11Enabled = List.of(clientCtx.getDefaultSSLParameters().getProtocols()).contains("TLSv1.1"); assumeTrue("TLSv1.1 must be enabled in installed JDK", tlsv11Enabled); assertHttpsRequestTriggersSslHandshakeException(driver, clientCtx, "TLSv1.1", null, "protocol"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_INCOMPATIBLE_PROTOCOLS, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.INCOMPATIBLE_PROTOCOLS.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesIncompatibleCiphers() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); JettyTestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(certificateFile) .withKeyStore(privateKeyFile, certificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "Received fatal alert: handshake_failure"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_INCOMPATIBLE_CIPHERS, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.INCOMPATIBLE_CIPHERS.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesInvalidCertificateInHandshake() throws IOException { Path serverPrivateKeyFile = tmpFolder.newFile().toPath(); Path serverCertificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(serverPrivateKeyFile, serverCertificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); JettyTestDriver driver = createSslTestDriver(serverCertificateFile, serverPrivateKeyFile, metricConsumer, connectionLog); Path clientPrivateKeyFile = tmpFolder.newFile().toPath(); Path clientCertificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(clientPrivateKeyFile, clientCertificateFile); SSLContext clientCtx = new SslContextBuilder() .withKeyStore(clientPrivateKeyFile, clientCertificateFile) .withTrustStore(serverCertificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, null, "Received fatal alert: certificate_unknown"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_INVALID_CLIENT_CERT, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.INVALID_CLIENT_CERT.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesExpiredCertificateInHandshake() throws IOException { Path rootPrivateKeyFile = tmpFolder.newFile().toPath(); Path rootCertificateFile = tmpFolder.newFile().toPath(); Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); Instant notAfter = Instant.now().minus(100, ChronoUnit.DAYS); generatePrivateKeyAndCertificate(rootPrivateKeyFile, rootCertificateFile, privateKeyFile, certificateFile, notAfter); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); JettyTestDriver driver = createSslTestDriver(rootCertificateFile, rootPrivateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(rootCertificateFile) .withKeyStore(privateKeyFile, certificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, null, "Received fatal alert: certificate_unknown"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_EXPIRED_CLIENT_CERT, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); } @Test public void requireThatProxyProtocolIsAcceptedAndActualRemoteAddressStoredInAccessLog() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); JettyTestDriver driver = createSslWithProxyProtocolTestDriver(certificateFile, privateKeyFile, requestLogMock, /*mixedMode*/connectionLog, false); String proxiedRemoteAddress = "192.168.0.100"; int proxiedRemotePort = 12345; sendJettyClientRequest(driver, certificateFile, new V1.Tag(proxiedRemoteAddress, proxiedRemotePort)); sendJettyClientRequest(driver, certificateFile, new V2.Tag(proxiedRemoteAddress, proxiedRemotePort)); assertTrue(driver.close()); assertEquals(2, requestLogMock.entries().size()); assertLogEntryHasRemote(requestLogMock.entries().get(0), proxiedRemoteAddress, proxiedRemotePort); assertLogEntryHasRemote(requestLogMock.entries().get(1), proxiedRemoteAddress, proxiedRemotePort); Assertions.assertThat(connectionLog.logEntries()).hasSize(2); assertLogEntryHasRemote(connectionLog.logEntries().get(0), proxiedRemoteAddress, proxiedRemotePort); assertEquals("v1", connectionLog.logEntries().get(0).proxyProtocolVersion().get()); assertLogEntryHasRemote(connectionLog.logEntries().get(1), proxiedRemoteAddress, proxiedRemotePort); assertEquals("v2", connectionLog.logEntries().get(1).proxyProtocolVersion().get()); } @Test public void requireThatConnectorWithProxyProtocolMixedEnabledAcceptsBothProxyProtocolAndHttps() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); JettyTestDriver driver = createSslWithProxyProtocolTestDriver(certificateFile, privateKeyFile, requestLogMock, /*mixedMode*/connectionLog, true); String proxiedRemoteAddress = "192.168.0.100"; sendJettyClientRequest(driver, certificateFile, null); sendJettyClientRequest(driver, certificateFile, new V1.Tag(proxiedRemoteAddress, 12345)); sendJettyClientRequest(driver, certificateFile, new V2.Tag(proxiedRemoteAddress, 12345)); assertTrue(driver.close()); assertEquals(3, requestLogMock.entries().size()); assertLogEntryHasRemote(requestLogMock.entries().get(0), "127.0.0.1", 0); assertLogEntryHasRemote(requestLogMock.entries().get(1), proxiedRemoteAddress, 0); assertLogEntryHasRemote(requestLogMock.entries().get(2), proxiedRemoteAddress, 0); Assertions.assertThat(connectionLog.logEntries()).hasSize(3); assertLogEntryHasRemote(connectionLog.logEntries().get(0), null, 0); assertLogEntryHasRemote(connectionLog.logEntries().get(1), proxiedRemoteAddress, 12345); assertLogEntryHasRemote(connectionLog.logEntries().get(2), proxiedRemoteAddress, 12345); } @Test public void requireThatJdiscLocalPortPropertyIsNotOverriddenByProxyProtocol() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); JettyTestDriver driver = createSslWithProxyProtocolTestDriver(certificateFile, privateKeyFile, requestLogMock, connectionLog, /*mixedMode*/false); String proxiedRemoteAddress = "192.168.0.100"; int proxiedRemotePort = 12345; String proxyLocalAddress = "10.0.0.10"; int proxyLocalPort = 23456; V2.Tag v2Tag = new V2.Tag(V2.Tag.Command.PROXY, null, V2.Tag.Protocol.STREAM, proxiedRemoteAddress, proxiedRemotePort, proxyLocalAddress, proxyLocalPort, null); ContentResponse response = sendJettyClientRequest(driver, certificateFile, v2Tag); assertTrue(driver.close()); int clientPort = Integer.parseInt(response.getHeaders().get("Jdisc-Local-Port")); assertNotEquals(proxyLocalPort, clientPort); assertNotEquals(proxyLocalPort, connectionLog.logEntries().get(0).localPort().get().intValue()); } @Test public void requireThatConnectionIsTrackedInConnectionLog() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); Module overrideModule = binder -> binder.bind(ConnectionLog.class).toInstance(connectionLog); JettyTestDriver driver = JettyTestDriver.newInstanceWithSsl(new OkRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.NEED, overrideModule); int listenPort = driver.server().getListenPort(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 1000; i++) { builder.append(i); } byte[] content = builder.toString().getBytes(); for (int i = 0; i < 100; i++) { driver.client().newPost("/status.html").setBinaryContent(content).execute() .expectStatusCode(is(OK)); } assertTrue(driver.close()); List<ConnectionLogEntry> logEntries = connectionLog.logEntries(); Assertions.assertThat(logEntries).hasSize(1); ConnectionLogEntry logEntry = logEntries.get(0); assertEquals(4, UUID.fromString(logEntry.id()).version()); Assertions.assertThat(logEntry.timestamp()).isAfter(Instant.EPOCH); Assertions.assertThat(logEntry.requests()).hasValue(100L); Assertions.assertThat(logEntry.responses()).hasValue(100L); Assertions.assertThat(logEntry.peerAddress()).hasValue("127.0.0.1"); Assertions.assertThat(logEntry.localAddress()).hasValue("127.0.0.1"); Assertions.assertThat(logEntry.localPort()).hasValue(listenPort); Assertions.assertThat(logEntry.httpBytesReceived()).hasValueSatisfying(value -> Assertions.assertThat(value).isGreaterThan(100000L)); Assertions.assertThat(logEntry.httpBytesSent()).hasValueSatisfying(value -> Assertions.assertThat(value).isGreaterThan(10000L)); Assertions.assertThat(logEntry.sslProtocol()).hasValueSatisfying(TlsContext.ALLOWED_PROTOCOLS::contains); Assertions.assertThat(logEntry.sslPeerSubject()).hasValue("CN=localhost"); Assertions.assertThat(logEntry.sslCipherSuite()).hasValueSatisfying(cipher -> Assertions.assertThat(cipher).isNotBlank()); Assertions.assertThat(logEntry.sslSessionId()).hasValueSatisfying(sessionId -> Assertions.assertThat(sessionId).hasSize(64)); Assertions.assertThat(logEntry.sslPeerNotBefore()).hasValue(Instant.EPOCH); Assertions.assertThat(logEntry.sslPeerNotAfter()).hasValue(Instant.EPOCH.plus(100_000, ChronoUnit.DAYS)); } @Test public void requireThatRequestIsTrackedInAccessLog() throws IOException, InterruptedException { BlockingQueueRequestLog requestLogMock = new BlockingQueueRequestLog(); JettyTestDriver driver = JettyTestDriver.newConfiguredInstance( new EchoRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder(), binder -> binder.bind(RequestLog.class).toInstance(requestLogMock)); driver.client().newPost("/status.html").setContent("abcdef").execute().expectStatusCode(is(OK)); RequestLogEntry entry = requestLogMock.poll(Duration.ofSeconds(5)); Assertions.assertThat(entry.statusCode()).hasValue(200); Assertions.assertThat(entry.requestSize()).hasValue(6); assertThat(driver.close(), is(true)); } @Test public void requireThatRequestsPerConnectionMetricIsAggregated() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); JettyTestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); driver.client().get("/").expectStatusCode(is(OK)); assertThat(driver.close(), is(true)); verify(metricConsumer.mockitoMock(), atLeast(1)) .set(MetricDefinitions.REQUESTS_PER_CONNECTION, 1L, MetricConsumerMock.STATIC_CONTEXT); } private ContentResponse sendJettyClientRequest(JettyTestDriver testDriver, Path certificateFile, Object tag) throws Exception { HttpClient client = createJettyHttpClient(certificateFile); try { int maxAttempts = 3; for (int attempt = 0; attempt < maxAttempts; attempt++) { try { ContentResponse response = client.newRequest(URI.create("https://localhost:" + testDriver.server().getListenPort() + "/")) .tag(tag) .send(); assertEquals(200, response.getStatus()); return response; } catch (ExecutionException e) { // Retry when the server closes the connection before the TLS handshake is completed. This have been observed in CI. // We have been unable to reproduce this locally. The cause is therefor currently unknown. log.log(Level.WARNING, String.format("Attempt %d failed: %s", attempt, e.getMessage()), e); Thread.sleep(10); } } throw new AssertionError("Failed to send request, see log for details"); } finally { client.stop(); } } // Using Jetty's http client as Apache httpclient does not support the proxy-protocol v1/v2. private static HttpClient createJettyHttpClient(Path certificateFile) throws Exception { SslContextFactory.Client clientSslCtxFactory = new SslContextFactory.Client(); clientSslCtxFactory.setHostnameVerifier(NoopHostnameVerifier.INSTANCE); clientSslCtxFactory.setSslContext(new SslContextBuilder().withTrustStore(certificateFile).build()); HttpClient client = new HttpClient(clientSslCtxFactory); client.start(); return client; } private static CloseableHttpAsyncClient createHttp2Client(JettyTestDriver driver) { TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create() .setSslContext(driver.sslContext()) .build(); var client = H2AsyncClientBuilder.create() .disableAutomaticRetries() .setTlsStrategy(tlsStrategy) .build(); client.start(); return client; } private static void assertLogEntryHasRemote(RequestLogEntry entry, String expectedAddress, int expectedPort) { assertEquals(expectedAddress, entry.peerAddress().get()); if (expectedPort > 0) { assertEquals(expectedPort, entry.peerPort().getAsInt()); } } private static void assertLogEntryHasRemote(ConnectionLogEntry entry, String expectedAddress, int expectedPort) { if (expectedAddress != null) { Assertions.assertThat(entry.remoteAddress()).hasValue(expectedAddress); } else { Assertions.assertThat(entry.remoteAddress()).isEmpty(); } if (expectedPort > 0) { Assertions.assertThat(entry.remotePort()).hasValue(expectedPort); } else { Assertions.assertThat(entry.remotePort()).isEmpty(); } } private static void assertSslHandshakeFailurePresent( ConnectionLogEntry entry, Class<? extends SSLHandshakeException> expectedException, String expectedType) { Assertions.assertThat(entry.sslHandshakeFailure()).isPresent(); ConnectionLogEntry.SslHandshakeFailure failure = entry.sslHandshakeFailure().get(); assertEquals(expectedType, failure.type()); ExceptionEntry exceptionEntry = failure.exceptionChain().get(0); assertEquals(expectedException.getName(), exceptionEntry.name()); } private static JettyTestDriver createSslWithProxyProtocolTestDriver( Path certificateFile, Path privateKeyFile, RequestLog requestLog, ConnectionLog connectionLog, boolean mixedMode) { ConnectorConfig.Builder connectorConfig = new ConnectorConfig.Builder() .http2Enabled(true) .proxyProtocol(new ConnectorConfig.ProxyProtocol.Builder() .enabled(true) .mixedMode(mixedMode)) .ssl(new ConnectorConfig.Ssl.Builder() .enabled(true) .privateKeyFile(privateKeyFile.toString()) .certificateFile(certificateFile.toString()) .caCertificateFile(certificateFile.toString())); return JettyTestDriver.newConfiguredInstance( new EchoRequestHandler(), new ServerConfig.Builder().connectionLog(new ServerConfig.ConnectionLog.Builder().enabled(true)), connectorConfig, binder -> { binder.bind(RequestLog.class).toInstance(requestLog); binder.bind(ConnectionLog.class).toInstance(connectionLog); }); } private static JettyTestDriver createSslWithTlsClientAuthenticationEnforcer(Path certificateFile, Path privateKeyFile) { ConnectorConfig.Builder connectorConfig = new ConnectorConfig.Builder() .tlsClientAuthEnforcer( new ConnectorConfig.TlsClientAuthEnforcer.Builder() .enable(true) .pathWhitelist("/status.html")) .ssl(new ConnectorConfig.Ssl.Builder() .enabled(true) .clientAuth(ConnectorConfig.Ssl.ClientAuth.Enum.WANT_AUTH) .privateKeyFile(privateKeyFile.toString()) .certificateFile(certificateFile.toString()) .caCertificateFile(certificateFile.toString())); return JettyTestDriver.newConfiguredInstance( new EchoRequestHandler(), new ServerConfig.Builder().connectionLog(new ServerConfig.ConnectionLog.Builder().enabled(true)), connectorConfig, binder -> {}); } private static JettyTestDriver createSslTestDriver( Path serverCertificateFile, Path serverPrivateKeyFile, MetricConsumerMock metricConsumer, InMemoryConnectionLog connectionLog) throws IOException { Module extraModule = binder -> { binder.bind(MetricConsumer.class).toInstance(metricConsumer.mockitoMock()); binder.bind(ConnectionLog.class).toInstance(connectionLog); }; return JettyTestDriver.newInstanceWithSsl( new EchoRequestHandler(), serverCertificateFile, serverPrivateKeyFile, TlsClientAuth.NEED, extraModule); } private static void assertHttpsRequestTriggersSslHandshakeException( JettyTestDriver testDriver, SSLContext sslContext, String protocolOverride, String cipherOverride, String expectedExceptionSubstring) throws IOException { List<String> protocols = protocolOverride != null ? List.of(protocolOverride) : null; List<String> ciphers = cipherOverride != null ? List.of(cipherOverride) : null; try (var client = new SimpleHttpClient(sslContext, protocols, ciphers, testDriver.server().getListenPort(), false)) { client.get("/status.html"); fail("SSLHandshakeException expected"); } catch (SSLHandshakeException e) { assertThat(e.getMessage(), containsString(expectedExceptionSubstring)); } catch (SSLException e) { // This exception is thrown if Apache httpclient's write thread detects the handshake failure before the read thread. log.log(Level.WARNING, "Client failed to get a proper TLS handshake response: " + e.getMessage(), e); // Only ignore a subset of exceptions assertThat(e.getMessage(), anyOf(containsString("readHandshakeRecord"), containsString("Broken pipe"))); } } private static void generatePrivateKeyAndCertificate(Path privateKeyFile, Path certificateFile) throws IOException { KeyPair keyPair = KeyUtils.generateKeypair(EC); Files.writeString(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate())); X509Certificate certificate = X509CertificateBuilder .fromKeypair( keyPair, new X500Principal("CN=localhost"), Instant.EPOCH, Instant.EPOCH.plus(100_000, ChronoUnit.DAYS), SHA256_WITH_ECDSA, BigInteger.ONE) .build(); Files.writeString(certificateFile, X509CertificateUtils.toPem(certificate)); } private static void generatePrivateKeyAndCertificate(Path rootPrivateKeyFile, Path rootCertificateFile, Path privateKeyFile, Path certificateFile, Instant notAfter) throws IOException { generatePrivateKeyAndCertificate(rootPrivateKeyFile, rootCertificateFile); X509Certificate rootCertificate = X509CertificateUtils.fromPem(Files.readString(rootCertificateFile)); PrivateKey privateKey = KeyUtils.fromPemEncodedPrivateKey(Files.readString(rootPrivateKeyFile)); KeyPair keyPair = KeyUtils.generateKeypair(EC); Files.writeString(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate())); Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(new X500Principal("CN=myclient"), keyPair, SHA256_WITH_ECDSA).build(); X509Certificate certificate = X509CertificateBuilder .fromCsr(csr, rootCertificate.getSubjectX500Principal(), Instant.EPOCH, notAfter, privateKey, SHA256_WITH_ECDSA, BigInteger.ONE) .build(); Files.writeString(certificateFile, X509CertificateUtils.toPem(certificate)); } private static RequestHandler mockRequestHandler() { final RequestHandler mockRequestHandler = mock(RequestHandler.class); when(mockRequestHandler.refer()).thenReturn(References.NOOP_REFERENCE); return mockRequestHandler; } private static String generateContent(final char c, final int len) { final StringBuilder ret = new StringBuilder(len); for (int i = 0; i < len; ++i) { ret.append(c); } return ret.toString(); } private static JettyTestDriver newDriverWithFormPostContentRemoved(RequestHandler requestHandler, boolean removeFormPostBody) throws Exception { return JettyTestDriver.newConfiguredInstance( requestHandler, new ServerConfig.Builder() .removeRawPostBodyForWwwUrlEncodedPost(removeFormPostBody), new ConnectorConfig.Builder()); } private static FormBodyPart newFileBody(final String fileName, final String fileContent) { return FormBodyPartBuilder.create() .setBody( new StringBody(fileContent, ContentType.TEXT_PLAIN) { @Override public String getFilename() { return fileName; } @Override public String getMimeType() { return ""; } @Override public String getCharset() { return null; } }) .setName(fileName) .build(); } private static class ConnectedAtRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final HttpRequest httpRequest = (HttpRequest)request; final String connectedAt = String.valueOf(httpRequest.getConnectedAt(TimeUnit.MILLISECONDS)); final ContentChannel ch = handler.handleResponse(new Response(OK)); ch.write(ByteBuffer.wrap(connectedAt.getBytes(StandardCharsets.UTF_8)), null); ch.close(null); return null; } } private static class CookieSetterRequestHandler extends AbstractRequestHandler { final Cookie cookie; CookieSetterRequestHandler(final Cookie cookie) { this.cookie = cookie; } @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final HttpResponse response = HttpResponse.newInstance(OK); response.encodeSetCookieHeader(Collections.singletonList(cookie)); ResponseDispatch.newInstance(response).dispatch(handler); return null; } } private static class CookiePrinterRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final List<Cookie> cookies = new ArrayList<>(((HttpRequest)request).decodeCookieHeader()); Collections.sort(cookies, new CookieComparator()); final ContentChannel out = ResponseDispatch.newInstance(Response.Status.OK).connect(handler); out.write(StandardCharsets.UTF_8.encode(cookies.toString()), null); out.close(null); return null; } } private static class ParameterPrinterRequestHandler extends AbstractRequestHandler { private static final CompletionHandler NULL_COMPLETION_HANDLER = null; @Override public ContentChannel handleRequest(Request request, ResponseHandler handler) { Map<String, List<String>> parameters = new TreeMap<>(((HttpRequest)request).parameters()); ContentChannel responseContentChannel = ResponseDispatch.newInstance(Response.Status.OK).connect(handler); responseContentChannel.write(ByteBuffer.wrap(parameters.toString().getBytes(StandardCharsets.UTF_8)), NULL_COMPLETION_HANDLER); // Have the request content written back to the response. return responseContentChannel; } } private static class RequestTypeHandler extends AbstractRequestHandler { private Request.RequestType requestType = null; public void setRequestType(Request.RequestType requestType) { this.requestType = requestType; } @Override public ContentChannel handleRequest(Request request, ResponseHandler handler) { Response response = new Response(OK); response.setRequestType(requestType); return handler.handleResponse(response); } } private static class ThrowingHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { throw new RuntimeException("Deliberately thrown exception"); } } private static class UnresponsiveHandler extends AbstractRequestHandler { ResponseHandler responseHandler; @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { request.setTimeout(100, TimeUnit.MILLISECONDS); responseHandler = handler; return null; } } private static class EchoRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { int port = request.getUri().getPort(); Response response = new Response(OK); response.headers().put("Jdisc-Local-Port", Integer.toString(port)); return handler.handleResponse(response); } } private static class OkRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(Request request, ResponseHandler handler) { Response response = new Response(OK); handler.handleResponse(response).close(null); return NullContent.INSTANCE; } } private static class EchoWithHeaderRequestHandler extends AbstractRequestHandler { final String headerName; final String headerValue; EchoWithHeaderRequestHandler(final String headerName, final String headerValue) { this.headerName = headerName; this.headerValue = headerValue; } @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final Response response = new Response(OK); response.headers().add(headerName, headerValue); return handler.handleResponse(response); } } private static Module newBindingSetSelector(final String setName) { return new AbstractModule() { @Override protected void configure() { bind(BindingSetSelector.class).toInstance(new BindingSetSelector() { @Override public String select(final URI uri) { return setName; } }); } }; } private static class CookieComparator implements Comparator<Cookie> { @Override public int compare(final Cookie lhs, final Cookie rhs) { return lhs.getName().compareTo(rhs.getName()); } } }
package de.tudresden.inf.lat.born.problog.connector; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import de.tudresden.inf.lat.born.core.term.ProbClause; import de.tudresden.inf.lat.born.core.term.ProbClauseImpl; import de.tudresden.inf.lat.born.core.term.Term; import de.tudresden.inf.lat.born.core.term.TermImpl; /** * An object of this class creates a Bayesian network using randomized values. * * @author Julian Mendez * */ public class BayesianNetworkCreatorCore { public static final String VARIABLE_PREFIX = "x"; public static final String NEGATION_PREFIX = "\\+"; public static final int PRECISION = 2; public static final int PRECISION_PLUS_2 = PRECISION + 2; public BayesianNetworkCreatorCore() { } Term newTerm(int variableIndex, boolean isNegative) { return new TermImpl((isNegative ? NEGATION_PREFIX : "") + VARIABLE_PREFIX + variableIndex); } List<Integer> chooseDependencies(int variableIndex, int parents) { if ((variableIndex < 0) || (parents < 0) || (parents > variableIndex)) { throw new IllegalArgumentException("It is not possible to create dependencies for " + VARIABLE_PREFIX + variableIndex + " with " + parents + " parents."); } Stream<Integer> chosen = IntStream.range(0, parents).mapToObj(x -> ((int) (Math.random() * variableIndex))) .distinct(); Stream<Integer> remaining = IntStream.range((int) chosen.count(), parents).mapToObj(x -> x); List<Integer> ret = Stream.concat(chosen, remaining).collect(Collectors.toList()); return ret; } ProbClause renderClause(int variableIndex, List<Integer> dependencies, List<Boolean> permutation, double probability) { if (dependencies.size() != permutation.size()) { throw new IllegalArgumentException("It is not possible to create a probabilistic clause with these values:" + " variable index '" + variableIndex + "' with dependencies '" + dependencies + "' with state '" + permutation + "'."); } Term head = newTerm(variableIndex, false); List<Term> body = new ArrayList<>(); for (int index = 0; (index < dependencies.size()); index++) { int dependencyIndex = dependencies.get(index); boolean isNegative = permutation.get(index); body.add(newTerm(dependencyIndex, isNegative)); } ProbClause ret = new ProbClauseImpl(head, body, asAnnotation(probability)); return ret; } String asAnnotation(double probability) { String ret = "" + probability; if (ret.length() > PRECISION_PLUS_2) { ret = ret.substring(0, PRECISION_PLUS_2); } return ret; } List<ProbClause> computeDependencies(int variableIndex, int parents) { List<ProbClause> ret = new ArrayList<>(); List<Integer> dependencies = chooseDependencies(variableIndex, parents); boolean valid = true; for (Permutation permutation = new Permutation(parents); valid; valid = permutation.computeNextPermutation()) { double probability = Math.random(); ret.add(renderClause(variableIndex, dependencies, permutation.getPermutation(), probability)); } return ret; } public List<ProbClause> createNetwork(List<Integer> variables) { List<ProbClause> ret = new ArrayList<>(); int variableIndex = 0; for (int parents = 0; parents < variables.size(); parents++) { int n = variables.get(parents); for (int currVar = 0; currVar < n; currVar++) { List<ProbClause> current = computeDependencies(variableIndex, parents); ret.addAll(current); variableIndex++; } } return ret; } public void write(Writer writer, List<ProbClause> network) throws IOException { BufferedWriter output = new BufferedWriter(writer); for (ProbClause clause : network) { output.append(clause.asString()); output.newLine(); } output.flush(); } public void run(BayesianNetworkCreatorConfiguration conf) { try { List<ProbClause> network = createNetwork(conf.getDependencies()); write(new OutputStreamWriter(conf.getOutput()), network); } catch (IOException e) { throw new RuntimeException(e); } } }
package org.pescuma.buildhealth.analyser.staticanalysis; import static java.util.Arrays.*; import static org.pescuma.buildhealth.analyser.BuildStatusHelper.*; import static org.pescuma.buildhealth.analyser.NumbersFormater.*; import static org.pescuma.buildhealth.analyser.utils.BuildHealthAnalyserUtils.*; import static org.pescuma.buildhealth.core.BuildHealth.ReportFlags.*; import static org.pescuma.buildhealth.core.prefs.BuildHealthPreference.*; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.Map; import org.kohsuke.MetaInfServices; import org.pescuma.buildhealth.analyser.BuildHealthAnalyser; import org.pescuma.buildhealth.analyser.utils.BuildHealthAnalyserUtils.TreeStats; import org.pescuma.buildhealth.analyser.utils.SimpleTree; import org.pescuma.buildhealth.core.BuildData; import org.pescuma.buildhealth.core.BuildData.Line; import org.pescuma.buildhealth.core.BuildStatus; import org.pescuma.buildhealth.core.Report; import org.pescuma.buildhealth.core.prefs.BuildHealthPreference; import org.pescuma.buildhealth.prefs.Preferences; import com.google.common.base.Function; @MetaInfServices public class StaticAnalysisAnalyser implements BuildHealthAnalyser { public static final int COLUMN_LANGUAGE = 1; public static final int COLUMN_FRAMEWORK = 2; public static final int COLUMN_FILE = 3; public static final int COLUMN_LINE = 4; public static final int COLUMN_CATEGORY = 5; public static final int COLUMN_MESSAGE = 6; public static final int COLUMN_SEVERITY = 7; public static final int COLUMN_DETAILS = 8; public static final int COLUMN_URL = 9; @Override public String getName() { return "Static analysis"; } @Override public int getPriority() { return 300; } @Override public List<BuildHealthPreference> getPreferences() { List<BuildHealthPreference> result = new ArrayList<BuildHealthPreference>(); result.add(new BuildHealthPreference("Maximun munber of violations for a Good build", "<no limit>", "staticanalysis", "good")); result.add(new BuildHealthPreference("Maximun munber of violations for a So So build", "<no limit>", "staticanalysis", "warn")); result.add(new BuildHealthPreference("Maximun munber of violations for a Good build", "<no limit>", "staticanalysis", ANY_VALUE_KEY_PREFIX + "<language>", "good")); result.add(new BuildHealthPreference("Maximun munber of violations for a So So build", "<no limit>", "staticanalysis", ANY_VALUE_KEY_PREFIX + "<language>", "warn")); result.add(new BuildHealthPreference("Maximun munber of violations for a Good build", "<no limit>", "staticanalysis", ANY_VALUE_KEY_PREFIX + "<language>", ANY_VALUE_KEY_PREFIX + "<framework>", "good")); result.add(new BuildHealthPreference("Maximun munber of violations for a So So build", "<no limit>", "staticanalysis", ANY_VALUE_KEY_PREFIX + "<language>", ANY_VALUE_KEY_PREFIX + "<framework>", "warn")); return Collections.unmodifiableList(result); } @Override public List<Report> computeReport(BuildData data, Preferences prefs, int opts) { data = data.filter("Static analysis"); if (data.isEmpty()) return Collections.emptyList(); prefs = prefs.child("staticanalysis"); boolean highlighProblems = (opts & HighlightProblems) != 0; boolean summaryOnly = (opts & SummaryOnly) != 0; SimpleTree<Stats> tree = buildTree(data); sumChildStatsAndComputeBuildStatuses(tree, prefs); if (summaryOnly) removeNonSummaryNodes(tree, highlighProblems); return asList(toReport(tree.getRoot(), getName(), prefs, highlighProblems, 2)); } private SimpleTree<Stats> buildTree(BuildData data) { SimpleTree<Stats> tree = new SimpleTree<Stats>(new Function<String[], Stats>() { @Override public Stats apply(String[] name) { return new Stats(name); } }); for (Line line : data.getLines()) { SimpleTree<Stats>.Node node = tree.getRoot(); node = node.getChild(line.getColumn(COLUMN_LANGUAGE)); node = node.getChild(line.getColumn(COLUMN_FRAMEWORK)); String category = line.getColumn(COLUMN_CATEGORY); if (!category.isEmpty()) node = node.getChild(category); Stats stats = node.getData(); stats.add(line); } return tree; } private void sumChildStatsAndComputeBuildStatuses(SimpleTree<Stats> tree, final Preferences prefs) { tree.visit(new SimpleTree.Visitor<Stats>() { Deque<Stats> parents = new ArrayDeque<Stats>(); @Override public void preVisitNode(SimpleTree<Stats>.Node node) { parents.push(node.getData()); } @Override public void posVisitNode(SimpleTree<Stats>.Node node) { parents.pop(); Stats stats = node.getData(); stats.computeStatus(prefs); if (!parents.isEmpty()) parents.peekFirst().addChild(stats); } }); } private Report toReport(SimpleTree<Stats>.Node node, String name, Preferences prefs, boolean highlighProblems, int showAllFrameworks) { Stats stats = node.getData(); List<Report> children = new ArrayList<Report>(); children.addAll(toViolations(stats)); for (SimpleTree<Stats>.Node child : sort(node.getChildren(), highlighProblems)) children.add(toReport(child, child.getName(), prefs, highlighProblems, showAllFrameworks - 1)); String description = ""; if (showAllFrameworks > 0) description = toDescription(stats); return new Report(node.isRoot() ? stats.getStatusWithChildren() : stats.getOwnStatus(), name, format1000(stats.getTotal()), description, children); } private String toDescription(Stats stats) { List<Framework> fs = new ArrayList<Framework>(stats.frameworks.values()); Collections.sort(fs, new Comparator<Framework>() { @Override public int compare(Framework o1, Framework o2) { int cmp = o1.language.compareToIgnoreCase(o2.language); if (cmp != 0) return cmp; return o1.framework.compareToIgnoreCase(o2.framework); } }); StringBuilder result = new StringBuilder(); int languages = countLanguages(fs); String oldLanguage = ""; for (Framework f : fs) { if (languages > 1 && !oldLanguage.equals(f.language)) { oldLanguage = f.language; if (result.length() > 0) result.append("; "); result.append(f.language).append(": "); } else { if (result.length() > 0) result.append(", "); } result.append(f.framework).append(": ").append(format1000(f.total)); } return result.toString(); } private int countLanguages(List<Framework> fs) { String oldLanguage = null; int languages = 0; for (Framework f : fs) { if (oldLanguage == null || !oldLanguage.equals(f.language)) { languages++; oldLanguage = f.language; } } return languages; } private List<StaticAnalysisViolation> toViolations(Stats stats) { List<StaticAnalysisViolation> violations = new ArrayList<StaticAnalysisViolation>(); for (Line line : stats.violations) violations.add(toViolation(line)); Collections.sort(violations, new Comparator<StaticAnalysisViolation>() { @Override public int compare(StaticAnalysisViolation o1, StaticAnalysisViolation o2) { int cmp = o1.getFilename().compareToIgnoreCase(o2.getFilename()); if (cmp != 0) return cmp; cmp = o1.getLine().compareToIgnoreCase(o2.getLine()); if (cmp != 0) return cmp; return o1.getMessage().compareToIgnoreCase(o2.getMessage()); } }); return violations; } private StaticAnalysisViolation toViolation(Line line) { String language = line.getColumn(COLUMN_LANGUAGE); String framework = line.getColumn(COLUMN_FRAMEWORK); String filename = line.getColumn(COLUMN_FILE); String fileLine = line.getColumn(COLUMN_LINE); String category = line.getColumn(COLUMN_CATEGORY); String message = line.getColumn(COLUMN_MESSAGE); String severity = line.getColumn(COLUMN_SEVERITY); String details = line.getColumn(COLUMN_DETAILS); String url = line.getColumn(COLUMN_URL); return new StaticAnalysisViolation(BuildStatus.Good, language, framework, filename, fileLine, category, message, severity, details, url); } private static class Stats extends TreeStats { final List<Line> violations = new ArrayList<Line>(); final Map<String, Framework> frameworks = new HashMap<String, Framework>(); Stats(String[] name) { super(name); } void add(Line line) { getFramework(line.getColumn(COLUMN_LANGUAGE), line.getColumn(COLUMN_FRAMEWORK)).total += line.getValue(); if (!line.getColumn(COLUMN_FILE).isEmpty()) violations.add(line); } void addChild(Stats stats) { for (Framework framework : stats.frameworks.values()) getFramework(framework.language, framework.framework).total += framework.total; mergeChildStatus(stats); } void computeStatus(Preferences prefs) { BuildStatus status = computeStatusFromThresholdIfExists(prefs.child(getNames()), getTotal(), false); if (status != null) setOwnStatus(status); } double getTotal() { double total = 0; for (Framework framework : frameworks.values()) total += framework.total; return total; } Framework getFramework(String language, String framework) { String key = language + "\n" + framework; Framework result = frameworks.get(key); if (result == null) { result = new Framework(language, framework); frameworks.put(key, result); } return result; } } private static class Framework { final String language; final String framework; double total = 0; Framework(String language, String framwork) { this.language = language; this.framework = framwork; } } }
package org.jboss.as.controller.test; import java.util.concurrent.CancellationException; import org.jboss.as.controller.ModelController; import org.jboss.as.controller.OperationResult; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.ProxyController; import org.jboss.as.controller.ResultHandler; import org.jboss.as.controller.client.Operation; import org.jboss.dmr.ModelNode; import org.junit.Before; import org.junit.Ignore; /** * * @author <a href="kabir.khan@jboss.com">Kabir Khan</a> * @version $Revision: 1.1 $ */ @Ignore("Pending Kabir's proxy controller work") public class ProxyControllerTestCase extends AbstractProxyControllerTest { @Before public void start() throws Exception { setupNodes(); } @Override protected ProxyController createProxyController(final ModelController proxiedController, final PathAddress proxyNodeAddress) { return new TestProxyController(proxiedController, proxyNodeAddress); } static class TestProxyController implements ProxyController { private final ModelController targetController; private final PathAddress proxyNodeAddress; public TestProxyController(final ModelController targetController, final PathAddress proxyNodeAddress) { this.targetController = targetController; this.proxyNodeAddress = proxyNodeAddress; } @Override public PathAddress getProxyNodeAddress() { return proxyNodeAddress; } @Override public OperationResult execute(final Operation operation, final ResultHandler resultHandler) { return targetController.execute(operation, resultHandler); } @Override public ModelNode execute(final Operation operation) throws CancellationException { return targetController.execute(operation); } } }
package org.jscsi.target.task; import java.io.File; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jscsi.target.conf.target.TargetConfiguration; import org.jscsi.target.task.abstracts.AbstractState; import org.jscsi.target.task.abstracts.AbstractTask; import org.jscsi.target.task.abstracts.AbstractTaskDescriptor; import org.jscsi.target.task.abstracts.AbstractTextOperation; import org.jscsi.target.task.abstracts.AbstractTextOperationDescriptor; import org.jscsi.target.task.abstracts.AbstractTextOperationState; import org.jscsi.target.task.abstracts.State; import org.jscsi.target.task.abstracts.Task; import org.jscsi.target.task.abstracts.TaskDescriptor; import org.jscsi.target.util.CreativeClassLoader; import org.jscsi.target.util.Singleton; public class TargetTaskLibrary { /** The Log interface. */ private static final Log LOGGER = LogFactory.getLog(TargetTaskLoader.class); /** A Set of TaskDescriptors mapped by their opcodes * */ private static final Map<String, Class<? extends AbstractTaskDescriptor>> loadedTaskDescriptors = new ConcurrentHashMap<String, Class<? extends AbstractTaskDescriptor>>(); private static final Map<String, Class<? extends AbstractTextOperationDescriptor>> loadedTextOperationDescriptors = new ConcurrentHashMap<String, Class<? extends AbstractTextOperationDescriptor>>(); private static final Map<String, Class<? extends AbstractTextOperation>> loadedTextOperations = new ConcurrentHashMap<String, Class<? extends AbstractTextOperation>>(); private static final Map<String, Class<? extends AbstractTextOperationState>> loadedTextOperationState = new ConcurrentHashMap<String, Class<? extends AbstractTextOperationState>>(); private static final Map<String, Class<? extends AbstractTask>> loadedTasks = new ConcurrentHashMap<String, Class<? extends AbstractTask>>(); private static final Map<String, Class<? extends AbstractState>> loadedStates = new ConcurrentHashMap<String, Class<? extends AbstractState>>(); private static final CreativeClassLoader classLoader = CreativeClassLoader .getInstance(); private TargetTaskLibrary() { } private TargetTaskLibrary(TargetConfiguration conf) { loadFrom(conf); } /** * Creates a TaskObject * * @param initialPDU * @param callingConnection * @return * @throws Exception */ /* * public Task createTask(ProtocolDataUnit initialPDU, Connection * callingConnection) throws Exception { byte opcode = * initialPDU.getBasicHeaderSegment().getOpCode().value(); for * (TaskDescriptor matchingDescriptor : getTaskDescriptors(opcode)) { if * (matchingDescriptor != null) { if * (matchingDescriptor.check(callingConnection, initialPDU)) { return * matchingDescriptor.createTask(); } } } logDebug("Unsupported Opcode * arrived: Opcode = " + opcode); throw new Exception("Couldn't find a * matching Task: Opcode = " + opcode); } * * public final TaskDescriptor getTaskDescriptor(String name) { for (Set<TaskDescriptor> * oneSet : loadedTaskDescriptors.values()) { for (TaskDescriptor taskD : * oneSet) { if (taskD.getClass().getName().equals(name)) { return taskD; } } } * logTrace("Couldn't find TaskDescriptor: " + name); return null; } * * public final Set<TaskDescriptor> getTaskDescriptors(byte opcode) { * return loadedTaskDescriptors.get(opcode); } */ public final Task createTask(String name) { Task newTask = null; try { newTask = getTask(name).newInstance(); } catch (Exception e) { } return newTask; } public final State createState(String name) { State newState = null; try { newState = getState(name).newInstance(); } catch (Exception e) { } return newState; } public final Class<? extends TaskDescriptor> getTaskDescriptor(String name) { return loadedTaskDescriptors.get(name); } public final Class<? extends AbstractTask> getTask(String name) { return loadedTasks.get(name); } public final Class<? extends AbstractState> getState(String name) { return loadedStates.get(name); } public int getNumberOfSupportedOpcodes() { return loadedTaskDescriptors.keySet().size(); } public int getNumberOfAvailableTasks() { return loadedTasks.keySet().size(); } public int getNumberOfAvailableTaskDescriptors() { return loadedTaskDescriptors.keySet().size(); } public int getNumberOfAvailableStates() { return loadedStates.keySet().size(); } public String getInfo() { StringBuffer result = new StringBuffer(); result.append("TaskLibrary is supporting "); result.append(getNumberOfSupportedOpcodes()); result.append(" different Opcodes ("); for(Class<? extends AbstractTaskDescriptor> desc : loadedTaskDescriptors.values()){ boolean error = false; TaskDescriptor descInst = null; try { descInst = desc.newInstance(); } catch (InstantiationException e) { error = true; } catch (IllegalAccessException e) { error = true; } if(!error){ result.append(descInst.getSupportedOpcode().value() + ", "); } } result.delete(result.length() - 2, result.length()); result.append(") "); result.append("and loaded: "); result.append(getNumberOfAvailableTaskDescriptors() + " TaskDescriptors;"); result.append(getNumberOfAvailableTasks() + " Tasks;"); result.append(getNumberOfAvailableStates() + " States;"); return result.toString(); } /* * public void addTaskDescriptor(TaskDescriptor descriptor) throws * ConflictedTaskException { byte opcode = * descriptor.getSupportedOpcode().value(); // check if a descriptor yet * exists, that has identical parameter if * (loadedTaskDescriptors.containsKey(opcode)) { for (TaskDescriptor * equalOpcode : loadedTaskDescriptors.get(opcode)) { if * (equalOpcode.compare((AbstractTaskDescriptor) descriptor)) { throw new * ConflictedTaskException( "Tried to load a TaskDescriptor that would * conflict with an already existing one: " + * descriptor.getClass().getName() + " and " + * equalOpcode.getClass().getName()); } } } // no collision, add * TaskDescriptor to library if (loadedTaskDescriptors.get(opcode) != null) { * loadedTaskDescriptors.get(opcode).add(descriptor); } Set<TaskDescriptor> * newSet = new HashSet<TaskDescriptor>(); newSet.add(descriptor); * loadedTaskDescriptors.put(opcode, newSet); } */ public Class<? extends AbstractTaskDescriptor> addTaskDescriptor( Class<? extends AbstractTaskDescriptor> newTaskDescriptor) { return addObject(newTaskDescriptor, loadedTaskDescriptors, AbstractTaskDescriptor.class); } public Class<? extends AbstractTask> addTask( Class<? extends AbstractTask> newTaskClass) { return addObject(newTaskClass, loadedTasks, AbstractTask.class); } /** * Adds a new instance from given object as value to the given map, using * the object's name as key. type is used to restrict map's value and object * to a given superclass. * * @param <T> * Both given object and map's value must have T as superclass * @param object * the object that will be added to the map. object's name will * be used as maps key * @param map * object's name and object will be added to the map * @param type * Both given object and map's value must have T as superclass * @return */ public static <T> Class<T> addObject(Class<? extends T> object, Map<String, Class<? extends T>> map, Class<T> type) { boolean valid = true; String error = null; // already added Task ? if (map.containsKey(object.getClass().getName())) { valid = false; error = "Tried to add an already existing entity: " + object.getName(); } // if no instance can be created -> error try { object.newInstance(); } catch (Exception e) { valid = false; error = "Cannot create an instance from " + object.getName(); } // everything ok if (valid) { if (type.equals(AbstractTaskDescriptor.class)) { logTrace("Added new TaskDescriptor: " + object.getName()); } else { if (type.equals(AbstractTask.class)) { logTrace("Added new Task: " + object.getName()); } else { if (type.equals(AbstractState.class)) { logTrace("Added new State: " + object.getName()); } else { if (type.equals(AbstractTextOperationDescriptor.class)) { logTrace("Added new TextOperationDescriptor: " + object.getName()); } else { if (type.equals(AbstractTextOperation.class)) { logTrace("Added new TextOperation: " + object.getName()); } else { if (type .equals(AbstractTextOperationState.class)) { logTrace("Added new TaskOperationState: " + object.getName()); } else { logTrace("Added new \"whatever unknown entity\": " + object.getName()); } } } } } } return (Class<T>) map.put(object.getName(), object); } // error occurred, log error and return null logDebug(error); return null; } public Class<? extends AbstractState> addState( Class<? extends AbstractState> newState) { return addObject(newState, loadedStates, AbstractState.class); } public static TargetTaskLibrary getInstance() { if (!Singleton.hasInstance(TargetTaskLibrary.class)) { Singleton.setInstance(new TargetTaskLibrary()); } TargetTaskLibrary instance = null; try { instance = Singleton.getInstance(TargetTaskLibrary.class); } catch (ClassNotFoundException e) { throw new Error("Couldn't load instance of " + TargetTaskLibrary.class); } return instance; } public void loadFrom(TargetConfiguration conf) { for (File file : conf.getTaskDescriptorDirectories()) { Set<Class<? extends AbstractTaskDescriptor>> loadedTaskDescriptor = classLoader .loadAllClassesHavingSuperclass(null, file, true, AbstractTaskDescriptor.class); for (Class<? extends AbstractTaskDescriptor> loadedDescriptor : loadedTaskDescriptor) { addTaskDescriptor(loadedDescriptor); } Set<Class<? extends AbstractTask>> loadedClasses = classLoader .loadAllClassesHavingSuperclass(null, file, true, AbstractTask.class); for (Class<? extends AbstractTask> loadedTask : loadedClasses) { addTask(loadedTask); } Set<Class<? extends AbstractState>> loadedStates = classLoader .loadAllClassesHavingSuperclass(null, file, true, AbstractState.class); for (Class<? extends AbstractState> loadedState : loadedStates) { addState(loadedState); } } logTrace(getInfo()); } /** * Logs a trace Message, if trace log is enabled within the logging * environment. * * @param logMessage */ private static void logTrace(String logMessage) { if (LOGGER.isTraceEnabled()) { LOGGER.trace(" Message: " + logMessage); } } /** * Logs a debug Message, if debug log is enabled within the logging * environment. * * @param logMessage */ private static void logDebug(String logMessage) { if (LOGGER.isDebugEnabled()) { LOGGER.trace(" Message: " + logMessage); } } }
// $ANTLR 3.4 C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g 2017-11-21 09:15:55 package se.raddo.raddose3D.parser; import se.raddo.raddose3D.*; import java.util.Vector; import java.util.HashMap; import java.util.Map; import org.antlr.runtime.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; /** "Here's an initializer, here's an input file. Good luck and God's Speed." */ @SuppressWarnings({"all", "warnings", "unchecked"}) public class InputfileParser extends Parser { public static final String[] tokenNames = new String[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "ABSCOEFCALC", "ANGLEL", "ANGLEP", "ANGULARRESOLUTION", "AVERAGE", "BEAM", "CALCULATEFLESCAPE", "CALCULATEPEESCAPE", "CIRCULAR", "COLLIMATION", "COMMENT", "CONTAINERDENSITY", "CONTAINERMATERIALELEMENTS", "CONTAINERMATERIALMIXTURE", "CONTAINERMATERIALTYPE", "CONTAINERTHICKNESS", "CRYSTAL", "DDM", "DECAYPARAM", "DEFAULT", "DIFFRACTIONDECAYMODEL", "DIMENSION", "DUMMY", "ELEMENT", "ELEMENTAL", "ENERGY", "EXPONENT", "EXPOSURETIME", "FILE", "FLOAT", "FLRESOLUTION", "FLUX", "FWHM", "HORIZONTAL", "KEV", "LEAL", "LINEAR", "MATERIALELEMENTS", "MATERIALMIXTURE", "MATERIALTYPE", "MIXTURE", "MODELFILE", "NONE", "NUMDNA", "NUMMONOMERS", "NUMRESIDUES", "NUMRNA", "PDB", "PDBNAME", "PERESOLUTION", "PIXELSIZE", "PIXELSPERMICRON", "PROTEINCONC", "PROTEINCONCENTRATION", "PROTEINHEAVYATOMS", "RDFORTAN", "RDJAVA", "RECTANGULAR", "ROTAXBEAMOFFSET", "SAXS", "SAXSSEQ", "SEQFILE", "SEQUENCE", "SEQUENCEFILE", "SIMPLE", "SOLVENTFRACTION", "SOLVENTHEAVYCONC", "STARTOFFSET", "STRING", "TRANSLATEPERDEGREE", "TYPE", "UNITCELL", "VERTICAL", "WEDGE", "WIREFRAMETYPE", "WS" }; public static final int EOF=-1; public static final int ABSCOEFCALC=4; public static final int ANGLEL=5; public static final int ANGLEP=6; public static final int ANGULARRESOLUTION=7; public static final int AVERAGE=8; public static final int BEAM=9; public static final int CALCULATEFLESCAPE=10; public static final int CALCULATEPEESCAPE=11; public static final int CIRCULAR=12; public static final int COLLIMATION=13; public static final int COMMENT=14; public static final int CONTAINERDENSITY=15; public static final int CONTAINERMATERIALELEMENTS=16; public static final int CONTAINERMATERIALMIXTURE=17; public static final int CONTAINERMATERIALTYPE=18; public static final int CONTAINERTHICKNESS=19; public static final int CRYSTAL=20; public static final int DDM=21; public static final int DECAYPARAM=22; public static final int DEFAULT=23; public static final int DIFFRACTIONDECAYMODEL=24; public static final int DIMENSION=25; public static final int DUMMY=26; public static final int ELEMENT=27; public static final int ELEMENTAL=28; public static final int ENERGY=29; public static final int EXPONENT=30; public static final int EXPOSURETIME=31; public static final int FILE=32; public static final int FLOAT=33; public static final int FLRESOLUTION=34; public static final int FLUX=35; public static final int FWHM=36; public static final int HORIZONTAL=37; public static final int KEV=38; public static final int LEAL=39; public static final int LINEAR=40; public static final int MATERIALELEMENTS=41; public static final int MATERIALMIXTURE=42; public static final int MATERIALTYPE=43; public static final int MIXTURE=44; public static final int MODELFILE=45; public static final int NONE=46; public static final int NUMDNA=47; public static final int NUMMONOMERS=48; public static final int NUMRESIDUES=49; public static final int NUMRNA=50; public static final int PDB=51; public static final int PDBNAME=52; public static final int PERESOLUTION=53; public static final int PIXELSIZE=54; public static final int PIXELSPERMICRON=55; public static final int PROTEINCONC=56; public static final int PROTEINCONCENTRATION=57; public static final int PROTEINHEAVYATOMS=58; public static final int RDFORTAN=59; public static final int RDJAVA=60; public static final int RECTANGULAR=61; public static final int ROTAXBEAMOFFSET=62; public static final int SAXS=63; public static final int SAXSSEQ=64; public static final int SEQFILE=65; public static final int SEQUENCE=66; public static final int SEQUENCEFILE=67; public static final int SIMPLE=68; public static final int SOLVENTFRACTION=69; public static final int SOLVENTHEAVYCONC=70; public static final int STARTOFFSET=71; public static final int STRING=72; public static final int TRANSLATEPERDEGREE=73; public static final int TYPE=74; public static final int UNITCELL=75; public static final int VERTICAL=76; public static final int WEDGE=77; public static final int WIREFRAMETYPE=78; public static final int WS=79; // delegates public Parser[] getDelegates() { return new Parser[] {}; } // delegators public InputfileParser(TokenStream input) { this(input, new RecognizerSharedState()); } public InputfileParser(TokenStream input, RecognizerSharedState state) { super(input, state); } public String[] getTokenNames() { return InputfileParser.tokenNames; } public String getGrammarFileName() { return "C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g"; } private BeamFactory beamFactory = null; private CrystalFactory crystalFactory = null; private Initializer raddoseInitializer = null; private Vector<String> parsingErrors = new Vector<String>(); public void setInitializer(Initializer i) { this.raddoseInitializer = i; } public void setBeamFactory(BeamFactory bf) { this.beamFactory = bf; } public void setCrystalFactory(CrystalFactory cf) { this.crystalFactory = cf; } public Vector<String> getErrors() { Vector<String> fetchedErrors = parsingErrors; parsingErrors = new Vector<String>(); return fetchedErrors; } public void emitErrorMessage(String msg) { parsingErrors.add(msg); } // $ANTLR start "configfile" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:41:1: configfile : (a= crystal |b= wedge |c= beam )* EOF ; public final void configfile() throws RecognitionException { Crystal a =null; Wedge b =null; Beam c =null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:41:11: ( (a= crystal |b= wedge |c= beam )* EOF ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:42:11: (a= crystal |b= wedge |c= beam )* EOF { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:42:11: (a= crystal |b= wedge |c= beam )* loop1: do { int alt1=4; switch ( input.LA(1) ) { case CRYSTAL: { alt1=1; } break; case WEDGE: { alt1=2; } break; case BEAM: { alt1=3; } break; } switch (alt1) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:42:13: a= crystal { pushFollow(FOLLOW_crystal_in_configfile47); a=crystal(); state._fsp raddoseInitializer.setCrystal(a); } break; case 2 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:43:13: b= wedge { pushFollow(FOLLOW_wedge_in_configfile65); b=wedge(); state._fsp raddoseInitializer.exposeWedge(b); } break; case 3 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:44:13: c= beam { pushFollow(FOLLOW_beam_in_configfile85); c=beam(); state._fsp raddoseInitializer.setBeam(c); } break; default : break loop1; } } while (true); match(input,EOF,FOLLOW_EOF_in_configfile105); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return ; } // $ANTLR end "configfile" protected static class crystal_scope { String crystalType; int crystalCoefCalc; CoefCalc crystalCoefCalcClass; int crystalDdm; DDM crystalDdmClass; int crystalContainerMaterial; Container crystalContainerMaterialClass; Double gammaParam; Double b0Param; Double betaParam; String containerMixture; Double containerThickness; Double containerDensity; List<String> containerElementNames; List<Double> containerElementNums; String pdb; String seqFile; Double proteinConc; Double cellA; Double cellB; Double cellC; Double cellAl; Double cellBe; Double cellGa; int numMon; int numRes; int numRNA; int numDNA; List<String> heavyProteinAtomNames; List<Double> heavyProteinAtomNums; List<String> heavySolutionConcNames; List<Double> heavySolutionConcNums; Double solFrac; HashMap<Object, Object> crystalProperties; } protected Stack<InputfileParser.crystal_scope> crystal_stack = new Stack<>(); // $ANTLR start "crystal" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:49:1: crystal returns [Crystal cObj] : CRYSTAL ( crystalLine )+ ; public final Crystal crystal() throws RecognitionException { crystal_stack.push(new crystal_scope()); Crystal cObj = null; ((crystal_scope)crystal_stack.peek()).crystalCoefCalc = 2; // 0 = error, 1 = Simple, 2 = DEFAULT, 3 = RDV2, 4 = PDB, 5 = SAXS ((crystal_scope)crystal_stack.peek()).crystalProperties = new HashMap<Object, Object>(); try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:186:2: ( CRYSTAL ( crystalLine )+ ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:186:4: CRYSTAL ( crystalLine )+ { match(input,CRYSTAL,FOLLOW_CRYSTAL_in_crystal134); // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:186:12: ( crystalLine )+ int cnt2=0; loop2: do { int alt2=2; int LA2_0 = input.LA(1); if ( ((LA2_0 >= ABSCOEFCALC && LA2_0 <= ANGLEP)||(LA2_0 >= CALCULATEFLESCAPE && LA2_0 <= CALCULATEPEESCAPE)||(LA2_0 >= CONTAINERDENSITY && LA2_0 <= CONTAINERTHICKNESS)||(LA2_0 >= DDM && LA2_0 <= DECAYPARAM)||(LA2_0 >= DIFFRACTIONDECAYMODEL && LA2_0 <= DIMENSION)||LA2_0==FLRESOLUTION||(LA2_0 >= MATERIALELEMENTS && LA2_0 <= MATERIALTYPE)||LA2_0==MODELFILE||(LA2_0 >= NUMDNA && LA2_0 <= NUMRNA)||(LA2_0 >= PDBNAME && LA2_0 <= PERESOLUTION)||(LA2_0 >= PIXELSPERMICRON && LA2_0 <= PROTEINHEAVYATOMS)||LA2_0==SEQFILE||LA2_0==SEQUENCEFILE||(LA2_0 >= SOLVENTFRACTION && LA2_0 <= SOLVENTHEAVYCONC)||(LA2_0 >= TYPE && LA2_0 <= UNITCELL)||LA2_0==WIREFRAMETYPE) ) { alt2=1; } switch (alt2) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:186:12: crystalLine { pushFollow(FOLLOW_crystalLine_in_crystal136); crystalLine(); state._fsp } break; default : if ( cnt2 >= 1 ) break loop2; EarlyExitException eee = new EarlyExitException(2, input); throw eee; } cnt2++; } while (true); } if (((crystal_scope)crystal_stack.peek()).crystalCoefCalc == 1) { ((crystal_scope)crystal_stack.peek()).crystalCoefCalcClass = new CoefCalcAverage(); } if (((crystal_scope)crystal_stack.peek()).crystalCoefCalc == 2) { ((crystal_scope)crystal_stack.peek()).crystalCoefCalcClass = new CoefCalcFromParams(((crystal_scope)crystal_stack.peek()).cellA, ((crystal_scope)crystal_stack.peek()).cellB, ((crystal_scope)crystal_stack.peek()).cellC, ((crystal_scope)crystal_stack.peek()).cellAl, ((crystal_scope)crystal_stack.peek()).cellBe, ((crystal_scope)crystal_stack.peek()).cellGa, ((crystal_scope)crystal_stack.peek()).numMon, ((crystal_scope)crystal_stack.peek()).numRes, ((crystal_scope)crystal_stack.peek()).numRNA, ((crystal_scope)crystal_stack.peek()).numDNA, ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNames, ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNums, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNames, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNums, ((crystal_scope)crystal_stack.peek()).solFrac); } if (((crystal_scope)crystal_stack.peek()).crystalCoefCalc == 3) { ((crystal_scope)crystal_stack.peek()).crystalCoefCalcClass = new CoefCalcRaddose(((crystal_scope)crystal_stack.peek()).cellA, ((crystal_scope)crystal_stack.peek()).cellB, ((crystal_scope)crystal_stack.peek()).cellC, ((crystal_scope)crystal_stack.peek()).cellAl, ((crystal_scope)crystal_stack.peek()).cellBe, ((crystal_scope)crystal_stack.peek()).cellGa, ((crystal_scope)crystal_stack.peek()).numMon, ((crystal_scope)crystal_stack.peek()).numRes, ((crystal_scope)crystal_stack.peek()).numRNA, ((crystal_scope)crystal_stack.peek()).numDNA, ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNames, ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNums, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNames, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNums, ((crystal_scope)crystal_stack.peek()).solFrac); } if (((crystal_scope)crystal_stack.peek()).crystalCoefCalc == 4) { if (((crystal_scope)crystal_stack.peek()).heavySolutionConcNames != null) ((crystal_scope)crystal_stack.peek()).crystalCoefCalcClass = new CoefCalcFromPDB(((crystal_scope)crystal_stack.peek()).pdb, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNames, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNums); else ((crystal_scope)crystal_stack.peek()).crystalCoefCalcClass = new CoefCalcFromPDB(((crystal_scope)crystal_stack.peek()).pdb); } if (((crystal_scope)crystal_stack.peek()).crystalCoefCalc == 5) { ((crystal_scope)crystal_stack.peek()).crystalCoefCalcClass = new CoefCalcSAXS(((crystal_scope)crystal_stack.peek()).cellA, ((crystal_scope)crystal_stack.peek()).cellB, ((crystal_scope)crystal_stack.peek()).cellC, ((crystal_scope)crystal_stack.peek()).cellAl, ((crystal_scope)crystal_stack.peek()).cellBe, ((crystal_scope)crystal_stack.peek()).cellGa, ((crystal_scope)crystal_stack.peek()).numRes, ((crystal_scope)crystal_stack.peek()).numRNA, ((crystal_scope)crystal_stack.peek()).numDNA, ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNames, ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNums, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNames, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNums, ((crystal_scope)crystal_stack.peek()).solFrac, ((crystal_scope)crystal_stack.peek()).proteinConc); } if (((crystal_scope)crystal_stack.peek()).crystalCoefCalc == 6) { ((crystal_scope)crystal_stack.peek()).crystalCoefCalcClass = new CoefCalcFromSequence(((crystal_scope)crystal_stack.peek()).cellA, ((crystal_scope)crystal_stack.peek()).cellB, ((crystal_scope)crystal_stack.peek()).cellC, ((crystal_scope)crystal_stack.peek()).cellAl, ((crystal_scope)crystal_stack.peek()).cellBe, ((crystal_scope)crystal_stack.peek()).cellGa, ((crystal_scope)crystal_stack.peek()).numMon, ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNames, ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNums, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNames, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNums, ((crystal_scope)crystal_stack.peek()).solFrac, ((crystal_scope)crystal_stack.peek()).seqFile); } if (((crystal_scope)crystal_stack.peek()).crystalCoefCalc == 7) { ((crystal_scope)crystal_stack.peek()).crystalCoefCalcClass = new CoefCalcFromSequenceSAXS(((crystal_scope)crystal_stack.peek()).cellA, ((crystal_scope)crystal_stack.peek()).cellB, ((crystal_scope)crystal_stack.peek()).cellC, ((crystal_scope)crystal_stack.peek()).cellAl, ((crystal_scope)crystal_stack.peek()).cellBe, ((crystal_scope)crystal_stack.peek()).cellGa, ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNames, ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNums, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNames, ((crystal_scope)crystal_stack.peek()).heavySolutionConcNums, ((crystal_scope)crystal_stack.peek()).solFrac, ((crystal_scope)crystal_stack.peek()).proteinConc, ((crystal_scope)crystal_stack.peek()).seqFile); } ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_COEFCALC, ((crystal_scope)crystal_stack.peek()).crystalCoefCalcClass); if (((crystal_scope)crystal_stack.peek()).crystalDdm == 1) { ((crystal_scope)crystal_stack.peek()).crystalDdmClass = new DDMSimple(); } if (((crystal_scope)crystal_stack.peek()).crystalDdm == 2) { ((crystal_scope)crystal_stack.peek()).crystalDdmClass = new DDMLinear(); } if (((crystal_scope)crystal_stack.peek()).crystalDdm == 3) { ((crystal_scope)crystal_stack.peek()).crystalDdmClass = new DDMLeal(((crystal_scope)crystal_stack.peek()).gammaParam, ((crystal_scope)crystal_stack.peek()).b0Param, ((crystal_scope)crystal_stack.peek()).betaParam); } ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_DDM, ((crystal_scope)crystal_stack.peek()).crystalDdmClass); if (((crystal_scope)crystal_stack.peek()).crystalContainerMaterial == 1) { ((crystal_scope)crystal_stack.peek()).crystalContainerMaterialClass = new ContainerTransparent(); } if (((crystal_scope)crystal_stack.peek()).crystalContainerMaterial == 2) { ((crystal_scope)crystal_stack.peek()).crystalContainerMaterialClass = new ContainerMixture(((crystal_scope)crystal_stack.peek()).containerThickness, ((crystal_scope)crystal_stack.peek()).containerDensity, ((crystal_scope)crystal_stack.peek()).containerMixture); } if (((crystal_scope)crystal_stack.peek()).crystalContainerMaterial == 3) { ((crystal_scope)crystal_stack.peek()).crystalContainerMaterialClass = new ContainerElemental(((crystal_scope)crystal_stack.peek()).containerThickness, ((crystal_scope)crystal_stack.peek()).containerDensity, ((crystal_scope)crystal_stack.peek()).containerElementNames, ((crystal_scope)crystal_stack.peek()).containerElementNums); } ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_CONTAINER, ((crystal_scope)crystal_stack.peek()).crystalContainerMaterialClass); cObj = crystalFactory.createCrystal(((crystal_scope)crystal_stack.peek()).crystalType, ((crystal_scope)crystal_stack.peek()).crystalProperties); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving crystal_stack.pop(); } return cObj; } // $ANTLR end "crystal" // $ANTLR start "crystalLine" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:189:1: crystalLine : (a= crystalType |b= crystalDDM |c= crystalCoefcalc |d= crystalDim |e= crystalPPM |f= crystalAngP |g= crystalAngL |h= crystalDecayParam |i= containerThickness |j= containerDensity |k= crystalContainerMaterial |l= containerMaterialMixture |m= unitcell |n= nummonomers |o= numresidues |p= numRNA |q= numDNA |r= heavyProteinAtoms |s= heavySolutionConc |t= solventFraction |u= pdb |v= wireframeType |w= modelFile |x= calculatePEEscape |y= proteinConcentration |z= containerMaterialElements |aa= sequenceFile |bb= calculateFLEscape |cc= flResolution |dd= peResolution ); public final void crystalLine() throws RecognitionException { String a =null; int b =0; int c =0; Map<Object, Object> d =null; double e =0.0; double f =0.0; double g =0.0; InputfileParser.crystalDecayParam_return h =null; double i =0.0; double j =0.0; int k =0; String l =null; InputfileParser.unitcell_return m =null; int n =0; int o =0; int p =0; int q =0; InputfileParser.heavyProteinAtoms_return r =null; InputfileParser.heavySolutionConc_return s =null; double t =0.0; String u =null; String v =null; String w =null; String x =null; Double y =null; InputfileParser.containerMaterialElements_return z =null; String aa =null; String bb =null; int cc =0; int dd =0; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:190:2: (a= crystalType |b= crystalDDM |c= crystalCoefcalc |d= crystalDim |e= crystalPPM |f= crystalAngP |g= crystalAngL |h= crystalDecayParam |i= containerThickness |j= containerDensity |k= crystalContainerMaterial |l= containerMaterialMixture |m= unitcell |n= nummonomers |o= numresidues |p= numRNA |q= numDNA |r= heavyProteinAtoms |s= heavySolutionConc |t= solventFraction |u= pdb |v= wireframeType |w= modelFile |x= calculatePEEscape |y= proteinConcentration |z= containerMaterialElements |aa= sequenceFile |bb= calculateFLEscape |cc= flResolution |dd= peResolution ) int alt3=30; switch ( input.LA(1) ) { case TYPE: { alt3=1; } break; case DDM: case DIFFRACTIONDECAYMODEL: { alt3=2; } break; case ABSCOEFCALC: { alt3=3; } break; case DIMENSION: { alt3=4; } break; case PIXELSPERMICRON: { alt3=5; } break; case ANGLEP: { alt3=6; } break; case ANGLEL: { alt3=7; } break; case DECAYPARAM: { alt3=8; } break; case CONTAINERTHICKNESS: { alt3=9; } break; case CONTAINERDENSITY: { alt3=10; } break; case CONTAINERMATERIALTYPE: case MATERIALTYPE: { alt3=11; } break; case CONTAINERMATERIALMIXTURE: case MATERIALMIXTURE: { alt3=12; } break; case UNITCELL: { alt3=13; } break; case NUMMONOMERS: { alt3=14; } break; case NUMRESIDUES: { alt3=15; } break; case NUMRNA: { alt3=16; } break; case NUMDNA: { alt3=17; } break; case PROTEINHEAVYATOMS: { alt3=18; } break; case SOLVENTHEAVYCONC: { alt3=19; } break; case SOLVENTFRACTION: { alt3=20; } break; case PDBNAME: { alt3=21; } break; case WIREFRAMETYPE: { alt3=22; } break; case MODELFILE: { alt3=23; } break; case CALCULATEPEESCAPE: { alt3=24; } break; case PROTEINCONC: case PROTEINCONCENTRATION: { alt3=25; } break; case CONTAINERMATERIALELEMENTS: case MATERIALELEMENTS: { alt3=26; } break; case SEQFILE: case SEQUENCEFILE: { alt3=27; } break; case CALCULATEFLESCAPE: { alt3=28; } break; case FLRESOLUTION: { alt3=29; } break; case PERESOLUTION: { alt3=30; } break; default: NoViableAltException nvae = new NoViableAltException("", 3, 0, input); throw nvae; } switch (alt3) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:190:4: a= crystalType { pushFollow(FOLLOW_crystalType_in_crystalLine192); a=crystalType(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalType = a; } break; case 2 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:191:4: b= crystalDDM { pushFollow(FOLLOW_crystalDDM_in_crystalLine203); b=crystalDDM(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalDdm = b; } break; case 3 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:192:4: c= crystalCoefcalc { pushFollow(FOLLOW_crystalCoefcalc_in_crystalLine215); c=crystalCoefcalc(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalCoefCalc = c; } break; case 4 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:193:4: d= crystalDim { pushFollow(FOLLOW_crystalDim_in_crystalLine225); d=crystalDim(); state._fsp if (d != null) { ((crystal_scope)crystal_stack.peek()).crystalProperties.putAll(d); }; } break; case 5 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:196:4: e= crystalPPM { pushFollow(FOLLOW_crystalPPM_in_crystalLine236); e=crystalPPM(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_RESOLUTION, e); } break; case 6 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:197:4: f= crystalAngP { pushFollow(FOLLOW_crystalAngP_in_crystalLine247); f=crystalAngP(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_ANGLE_P, f); } break; case 7 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:198:4: g= crystalAngL { pushFollow(FOLLOW_crystalAngL_in_crystalLine258); g=crystalAngL(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_ANGLE_L, g); } break; case 8 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:199:4: h= crystalDecayParam { pushFollow(FOLLOW_crystalDecayParam_in_crystalLine269); h=crystalDecayParam(); state._fsp ((crystal_scope)crystal_stack.peek()).gammaParam = (h!=null?h.gammaParam:null); ((crystal_scope)crystal_stack.peek()).b0Param = (h!=null?h.b0Param:null); ((crystal_scope)crystal_stack.peek()).betaParam = (h!=null?h.betaParam:null); } break; case 9 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:202:4: i= containerThickness { pushFollow(FOLLOW_containerThickness_in_crystalLine279); i=containerThickness(); state._fsp ((crystal_scope)crystal_stack.peek()).containerThickness = i; } break; case 10 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:203:4: j= containerDensity { pushFollow(FOLLOW_containerDensity_in_crystalLine289); j=containerDensity(); state._fsp ((crystal_scope)crystal_stack.peek()).containerDensity = j; } break; case 11 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:204:4: k= crystalContainerMaterial { pushFollow(FOLLOW_crystalContainerMaterial_in_crystalLine299); k=crystalContainerMaterial(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalContainerMaterial = k; } break; case 12 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:205:4: l= containerMaterialMixture { pushFollow(FOLLOW_containerMaterialMixture_in_crystalLine308); l=containerMaterialMixture(); state._fsp ((crystal_scope)crystal_stack.peek()).containerMixture = l; } break; case 13 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:206:4: m= unitcell { pushFollow(FOLLOW_unitcell_in_crystalLine317); m=unitcell(); state._fsp ((crystal_scope)crystal_stack.peek()).cellA = (m!=null?m.dimA:null); ((crystal_scope)crystal_stack.peek()).cellB = (m!=null?m.dimB:null); ((crystal_scope)crystal_stack.peek()).cellC = (m!=null?m.dimC:null); ((crystal_scope)crystal_stack.peek()).cellAl = (m!=null?m.angA:null); ((crystal_scope)crystal_stack.peek()).cellBe = (m!=null?m.angB:null); ((crystal_scope)crystal_stack.peek()).cellGa = (m!=null?m.angC:null); } break; case 14 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:212:4: n= nummonomers { pushFollow(FOLLOW_nummonomers_in_crystalLine328); n=nummonomers(); state._fsp ((crystal_scope)crystal_stack.peek()).numMon = n; } break; case 15 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:213:4: o= numresidues { pushFollow(FOLLOW_numresidues_in_crystalLine339); o=numresidues(); state._fsp ((crystal_scope)crystal_stack.peek()).numRes = o; } break; case 16 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:214:4: p= numRNA { pushFollow(FOLLOW_numRNA_in_crystalLine350); p=numRNA(); state._fsp ((crystal_scope)crystal_stack.peek()).numRNA = p; } break; case 17 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:215:4: q= numDNA { pushFollow(FOLLOW_numDNA_in_crystalLine363); q=numDNA(); state._fsp ((crystal_scope)crystal_stack.peek()).numDNA = q; } break; case 18 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:216:4: r= heavyProteinAtoms { pushFollow(FOLLOW_heavyProteinAtoms_in_crystalLine376); r=heavyProteinAtoms(); state._fsp ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNames = (r!=null?r.names:null); ((crystal_scope)crystal_stack.peek()).heavyProteinAtomNums = (r!=null?r.num:null); } break; case 19 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:218:4: s= heavySolutionConc { pushFollow(FOLLOW_heavySolutionConc_in_crystalLine385); s=heavySolutionConc(); state._fsp ((crystal_scope)crystal_stack.peek()).heavySolutionConcNames = (s!=null?s.names:null); ((crystal_scope)crystal_stack.peek()).heavySolutionConcNums = (s!=null?s.num:null); } break; case 20 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:220:4: t= solventFraction { pushFollow(FOLLOW_solventFraction_in_crystalLine394); t=solventFraction(); state._fsp ((crystal_scope)crystal_stack.peek()).solFrac = t; } break; case 21 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:221:4: u= pdb { pushFollow(FOLLOW_pdb_in_crystalLine404); u=pdb(); state._fsp ((crystal_scope)crystal_stack.peek()).pdb = u; } break; case 22 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:222:4: v= wireframeType { pushFollow(FOLLOW_wireframeType_in_crystalLine417); v=wireframeType(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_WIREFRAME_TYPE, v); } break; case 23 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:223:4: w= modelFile { pushFollow(FOLLOW_modelFile_in_crystalLine428); w=modelFile(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_WIREFRAME_FILE, w); } break; case 24 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:224:4: x= calculatePEEscape { pushFollow(FOLLOW_calculatePEEscape_in_crystalLine440); x=calculatePEEscape(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_ELECTRON_ESCAPE, x); } break; case 25 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:225:4: y= proteinConcentration { pushFollow(FOLLOW_proteinConcentration_in_crystalLine450); y=proteinConcentration(); state._fsp ((crystal_scope)crystal_stack.peek()).proteinConc = y; } break; case 26 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:226:4: z= containerMaterialElements { pushFollow(FOLLOW_containerMaterialElements_in_crystalLine459); z=containerMaterialElements(); state._fsp ((crystal_scope)crystal_stack.peek()).containerElementNames = (z!=null?z.names:null); ((crystal_scope)crystal_stack.peek()).containerElementNums = (z!=null?z.num:null); } break; case 27 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:228:4: aa= sequenceFile { pushFollow(FOLLOW_sequenceFile_in_crystalLine468); aa=sequenceFile(); state._fsp ((crystal_scope)crystal_stack.peek()).seqFile = aa; } break; case 28 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:230:4: bb= calculateFLEscape { pushFollow(FOLLOW_calculateFLEscape_in_crystalLine481); bb=calculateFLEscape(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_FLUORESCENT_ESCAPE, bb); } break; case 29 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:231:4: cc= flResolution { pushFollow(FOLLOW_flResolution_in_crystalLine491); cc=flResolution(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_FLUORESCENT_RESOLUTION, cc); } break; case 30 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:232:4: dd= peResolution { pushFollow(FOLLOW_peResolution_in_crystalLine502); dd=peResolution(); state._fsp ((crystal_scope)crystal_stack.peek()).crystalProperties.put(Crystal.CRYSTAL_PHOTOELECTRON_RESOLUTION, dd); } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return ; } // $ANTLR end "crystalLine" // $ANTLR start "crystalType" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:236:1: crystalType returns [String crystalType] : TYPE e= STRING ; public final String crystalType() throws RecognitionException { String crystalType = null; Token e=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:237:2: ( TYPE e= STRING ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:237:4: TYPE e= STRING { match(input,TYPE,FOLLOW_TYPE_in_crystalType523); e=(Token)match(input,STRING,FOLLOW_STRING_in_crystalType527); crystalType = (e!=null?e.getText():null); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return crystalType; } // $ANTLR end "crystalType" // $ANTLR start "crystalDDM" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:240:1: crystalDDM returns [int value] : ( DIFFRACTIONDECAYMODEL | DDM ) e= crystalDDMKeyword ; public final int crystalDDM() throws RecognitionException { int value = 0; int e =0; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:241:2: ( ( DIFFRACTIONDECAYMODEL | DDM ) e= crystalDDMKeyword ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:241:4: ( DIFFRACTIONDECAYMODEL | DDM ) e= crystalDDMKeyword { if ( input.LA(1)==DDM||input.LA(1)==DIFFRACTIONDECAYMODEL ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } pushFollow(FOLLOW_crystalDDMKeyword_in_crystalDDM581); e=crystalDDMKeyword(); state._fsp value = e; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "crystalDDM" // $ANTLR start "crystalDDMKeyword" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:244:1: crystalDDMKeyword returns [int value] : ( SIMPLE | LINEAR | LEAL ); public final int crystalDDMKeyword() throws RecognitionException { int value = 0; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:245:2: ( SIMPLE | LINEAR | LEAL ) int alt4=3; switch ( input.LA(1) ) { case SIMPLE: { alt4=1; } break; case LINEAR: { alt4=2; } break; case LEAL: { alt4=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 4, 0, input); throw nvae; } switch (alt4) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:245:4: SIMPLE { match(input,SIMPLE,FOLLOW_SIMPLE_in_crystalDDMKeyword729); value = 1; } break; case 2 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:246:4: LINEAR { match(input,LINEAR,FOLLOW_LINEAR_in_crystalDDMKeyword736); value = 2; } break; case 3 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:247:4: LEAL { match(input,LEAL,FOLLOW_LEAL_in_crystalDDMKeyword743); value = 3; } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "crystalDDMKeyword" public static class crystalDecayParam_return extends ParserRuleReturnScope { public Double gammaParam; public Double b0Param; public Double betaParam; }; // $ANTLR start "crystalDecayParam" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:253:1: crystalDecayParam returns [Double gammaParam, Double b0Param, Double betaParam] : DECAYPARAM a= FLOAT b= FLOAT c= FLOAT ; public final InputfileParser.crystalDecayParam_return crystalDecayParam() throws RecognitionException { InputfileParser.crystalDecayParam_return retval = new InputfileParser.crystalDecayParam_return(); retval.start = input.LT(1); Token a=null; Token b=null; Token c=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:254:2: ( DECAYPARAM a= FLOAT b= FLOAT c= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:254:4: DECAYPARAM a= FLOAT b= FLOAT c= FLOAT { match(input,DECAYPARAM,FOLLOW_DECAYPARAM_in_crystalDecayParam863); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalDecayParam867); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalDecayParam871); c=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalDecayParam875); retval.gammaParam = Double.parseDouble((a!=null?a.getText():null)); retval.b0Param = Double.parseDouble((b!=null?b.getText():null)); retval.betaParam = Double.parseDouble((c!=null?c.getText():null)); } retval.stop = input.LT(-1); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "crystalDecayParam" // $ANTLR start "crystalCoefcalc" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:257:1: crystalCoefcalc returns [int value] : ABSCOEFCALC a= crystalCoefcalcKeyword ; public final int crystalCoefcalc() throws RecognitionException { int value = 0; int a =0; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:258:2: ( ABSCOEFCALC a= crystalCoefcalcKeyword ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:258:4: ABSCOEFCALC a= crystalCoefcalcKeyword { match(input,ABSCOEFCALC,FOLLOW_ABSCOEFCALC_in_crystalCoefcalc947); pushFollow(FOLLOW_crystalCoefcalcKeyword_in_crystalCoefcalc951); a=crystalCoefcalcKeyword(); state._fsp value = a; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "crystalCoefcalc" // $ANTLR start "crystalCoefcalcKeyword" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:260:1: crystalCoefcalcKeyword returns [int value] : ( DUMMY | AVERAGE | DEFAULT | RDJAVA | RDFORTAN | PDB | SAXS | SEQUENCE | SAXSSEQ ); public final int crystalCoefcalcKeyword() throws RecognitionException { int value = 0; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:261:2: ( DUMMY | AVERAGE | DEFAULT | RDJAVA | RDFORTAN | PDB | SAXS | SEQUENCE | SAXSSEQ ) int alt5=9; switch ( input.LA(1) ) { case DUMMY: { alt5=1; } break; case AVERAGE: { alt5=2; } break; case DEFAULT: { alt5=3; } break; case RDJAVA: { alt5=4; } break; case RDFORTAN: { alt5=5; } break; case PDB: { alt5=6; } break; case SAXS: { alt5=7; } break; case SEQUENCE: { alt5=8; } break; case SAXSSEQ: { alt5=9; } break; default: NoViableAltException nvae = new NoViableAltException("", 5, 0, input); throw nvae; } switch (alt5) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:261:4: DUMMY { match(input,DUMMY,FOLLOW_DUMMY_in_crystalCoefcalcKeyword1030); value = 1; } break; case 2 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:262:4: AVERAGE { match(input,AVERAGE,FOLLOW_AVERAGE_in_crystalCoefcalcKeyword1040); value = 1; } break; case 3 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:263:4: DEFAULT { match(input,DEFAULT,FOLLOW_DEFAULT_in_crystalCoefcalcKeyword1048); value = 2; } break; case 4 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:264:4: RDJAVA { match(input,RDJAVA,FOLLOW_RDJAVA_in_crystalCoefcalcKeyword1056); value = 2; } break; case 5 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:265:4: RDFORTAN { match(input,RDFORTAN,FOLLOW_RDFORTAN_in_crystalCoefcalcKeyword1063); value = 3; } break; case 6 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:266:4: PDB { match(input,PDB,FOLLOW_PDB_in_crystalCoefcalcKeyword1070); value = 4; } break; case 7 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:267:4: SAXS { match(input,SAXS,FOLLOW_SAXS_in_crystalCoefcalcKeyword1080); value = 5; } break; case 8 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:268:4: SEQUENCE { match(input,SEQUENCE,FOLLOW_SEQUENCE_in_crystalCoefcalcKeyword1088); value = 6; } break; case 9 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:269:4: SAXSSEQ { match(input,SAXSSEQ,FOLLOW_SAXSSEQ_in_crystalCoefcalcKeyword1095); value = 7; } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "crystalCoefcalcKeyword" // $ANTLR start "crystalDim" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:281:1: crystalDim returns [Map<Object, Object> properties] : DIMENSION (a= FLOAT b= FLOAT c= FLOAT |e= FLOAT f= FLOAT |d= FLOAT ) ; public final Map<Object, Object> crystalDim() throws RecognitionException { Map<Object, Object> properties = null; Token a=null; Token b=null; Token c=null; Token e=null; Token f=null; Token d=null; properties = new HashMap<Object, Object>(); try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:284:3: ( DIMENSION (a= FLOAT b= FLOAT c= FLOAT |e= FLOAT f= FLOAT |d= FLOAT ) ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:284:5: DIMENSION (a= FLOAT b= FLOAT c= FLOAT |e= FLOAT f= FLOAT |d= FLOAT ) { match(input,DIMENSION,FOLLOW_DIMENSION_in_crystalDim1419); // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:285:2: (a= FLOAT b= FLOAT c= FLOAT |e= FLOAT f= FLOAT |d= FLOAT ) int alt6=3; int LA6_0 = input.LA(1); if ( (LA6_0==FLOAT) ) { int LA6_1 = input.LA(2); if ( (LA6_1==FLOAT) ) { int LA6_2 = input.LA(3); if ( (LA6_2==FLOAT) ) { alt6=1; } else if ( (LA6_2==EOF||(LA6_2 >= ABSCOEFCALC && LA6_2 <= ANGLEP)||(LA6_2 >= BEAM && LA6_2 <= CALCULATEPEESCAPE)||(LA6_2 >= CONTAINERDENSITY && LA6_2 <= DECAYPARAM)||(LA6_2 >= DIFFRACTIONDECAYMODEL && LA6_2 <= DIMENSION)||LA6_2==FLRESOLUTION||(LA6_2 >= MATERIALELEMENTS && LA6_2 <= MATERIALTYPE)||LA6_2==MODELFILE||(LA6_2 >= NUMDNA && LA6_2 <= NUMRNA)||(LA6_2 >= PDBNAME && LA6_2 <= PERESOLUTION)||(LA6_2 >= PIXELSPERMICRON && LA6_2 <= PROTEINHEAVYATOMS)||LA6_2==SEQFILE||LA6_2==SEQUENCEFILE||(LA6_2 >= SOLVENTFRACTION && LA6_2 <= SOLVENTHEAVYCONC)||(LA6_2 >= TYPE && LA6_2 <= UNITCELL)||(LA6_2 >= WEDGE && LA6_2 <= WIREFRAMETYPE)) ) { alt6=2; } else { NoViableAltException nvae = new NoViableAltException("", 6, 2, input); throw nvae; } } else if ( (LA6_1==EOF||(LA6_1 >= ABSCOEFCALC && LA6_1 <= ANGLEP)||(LA6_1 >= BEAM && LA6_1 <= CALCULATEPEESCAPE)||(LA6_1 >= CONTAINERDENSITY && LA6_1 <= DECAYPARAM)||(LA6_1 >= DIFFRACTIONDECAYMODEL && LA6_1 <= DIMENSION)||LA6_1==FLRESOLUTION||(LA6_1 >= MATERIALELEMENTS && LA6_1 <= MATERIALTYPE)||LA6_1==MODELFILE||(LA6_1 >= NUMDNA && LA6_1 <= NUMRNA)||(LA6_1 >= PDBNAME && LA6_1 <= PERESOLUTION)||(LA6_1 >= PIXELSPERMICRON && LA6_1 <= PROTEINHEAVYATOMS)||LA6_1==SEQFILE||LA6_1==SEQUENCEFILE||(LA6_1 >= SOLVENTFRACTION && LA6_1 <= SOLVENTHEAVYCONC)||(LA6_1 >= TYPE && LA6_1 <= UNITCELL)||(LA6_1 >= WEDGE && LA6_1 <= WIREFRAMETYPE)) ) { alt6=3; } else { NoViableAltException nvae = new NoViableAltException("", 6, 1, input); throw nvae; } } else { NoViableAltException nvae = new NoViableAltException("", 6, 0, input); throw nvae; } switch (alt6) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:286:7: a= FLOAT b= FLOAT c= FLOAT { a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalDim1432); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalDim1436); c=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalDim1440); properties.put(Crystal.CRYSTAL_DIM_X, Double.parseDouble((a!=null?a.getText():null))); properties.put(Crystal.CRYSTAL_DIM_Y, Double.parseDouble((b!=null?b.getText():null))); properties.put(Crystal.CRYSTAL_DIM_Z, Double.parseDouble((c!=null?c.getText():null))); } break; case 2 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:289:7: e= FLOAT f= FLOAT { e=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalDim1452); f=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalDim1456); properties.put(Crystal.CRYSTAL_DIM_X, Double.parseDouble((e!=null?e.getText():null))); properties.put(Crystal.CRYSTAL_DIM_Y, Double.parseDouble((f!=null?f.getText():null))); } break; case 3 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:291:7: d= FLOAT { d=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalDim1468); properties.put(Crystal.CRYSTAL_DIM_X, Double.parseDouble((d!=null?d.getText():null))); } break; } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return properties; } // $ANTLR end "crystalDim" // $ANTLR start "crystalAngP" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:295:1: crystalAngP returns [double value] : ANGLEP a= FLOAT ; public final double crystalAngP() throws RecognitionException { double value = 0.0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:296:2: ( ANGLEP a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:296:4: ANGLEP a= FLOAT { match(input,ANGLEP,FOLLOW_ANGLEP_in_crystalAngP1545); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalAngP1549); value = Double.parseDouble((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "crystalAngP" // $ANTLR start "crystalAngL" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:300:1: crystalAngL returns [double value] : ANGLEL a= FLOAT ; public final double crystalAngL() throws RecognitionException { double value = 0.0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:301:2: ( ANGLEL a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:301:4: ANGLEL a= FLOAT { match(input,ANGLEL,FOLLOW_ANGLEL_in_crystalAngL1604); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalAngL1608); value = Double.parseDouble((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "crystalAngL" // $ANTLR start "crystalPPM" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:305:1: crystalPPM returns [double ppm] : PIXELSPERMICRON FLOAT ; public final double crystalPPM() throws RecognitionException { double ppm = 0.0; Token FLOAT1=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:306:2: ( PIXELSPERMICRON FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:306:4: PIXELSPERMICRON FLOAT { match(input,PIXELSPERMICRON,FOLLOW_PIXELSPERMICRON_in_crystalPPM1662); FLOAT1=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_crystalPPM1664); ppm = Double.parseDouble((FLOAT1!=null?FLOAT1.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return ppm; } // $ANTLR end "crystalPPM" public static class unitcell_return extends ParserRuleReturnScope { public Double dimA; public Double dimB; public Double dimC; public Double angA; public Double angB; public Double angC; }; // $ANTLR start "unitcell" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:309:1: unitcell returns [Double dimA, Double dimB, Double dimC, Double angA, Double angB, Double angC] : UNITCELL a= FLOAT b= FLOAT c= FLOAT (al= FLOAT be= FLOAT ga= FLOAT )? ; public final InputfileParser.unitcell_return unitcell() throws RecognitionException { InputfileParser.unitcell_return retval = new InputfileParser.unitcell_return(); retval.start = input.LT(1); Token a=null; Token b=null; Token c=null; Token al=null; Token be=null; Token ga=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:310:2: ( UNITCELL a= FLOAT b= FLOAT c= FLOAT (al= FLOAT be= FLOAT ga= FLOAT )? ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:310:4: UNITCELL a= FLOAT b= FLOAT c= FLOAT (al= FLOAT be= FLOAT ga= FLOAT )? { match(input,UNITCELL,FOLLOW_UNITCELL_in_unitcell1762); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_unitcell1766); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_unitcell1770); c=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_unitcell1774); retval.dimA = Double.parseDouble((a!=null?a.getText():null)); retval.dimB = Double.parseDouble((b!=null?b.getText():null)); retval.dimC = Double.parseDouble((c!=null?c.getText():null)); // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:314:7: (al= FLOAT be= FLOAT ga= FLOAT )? int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0==FLOAT) ) { alt7=1; } switch (alt7) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:314:8: al= FLOAT be= FLOAT ga= FLOAT { al=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_unitcell1789); be=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_unitcell1793); ga=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_unitcell1797); retval.angA = Double.parseDouble((al!=null?al.getText():null)); retval.angB = Double.parseDouble((be!=null?be.getText():null)); retval.angC = Double.parseDouble((ga!=null?ga.getText():null)); } break; } } retval.stop = input.LT(-1); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "unitcell" // $ANTLR start "proteinConcentration" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:322:1: proteinConcentration returns [Double proteinConc] : ( PROTEINCONCENTRATION | PROTEINCONC ) a= FLOAT ; public final Double proteinConcentration() throws RecognitionException { Double proteinConc = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:323:2: ( ( PROTEINCONCENTRATION | PROTEINCONC ) a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:323:4: ( PROTEINCONCENTRATION | PROTEINCONC ) a= FLOAT { if ( (input.LA(1) >= PROTEINCONC && input.LA(1) <= PROTEINCONCENTRATION) ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_proteinConcentration1885); proteinConc = Double.parseDouble((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return proteinConc; } // $ANTLR end "proteinConcentration" // $ANTLR start "nummonomers" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:327:1: nummonomers returns [int value] : NUMMONOMERS a= FLOAT ; public final int nummonomers() throws RecognitionException { int value = 0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:328:2: ( NUMMONOMERS a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:328:4: NUMMONOMERS a= FLOAT { match(input,NUMMONOMERS,FOLLOW_NUMMONOMERS_in_nummonomers2067); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_nummonomers2071); value = Integer.parseInt((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "nummonomers" // $ANTLR start "numresidues" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:331:1: numresidues returns [int value] : NUMRESIDUES a= FLOAT ; public final int numresidues() throws RecognitionException { int value = 0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:332:2: ( NUMRESIDUES a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:332:4: NUMRESIDUES a= FLOAT { match(input,NUMRESIDUES,FOLLOW_NUMRESIDUES_in_numresidues2148); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_numresidues2152); value = Integer.parseInt((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "numresidues" // $ANTLR start "numRNA" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:335:1: numRNA returns [int value] : NUMRNA a= FLOAT ; public final int numRNA() throws RecognitionException { int value = 0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:336:2: ( NUMRNA a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:336:4: NUMRNA a= FLOAT { match(input,NUMRNA,FOLLOW_NUMRNA_in_numRNA2230); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_numRNA2234); value = Integer.parseInt((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "numRNA" // $ANTLR start "numDNA" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:339:1: numDNA returns [int value] : NUMDNA a= FLOAT ; public final int numDNA() throws RecognitionException { int value = 0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:340:2: ( NUMDNA a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:340:4: NUMDNA a= FLOAT { match(input,NUMDNA,FOLLOW_NUMDNA_in_numDNA2287); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_numDNA2291); value = Integer.parseInt((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "numDNA" public static class heavyProteinAtoms_return extends ParserRuleReturnScope { public List<String> names; public List<Double> num;; }; // $ANTLR start "heavyProteinAtoms" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:343:1: heavyProteinAtoms returns [List<String> names, List<Double> num;] : PROTEINHEAVYATOMS (a= ELEMENT b= FLOAT )+ ; public final InputfileParser.heavyProteinAtoms_return heavyProteinAtoms() throws RecognitionException { InputfileParser.heavyProteinAtoms_return retval = new InputfileParser.heavyProteinAtoms_return(); retval.start = input.LT(1); Token a=null; Token b=null; retval.names = new ArrayList<String>(); retval.num = new ArrayList<Double>(); try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:348:2: ( PROTEINHEAVYATOMS (a= ELEMENT b= FLOAT )+ ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:348:4: PROTEINHEAVYATOMS (a= ELEMENT b= FLOAT )+ { match(input,PROTEINHEAVYATOMS,FOLLOW_PROTEINHEAVYATOMS_in_heavyProteinAtoms2347); // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:348:22: (a= ELEMENT b= FLOAT )+ int cnt8=0; loop8: do { int alt8=2; int LA8_0 = input.LA(1); if ( (LA8_0==ELEMENT) ) { alt8=1; } switch (alt8) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:348:23: a= ELEMENT b= FLOAT { a=(Token)match(input,ELEMENT,FOLLOW_ELEMENT_in_heavyProteinAtoms2352); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_heavyProteinAtoms2356); retval.names.add((a!=null?a.getText():null)); retval.num.add(Double.parseDouble((b!=null?b.getText():null))); } break; default : if ( cnt8 >= 1 ) break loop8; EarlyExitException eee = new EarlyExitException(8, input); throw eee; } cnt8++; } while (true); } retval.stop = input.LT(-1); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "heavyProteinAtoms" public static class heavySolutionConc_return extends ParserRuleReturnScope { public List<String> names; public List<Double> num;; }; // $ANTLR start "heavySolutionConc" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:352:1: heavySolutionConc returns [List<String> names, List<Double> num;] : SOLVENTHEAVYCONC (a= ELEMENT b= FLOAT )+ ; public final InputfileParser.heavySolutionConc_return heavySolutionConc() throws RecognitionException { InputfileParser.heavySolutionConc_return retval = new InputfileParser.heavySolutionConc_return(); retval.start = input.LT(1); Token a=null; Token b=null; retval.names = new ArrayList<String>(); retval.num = new ArrayList<Double>(); try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:357:2: ( SOLVENTHEAVYCONC (a= ELEMENT b= FLOAT )+ ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:357:4: SOLVENTHEAVYCONC (a= ELEMENT b= FLOAT )+ { match(input,SOLVENTHEAVYCONC,FOLLOW_SOLVENTHEAVYCONC_in_heavySolutionConc2503); // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:357:21: (a= ELEMENT b= FLOAT )+ int cnt9=0; loop9: do { int alt9=2; int LA9_0 = input.LA(1); if ( (LA9_0==ELEMENT) ) { alt9=1; } switch (alt9) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:357:22: a= ELEMENT b= FLOAT { a=(Token)match(input,ELEMENT,FOLLOW_ELEMENT_in_heavySolutionConc2508); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_heavySolutionConc2512); retval.names.add((a!=null?a.getText():null)); retval.num.add(Double.parseDouble((b!=null?b.getText():null))); } break; default : if ( cnt9 >= 1 ) break loop9; EarlyExitException eee = new EarlyExitException(9, input); throw eee; } cnt9++; } while (true); } retval.stop = input.LT(-1); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "heavySolutionConc" // $ANTLR start "solventFraction" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:360:1: solventFraction returns [double solFrac] : SOLVENTFRACTION a= FLOAT ; public final double solventFraction() throws RecognitionException { double solFrac = 0.0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:361:2: ( SOLVENTFRACTION a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:361:4: SOLVENTFRACTION a= FLOAT { match(input,SOLVENTFRACTION,FOLLOW_SOLVENTFRACTION_in_solventFraction2618); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_solventFraction2622); solFrac = Double.parseDouble((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return solFrac; } // $ANTLR end "solventFraction" // $ANTLR start "pdb" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:364:1: pdb returns [String pdb] : PDBNAME a= STRING ; public final String pdb() throws RecognitionException { String pdb = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:365:2: ( PDBNAME a= STRING ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:365:4: PDBNAME a= STRING { match(input,PDBNAME,FOLLOW_PDBNAME_in_pdb2719); a=(Token)match(input,STRING,FOLLOW_STRING_in_pdb2723); pdb = (a!=null?a.getText():null); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return pdb; } // $ANTLR end "pdb" // $ANTLR start "wireframeType" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:368:1: wireframeType returns [String value] : WIREFRAMETYPE a= STRING ; public final String wireframeType() throws RecognitionException { String value = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:369:2: ( WIREFRAMETYPE a= STRING ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:369:4: WIREFRAMETYPE a= STRING { match(input,WIREFRAMETYPE,FOLLOW_WIREFRAMETYPE_in_wireframeType2760); a=(Token)match(input,STRING,FOLLOW_STRING_in_wireframeType2764); value = (a!=null?a.getText():null); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "wireframeType" // $ANTLR start "modelFile" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:372:1: modelFile returns [String value] : MODELFILE a= STRING ; public final String modelFile() throws RecognitionException { String value = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:373:2: ( MODELFILE a= STRING ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:373:4: MODELFILE a= STRING { match(input,MODELFILE,FOLLOW_MODELFILE_in_modelFile2852); a=(Token)match(input,STRING,FOLLOW_STRING_in_modelFile2856); value = (a!=null?a.getText():null); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "modelFile" // $ANTLR start "calculatePEEscape" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:376:1: calculatePEEscape returns [String value] : CALCULATEPEESCAPE a= STRING ; public final String calculatePEEscape() throws RecognitionException { String value = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:377:2: ( CALCULATEPEESCAPE a= STRING ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:377:4: CALCULATEPEESCAPE a= STRING { match(input,CALCULATEPEESCAPE,FOLLOW_CALCULATEPEESCAPE_in_calculatePEEscape2923); a=(Token)match(input,STRING,FOLLOW_STRING_in_calculatePEEscape2927); value = (a!=null?a.getText():null); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "calculatePEEscape" // $ANTLR start "crystalContainerMaterial" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:381:1: crystalContainerMaterial returns [int value] : ( CONTAINERMATERIALTYPE | MATERIALTYPE ) e= crystalContainerKeyword ; public final int crystalContainerMaterial() throws RecognitionException { int value = 0; int e =0; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:382:2: ( ( CONTAINERMATERIALTYPE | MATERIALTYPE ) e= crystalContainerKeyword ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:382:4: ( CONTAINERMATERIALTYPE | MATERIALTYPE ) e= crystalContainerKeyword { if ( input.LA(1)==CONTAINERMATERIALTYPE||input.LA(1)==MATERIALTYPE ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } pushFollow(FOLLOW_crystalContainerKeyword_in_crystalContainerMaterial3051); e=crystalContainerKeyword(); state._fsp value = e; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "crystalContainerMaterial" // $ANTLR start "crystalContainerKeyword" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:385:1: crystalContainerKeyword returns [int value] : ( NONE | MIXTURE | ELEMENTAL ); public final int crystalContainerKeyword() throws RecognitionException { int value = 0; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:386:2: ( NONE | MIXTURE | ELEMENTAL ) int alt10=3; switch ( input.LA(1) ) { case NONE: { alt10=1; } break; case MIXTURE: { alt10=2; } break; case ELEMENTAL: { alt10=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 10, 0, input); throw nvae; } switch (alt10) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:386:4: NONE { match(input,NONE,FOLLOW_NONE_in_crystalContainerKeyword3244); value = 1; } break; case 2 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:387:4: MIXTURE { match(input,MIXTURE,FOLLOW_MIXTURE_in_crystalContainerKeyword3253); value = 2; } break; case 3 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:388:4: ELEMENTAL { match(input,ELEMENTAL,FOLLOW_ELEMENTAL_in_crystalContainerKeyword3261); value = 3; } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "crystalContainerKeyword" // $ANTLR start "containerThickness" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:394:1: containerThickness returns [double value] : CONTAINERTHICKNESS a= FLOAT ; public final double containerThickness() throws RecognitionException { double value = 0.0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:395:2: ( CONTAINERTHICKNESS a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:395:4: CONTAINERTHICKNESS a= FLOAT { match(input,CONTAINERTHICKNESS,FOLLOW_CONTAINERTHICKNESS_in_containerThickness3401); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_containerThickness3405); value = Double.parseDouble((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "containerThickness" // $ANTLR start "containerMaterialMixture" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:398:1: containerMaterialMixture returns [String value] : ( CONTAINERMATERIALMIXTURE | MATERIALMIXTURE ) a= STRING ; public final String containerMaterialMixture() throws RecognitionException { String value = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:399:2: ( ( CONTAINERMATERIALMIXTURE | MATERIALMIXTURE ) a= STRING ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:399:4: ( CONTAINERMATERIALMIXTURE | MATERIALMIXTURE ) a= STRING { if ( input.LA(1)==CONTAINERMATERIALMIXTURE||input.LA(1)==MATERIALMIXTURE ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } a=(Token)match(input,STRING,FOLLOW_STRING_in_containerMaterialMixture3526); value = (a!=null?a.getText():null); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "containerMaterialMixture" public static class containerMaterialElements_return extends ParserRuleReturnScope { public List<String> names; public List<Double> num;; }; // $ANTLR start "containerMaterialElements" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:403:1: containerMaterialElements returns [List<String> names, List<Double> num;] : ( CONTAINERMATERIALELEMENTS | MATERIALELEMENTS ) (a= ELEMENT b= FLOAT )+ ; public final InputfileParser.containerMaterialElements_return containerMaterialElements() throws RecognitionException { InputfileParser.containerMaterialElements_return retval = new InputfileParser.containerMaterialElements_return(); retval.start = input.LT(1); Token a=null; Token b=null; retval.names = new ArrayList<String>(); retval.num = new ArrayList<Double>(); try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:408:2: ( ( CONTAINERMATERIALELEMENTS | MATERIALELEMENTS ) (a= ELEMENT b= FLOAT )+ ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:408:4: ( CONTAINERMATERIALELEMENTS | MATERIALELEMENTS ) (a= ELEMENT b= FLOAT )+ { if ( input.LA(1)==CONTAINERMATERIALELEMENTS||input.LA(1)==MATERIALELEMENTS ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:408:51: (a= ELEMENT b= FLOAT )+ int cnt11=0; loop11: do { int alt11=2; int LA11_0 = input.LA(1); if ( (LA11_0==ELEMENT) ) { alt11=1; } switch (alt11) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:408:52: a= ELEMENT b= FLOAT { a=(Token)match(input,ELEMENT,FOLLOW_ELEMENT_in_containerMaterialElements3762); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_containerMaterialElements3766); retval.names.add((a!=null?a.getText():null)); retval.num.add(Double.parseDouble((b!=null?b.getText():null))); } break; default : if ( cnt11 >= 1 ) break loop11; EarlyExitException eee = new EarlyExitException(11, input); throw eee; } cnt11++; } while (true); } retval.stop = input.LT(-1); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "containerMaterialElements" // $ANTLR start "containerDensity" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:412:1: containerDensity returns [double value] : CONTAINERDENSITY a= FLOAT ; public final double containerDensity() throws RecognitionException { double value = 0.0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:413:2: ( CONTAINERDENSITY a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:413:4: CONTAINERDENSITY a= FLOAT { match(input,CONTAINERDENSITY,FOLLOW_CONTAINERDENSITY_in_containerDensity4001); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_containerDensity4005); value = Double.parseDouble((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "containerDensity" // $ANTLR start "sequenceFile" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:416:1: sequenceFile returns [String value] : ( SEQUENCEFILE | SEQFILE ) a= STRING ; public final String sequenceFile() throws RecognitionException { String value = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:417:2: ( ( SEQUENCEFILE | SEQFILE ) a= STRING ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:417:4: ( SEQUENCEFILE | SEQFILE ) a= STRING { if ( input.LA(1)==SEQFILE||input.LA(1)==SEQUENCEFILE ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } a=(Token)match(input,STRING,FOLLOW_STRING_in_sequenceFile4116); value = (a!=null?a.getText():null); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "sequenceFile" // $ANTLR start "calculateFLEscape" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:421:1: calculateFLEscape returns [String value] : CALCULATEFLESCAPE a= STRING ; public final String calculateFLEscape() throws RecognitionException { String value = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:422:2: ( CALCULATEFLESCAPE a= STRING ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:422:4: CALCULATEFLESCAPE a= STRING { match(input,CALCULATEFLESCAPE,FOLLOW_CALCULATEFLESCAPE_in_calculateFLEscape4239); a=(Token)match(input,STRING,FOLLOW_STRING_in_calculateFLEscape4243); value = (a!=null?a.getText():null); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "calculateFLEscape" // $ANTLR start "flResolution" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:426:1: flResolution returns [int value] : FLRESOLUTION a= FLOAT ; public final int flResolution() throws RecognitionException { int value = 0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:427:2: ( FLRESOLUTION a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:427:4: FLRESOLUTION a= FLOAT { match(input,FLRESOLUTION,FOLLOW_FLRESOLUTION_in_flResolution4355); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_flResolution4359); value = Integer.parseInt((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "flResolution" // $ANTLR start "peResolution" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:430:1: peResolution returns [int value] : PERESOLUTION a= FLOAT ; public final int peResolution() throws RecognitionException { int value = 0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:431:2: ( PERESOLUTION a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:431:4: PERESOLUTION a= FLOAT { match(input,PERESOLUTION,FOLLOW_PERESOLUTION_in_peResolution4441); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_peResolution4445); value = Integer.parseInt((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "peResolution" protected static class beam_scope { String beamType; HashMap<Object, Object> beamProperties; } protected Stack<InputfileParser.beam_scope> beam_stack = new Stack<>(); // $ANTLR start "beam" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:434:1: beam returns [Beam bObj] : BEAM ( beamLine )+ ; public final Beam beam() throws RecognitionException { beam_stack.push(new beam_scope()); Beam bObj = null; ((beam_scope)beam_stack.peek()).beamProperties = new HashMap<Object, Object>(); try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:445:2: ( BEAM ( beamLine )+ ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:445:4: BEAM ( beamLine )+ { match(input,BEAM,FOLLOW_BEAM_in_beam4541); // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:445:9: ( beamLine )+ int cnt12=0; loop12: do { int alt12=2; int LA12_0 = input.LA(1); if ( ((LA12_0 >= CIRCULAR && LA12_0 <= COLLIMATION)||LA12_0==ENERGY||LA12_0==FILE||(LA12_0 >= FLUX && LA12_0 <= HORIZONTAL)||LA12_0==PIXELSIZE||LA12_0==RECTANGULAR||LA12_0==TYPE||LA12_0==VERTICAL) ) { alt12=1; } switch (alt12) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:445:9: beamLine { pushFollow(FOLLOW_beamLine_in_beam4543); beamLine(); state._fsp } break; default : if ( cnt12 >= 1 ) break loop12; EarlyExitException eee = new EarlyExitException(12, input); throw eee; } cnt12++; } while (true); } bObj = beamFactory.createBeam(((beam_scope)beam_stack.peek()).beamType, ((beam_scope)beam_stack.peek()).beamProperties); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving beam_stack.pop(); } return bObj; } // $ANTLR end "beam" // $ANTLR start "beamLine" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:448:1: beamLine : ( TYPE a= STRING |b= beamFlux |c= beamFWHM |d= beamEnergy |e= beamCollimation |f= beamFile |g= beamPixelSize ); public final void beamLine() throws RecognitionException { Token a=null; Double b =null; InputfileParser.beamFWHM_return c =null; Double d =null; Map<Object, Object> e =null; String f =null; Map<Object, Object> g =null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:449:2: ( TYPE a= STRING |b= beamFlux |c= beamFWHM |d= beamEnergy |e= beamCollimation |f= beamFile |g= beamPixelSize ) int alt13=7; switch ( input.LA(1) ) { case TYPE: { alt13=1; } break; case FLUX: { alt13=2; } break; case FWHM: { alt13=3; } break; case ENERGY: { alt13=4; } break; case CIRCULAR: case COLLIMATION: case HORIZONTAL: case RECTANGULAR: case VERTICAL: { alt13=5; } break; case FILE: { alt13=6; } break; case PIXELSIZE: { alt13=7; } break; default: NoViableAltException nvae = new NoViableAltException("", 13, 0, input); throw nvae; } switch (alt13) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:449:4: TYPE a= STRING { match(input,TYPE,FOLLOW_TYPE_in_beamLine4582); a=(Token)match(input,STRING,FOLLOW_STRING_in_beamLine4586); ((beam_scope)beam_stack.peek()).beamType = (a!=null?a.getText():null); } break; case 2 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:450:4: b= beamFlux { pushFollow(FOLLOW_beamFlux_in_beamLine4604); b=beamFlux(); state._fsp ((beam_scope)beam_stack.peek()).beamProperties.put(Beam.BEAM_FLUX, b); } break; case 3 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:451:4: c= beamFWHM { pushFollow(FOLLOW_beamFWHM_in_beamLine4616); c=beamFWHM(); state._fsp ((beam_scope)beam_stack.peek()).beamProperties.put(Beam.BEAM_FWHM_X, (c!=null?c.x:null)); ((beam_scope)beam_stack.peek()).beamProperties.put(Beam.BEAM_FWHM_Y, (c!=null?c.y:null)); } break; case 4 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:453:4: d= beamEnergy { pushFollow(FOLLOW_beamEnergy_in_beamLine4628); d=beamEnergy(); state._fsp ((beam_scope)beam_stack.peek()).beamProperties.put(Beam.BEAM_ENERGY, d); } break; case 5 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:454:4: e= beamCollimation { pushFollow(FOLLOW_beamCollimation_in_beamLine4640); e=beamCollimation(); state._fsp if (e != null) { ((beam_scope)beam_stack.peek()).beamProperties.putAll(e); } } break; case 6 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:457:4: f= beamFile { pushFollow(FOLLOW_beamFile_in_beamLine4651); f=beamFile(); state._fsp ((beam_scope)beam_stack.peek()).beamProperties.put(Beam.BEAM_EXTFILE, f); } break; case 7 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:458:4: g= beamPixelSize { pushFollow(FOLLOW_beamPixelSize_in_beamLine4672); g=beamPixelSize(); state._fsp ((beam_scope)beam_stack.peek()).beamProperties.putAll(g); } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return ; } // $ANTLR end "beamLine" // $ANTLR start "beamFlux" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:461:1: beamFlux returns [Double flux] : FLUX a= FLOAT ; public final Double beamFlux() throws RecognitionException { Double flux = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:462:2: ( FLUX a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:462:4: FLUX a= FLOAT { match(input,FLUX,FOLLOW_FLUX_in_beamFlux4696); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_beamFlux4700); flux = Double.parseDouble((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return flux; } // $ANTLR end "beamFlux" public static class beamFWHM_return extends ParserRuleReturnScope { public Double x; public Double y; }; // $ANTLR start "beamFWHM" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:465:1: beamFWHM returns [Double x, Double y] : FWHM a= FLOAT b= FLOAT ; public final InputfileParser.beamFWHM_return beamFWHM() throws RecognitionException { InputfileParser.beamFWHM_return retval = new InputfileParser.beamFWHM_return(); retval.start = input.LT(1); Token a=null; Token b=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:466:2: ( FWHM a= FLOAT b= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:466:4: FWHM a= FLOAT b= FLOAT { match(input,FWHM,FOLLOW_FWHM_in_beamFWHM4742); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_beamFWHM4746); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_beamFWHM4750); retval.x = Double.parseDouble((a!=null?a.getText():null)); retval.y = Double.parseDouble((b!=null?b.getText():null)); } retval.stop = input.LT(-1); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "beamFWHM" // $ANTLR start "beamEnergy" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:469:1: beamEnergy returns [Double energy] : ENERGY a= FLOAT ( KEV )? ; public final Double beamEnergy() throws RecognitionException { Double energy = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:470:2: ( ENERGY a= FLOAT ( KEV )? ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:470:4: ENERGY a= FLOAT ( KEV )? { match(input,ENERGY,FOLLOW_ENERGY_in_beamEnergy4792); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_beamEnergy4796); energy = Double.parseDouble((a!=null?a.getText():null)); // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:471:2: ( KEV )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0==KEV) ) { alt14=1; } switch (alt14) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:471:4: KEV { match(input,KEV,FOLLOW_KEV_in_beamEnergy4803); } break; } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return energy; } // $ANTLR end "beamEnergy" // $ANTLR start "beamFile" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:476:1: beamFile returns [String filename] : FILE a= STRING ; public final String beamFile() throws RecognitionException { String filename = null; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:477:2: ( FILE a= STRING ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:477:4: FILE a= STRING { match(input,FILE,FOLLOW_FILE_in_beamFile4881); a=(Token)match(input,STRING,FOLLOW_STRING_in_beamFile4885); filename = (a!=null?a.getText():null); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return filename; } // $ANTLR end "beamFile" // $ANTLR start "beamPixelSize" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:481:1: beamPixelSize returns [Map<Object, Object> properties] : PIXELSIZE a= FLOAT b= FLOAT ; public final Map<Object, Object> beamPixelSize() throws RecognitionException { Map<Object, Object> properties = null; Token a=null; Token b=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:482:5: ( PIXELSIZE a= FLOAT b= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:482:7: PIXELSIZE a= FLOAT b= FLOAT { match(input,PIXELSIZE,FOLLOW_PIXELSIZE_in_beamPixelSize4932); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_beamPixelSize4936); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_beamPixelSize4940); properties = new HashMap<Object, Object>(); properties.put(Beam.BEAM_PIXSIZE_X, Double.parseDouble((a!=null?a.getText():null))); properties.put(Beam.BEAM_PIXSIZE_Y, Double.parseDouble((b!=null?b.getText():null))); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return properties; } // $ANTLR end "beamPixelSize" // $ANTLR start "beamCollimation" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:489:1: beamCollimation returns [Map<Object, Object> properties] : ( COLLIMATION | RECTANGULAR a= FLOAT b= FLOAT | CIRCULAR FLOAT | HORIZONTAL d= FLOAT | VERTICAL e= FLOAT ); public final Map<Object, Object> beamCollimation() throws RecognitionException { Map<Object, Object> properties = null; Token a=null; Token b=null; Token d=null; Token e=null; properties = new HashMap<Object, Object>(); try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:493:2: ( COLLIMATION | RECTANGULAR a= FLOAT b= FLOAT | CIRCULAR FLOAT | HORIZONTAL d= FLOAT | VERTICAL e= FLOAT ) int alt15=5; switch ( input.LA(1) ) { case COLLIMATION: { alt15=1; } break; case RECTANGULAR: { alt15=2; } break; case CIRCULAR: { alt15=3; } break; case HORIZONTAL: { alt15=4; } break; case VERTICAL: { alt15=5; } break; default: NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:493:4: COLLIMATION { match(input,COLLIMATION,FOLLOW_COLLIMATION_in_beamCollimation5019); } break; case 2 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:494:4: RECTANGULAR a= FLOAT b= FLOAT { match(input,RECTANGULAR,FOLLOW_RECTANGULAR_in_beamCollimation5025); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_beamCollimation5029); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_beamCollimation5033); properties.put(Beam.BEAM_COLL_H, Double.parseDouble((a!=null?a.getText():null))); properties.put(Beam.BEAM_COLL_V, Double.parseDouble((b!=null?b.getText():null))); } break; case 3 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:496:4: CIRCULAR FLOAT { match(input,CIRCULAR,FOLLOW_CIRCULAR_in_beamCollimation5040); match(input,FLOAT,FOLLOW_FLOAT_in_beamCollimation5042); } break; case 4 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:497:4: HORIZONTAL d= FLOAT { match(input,HORIZONTAL,FOLLOW_HORIZONTAL_in_beamCollimation5048); d=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_beamCollimation5052); properties.put(Beam.BEAM_COLL_H, Double.parseDouble((d!=null?d.getText():null))); } break; case 5 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:498:4: VERTICAL e= FLOAT { match(input,VERTICAL,FOLLOW_VERTICAL_in_beamCollimation5059); e=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_beamCollimation5063); properties.put(Beam.BEAM_COLL_V, Double.parseDouble((e!=null?e.getText():null))); } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return properties; } // $ANTLR end "beamCollimation" protected static class wedge_scope { Double angRes; Double startAng; Double endAng; Double expTime; Double offsetX; Double offsetY; Double offsetZ; Double translateX; Double translateY; Double translateZ; Double rotationOffset; } protected Stack<InputfileParser.wedge_scope> wedge_stack = new Stack<>(); // $ANTLR start "wedge" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:508:1: wedge returns [Wedge wObj] : WEDGE a= FLOAT b= FLOAT ( wedgeLine )+ ; public final Wedge wedge() throws RecognitionException { wedge_stack.push(new wedge_scope()); Wedge wObj = null; Token a=null; Token b=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:527:2: ( WEDGE a= FLOAT b= FLOAT ( wedgeLine )+ ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:527:4: WEDGE a= FLOAT b= FLOAT ( wedgeLine )+ { match(input,WEDGE,FOLLOW_WEDGE_in_wedge5376); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedge5380); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedge5384); ((wedge_scope)wedge_stack.peek()).startAng = Double.parseDouble((a!=null?a.getText():null)); ((wedge_scope)wedge_stack.peek()).endAng = Double.parseDouble((b!=null?b.getText():null)); // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:529:4: ( wedgeLine )+ int cnt16=0; loop16: do { int alt16=2; int LA16_0 = input.LA(1); if ( (LA16_0==ANGULARRESOLUTION||LA16_0==EXPOSURETIME||LA16_0==ROTAXBEAMOFFSET||LA16_0==STARTOFFSET||LA16_0==TRANSLATEPERDEGREE) ) { alt16=1; } switch (alt16) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:529:4: wedgeLine { pushFollow(FOLLOW_wedgeLine_in_wedge5391); wedgeLine(); state._fsp } break; default : if ( cnt16 >= 1 ) break loop16; EarlyExitException eee = new EarlyExitException(16, input); throw eee; } cnt16++; } while (true); } wObj = new Wedge(((wedge_scope)wedge_stack.peek()).angRes, ((wedge_scope)wedge_stack.peek()).startAng, ((wedge_scope)wedge_stack.peek()).endAng, ((wedge_scope)wedge_stack.peek()).expTime, ((wedge_scope)wedge_stack.peek()).offsetX, ((wedge_scope)wedge_stack.peek()).offsetY, ((wedge_scope)wedge_stack.peek()).offsetZ, ((wedge_scope)wedge_stack.peek()).translateX, ((wedge_scope)wedge_stack.peek()).translateY, ((wedge_scope)wedge_stack.peek()).translateZ, ((wedge_scope)wedge_stack.peek()).rotationOffset); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving wedge_stack.pop(); } return wObj; } // $ANTLR end "wedge" // $ANTLR start "wedgeLine" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:532:1: wedgeLine : (a= wedgeExposure |b= wedgeAngRes |c= wedgeStartOffset |d= wedgeTranslate |e= wedgeRotAxBeamOffset ); public final void wedgeLine() throws RecognitionException { double a =0.0; double b =0.0; InputfileParser.wedgeStartOffset_return c =null; InputfileParser.wedgeTranslate_return d =null; double e =0.0; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:533:2: (a= wedgeExposure |b= wedgeAngRes |c= wedgeStartOffset |d= wedgeTranslate |e= wedgeRotAxBeamOffset ) int alt17=5; switch ( input.LA(1) ) { case EXPOSURETIME: { alt17=1; } break; case ANGULARRESOLUTION: { alt17=2; } break; case STARTOFFSET: { alt17=3; } break; case TRANSLATEPERDEGREE: { alt17=4; } break; case ROTAXBEAMOFFSET: { alt17=5; } break; default: NoViableAltException nvae = new NoViableAltException("", 17, 0, input); throw nvae; } switch (alt17) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:533:4: a= wedgeExposure { pushFollow(FOLLOW_wedgeExposure_in_wedgeLine5435); a=wedgeExposure(); state._fsp ((wedge_scope)wedge_stack.peek()).expTime =a; } break; case 2 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:534:4: b= wedgeAngRes { pushFollow(FOLLOW_wedgeAngRes_in_wedgeLine5445); b=wedgeAngRes(); state._fsp ((wedge_scope)wedge_stack.peek()).angRes =b; } break; case 3 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:535:4: c= wedgeStartOffset { pushFollow(FOLLOW_wedgeStartOffset_in_wedgeLine5456); c=wedgeStartOffset(); state._fsp ((wedge_scope)wedge_stack.peek()).offsetX =(c!=null?c.x:null); ((wedge_scope)wedge_stack.peek()).offsetY =(c!=null?c.y:null); ((wedge_scope)wedge_stack.peek()).offsetZ =(c!=null?c.z:null); } break; case 4 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:538:4: d= wedgeTranslate { pushFollow(FOLLOW_wedgeTranslate_in_wedgeLine5466); d=wedgeTranslate(); state._fsp ((wedge_scope)wedge_stack.peek()).translateX =(d!=null?d.x:null); ((wedge_scope)wedge_stack.peek()).translateY =(d!=null?d.y:null); ((wedge_scope)wedge_stack.peek()).translateZ =(d!=null?d.z:null); } break; case 5 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:541:4: e= wedgeRotAxBeamOffset { pushFollow(FOLLOW_wedgeRotAxBeamOffset_in_wedgeLine5476); e=wedgeRotAxBeamOffset(); state._fsp ((wedge_scope)wedge_stack.peek()).rotationOffset =e; } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return ; } // $ANTLR end "wedgeLine" // $ANTLR start "wedgeExposure" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:544:1: wedgeExposure returns [double value] : EXPOSURETIME a= FLOAT ; public final double wedgeExposure() throws RecognitionException { double value = 0.0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:545:2: ( EXPOSURETIME a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:545:4: EXPOSURETIME a= FLOAT { match(input,EXPOSURETIME,FOLLOW_EXPOSURETIME_in_wedgeExposure5493); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedgeExposure5497); value = Double.parseDouble((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return value; } // $ANTLR end "wedgeExposure" // $ANTLR start "wedgeAngRes" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:548:1: wedgeAngRes returns [double res] : ANGULARRESOLUTION a= FLOAT ; public final double wedgeAngRes() throws RecognitionException { double res = 0.0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:549:2: ( ANGULARRESOLUTION a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:549:4: ANGULARRESOLUTION a= FLOAT { match(input,ANGULARRESOLUTION,FOLLOW_ANGULARRESOLUTION_in_wedgeAngRes5579); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedgeAngRes5583); res = Double.parseDouble((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return res; } // $ANTLR end "wedgeAngRes" public static class wedgeStartOffset_return extends ParserRuleReturnScope { public Double x; public Double y; public Double z; }; // $ANTLR start "wedgeStartOffset" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:552:1: wedgeStartOffset returns [Double x, Double y, Double z] : STARTOFFSET a= FLOAT b= FLOAT (c= FLOAT )? ; public final InputfileParser.wedgeStartOffset_return wedgeStartOffset() throws RecognitionException { InputfileParser.wedgeStartOffset_return retval = new InputfileParser.wedgeStartOffset_return(); retval.start = input.LT(1); Token a=null; Token b=null; Token c=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:553:2: ( STARTOFFSET a= FLOAT b= FLOAT (c= FLOAT )? ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:553:4: STARTOFFSET a= FLOAT b= FLOAT (c= FLOAT )? { match(input,STARTOFFSET,FOLLOW_STARTOFFSET_in_wedgeStartOffset5690); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedgeStartOffset5694); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedgeStartOffset5698); retval.x = Double.parseDouble((a!=null?a.getText():null)); retval.y = Double.parseDouble((b!=null?b.getText():null)); // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:554:17: (c= FLOAT )? int alt18=2; int LA18_0 = input.LA(1); if ( (LA18_0==FLOAT) ) { alt18=1; } switch (alt18) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:554:17: c= FLOAT { c=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedgeStartOffset5719); } break; } retval.z = ((c!=null?c.getText():null) == null) ? null : Double.parseDouble((c!=null?c.getText():null)); } retval.stop = input.LT(-1); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "wedgeStartOffset" public static class wedgeTranslate_return extends ParserRuleReturnScope { public Double x; public Double y; public Double z; }; // $ANTLR start "wedgeTranslate" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:558:1: wedgeTranslate returns [Double x, Double y, Double z] : TRANSLATEPERDEGREE a= FLOAT b= FLOAT (c= FLOAT )? ; public final InputfileParser.wedgeTranslate_return wedgeTranslate() throws RecognitionException { InputfileParser.wedgeTranslate_return retval = new InputfileParser.wedgeTranslate_return(); retval.start = input.LT(1); Token a=null; Token b=null; Token c=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:559:2: ( TRANSLATEPERDEGREE a= FLOAT b= FLOAT (c= FLOAT )? ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:559:4: TRANSLATEPERDEGREE a= FLOAT b= FLOAT (c= FLOAT )? { match(input,TRANSLATEPERDEGREE,FOLLOW_TRANSLATEPERDEGREE_in_wedgeTranslate5813); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedgeTranslate5817); b=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedgeTranslate5821); retval.x = Double.parseDouble((a!=null?a.getText():null)); retval.y = Double.parseDouble((b!=null?b.getText():null)); // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:560:24: (c= FLOAT )? int alt19=2; int LA19_0 = input.LA(1); if ( (LA19_0==FLOAT) ) { alt19=1; } switch (alt19) { case 1 : // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:560:24: c= FLOAT { c=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedgeTranslate5849); } break; } retval.z = ((c!=null?c.getText():null) == null) ? null : Double.parseDouble((c!=null?c.getText():null)); } retval.stop = input.LT(-1); } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "wedgeTranslate" // $ANTLR start "wedgeRotAxBeamOffset" // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:564:1: wedgeRotAxBeamOffset returns [double delta] : ROTAXBEAMOFFSET a= FLOAT ; public final double wedgeRotAxBeamOffset() throws RecognitionException { double delta = 0.0; Token a=null; try { // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:565:2: ( ROTAXBEAMOFFSET a= FLOAT ) // C:\\Users\\Josh\\git\\RADDOSE-3D\\lib\\antlrworks-parsergenerator\\Inputfile.g:565:4: ROTAXBEAMOFFSET a= FLOAT { match(input,ROTAXBEAMOFFSET,FOLLOW_ROTAXBEAMOFFSET_in_wedgeRotAxBeamOffset5985); a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_wedgeRotAxBeamOffset5989); delta = Double.parseDouble((a!=null?a.getText():null)); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return delta; } // $ANTLR end "wedgeRotAxBeamOffset" // Delegated rules public static final BitSet FOLLOW_crystal_in_configfile47 = new BitSet(new long[]{0x0000000000100200L,0x0000000000002000L}); public static final BitSet FOLLOW_wedge_in_configfile65 = new BitSet(new long[]{0x0000000000100200L,0x0000000000002000L}); public static final BitSet FOLLOW_beam_in_configfile85 = new BitSet(new long[]{0x0000000000100200L,0x0000000000002000L}); public static final BitSet FOLLOW_EOF_in_configfile105 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_CRYSTAL_in_crystal134 = new BitSet(new long[]{0x07B7AE04036F8C70L,0x0000000000004C6AL}); public static final BitSet FOLLOW_crystalLine_in_crystal136 = new BitSet(new long[]{0x07B7AE04036F8C72L,0x0000000000004C6AL}); public static final BitSet FOLLOW_crystalType_in_crystalLine192 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_crystalDDM_in_crystalLine203 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_crystalCoefcalc_in_crystalLine215 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_crystalDim_in_crystalLine225 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_crystalPPM_in_crystalLine236 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_crystalAngP_in_crystalLine247 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_crystalAngL_in_crystalLine258 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_crystalDecayParam_in_crystalLine269 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_containerThickness_in_crystalLine279 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_containerDensity_in_crystalLine289 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_crystalContainerMaterial_in_crystalLine299 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_containerMaterialMixture_in_crystalLine308 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_unitcell_in_crystalLine317 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_nummonomers_in_crystalLine328 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_numresidues_in_crystalLine339 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_numRNA_in_crystalLine350 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_numDNA_in_crystalLine363 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_heavyProteinAtoms_in_crystalLine376 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_heavySolutionConc_in_crystalLine385 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_solventFraction_in_crystalLine394 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_pdb_in_crystalLine404 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_wireframeType_in_crystalLine417 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_modelFile_in_crystalLine428 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_calculatePEEscape_in_crystalLine440 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_proteinConcentration_in_crystalLine450 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_containerMaterialElements_in_crystalLine459 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_sequenceFile_in_crystalLine468 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_calculateFLEscape_in_crystalLine481 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_flResolution_in_crystalLine491 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_peResolution_in_crystalLine502 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_TYPE_in_crystalType523 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L}); public static final BitSet FOLLOW_STRING_in_crystalType527 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_crystalDDM569 = new BitSet(new long[]{0x0000018000000000L,0x0000000000000010L}); public static final BitSet FOLLOW_crystalDDMKeyword_in_crystalDDM581 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_SIMPLE_in_crystalDDMKeyword729 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_LINEAR_in_crystalDDMKeyword736 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_LEAL_in_crystalDDMKeyword743 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_DECAYPARAM_in_crystalDecayParam863 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_crystalDecayParam867 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_crystalDecayParam871 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_crystalDecayParam875 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_ABSCOEFCALC_in_crystalCoefcalc947 = new BitSet(new long[]{0x9808000004800100L,0x0000000000000005L}); public static final BitSet FOLLOW_crystalCoefcalcKeyword_in_crystalCoefcalc951 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_DUMMY_in_crystalCoefcalcKeyword1030 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_AVERAGE_in_crystalCoefcalcKeyword1040 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_DEFAULT_in_crystalCoefcalcKeyword1048 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_RDJAVA_in_crystalCoefcalcKeyword1056 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_RDFORTAN_in_crystalCoefcalcKeyword1063 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_PDB_in_crystalCoefcalcKeyword1070 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_SAXS_in_crystalCoefcalcKeyword1080 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_SEQUENCE_in_crystalCoefcalcKeyword1088 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_SAXSSEQ_in_crystalCoefcalcKeyword1095 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_DIMENSION_in_crystalDim1419 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_crystalDim1432 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_crystalDim1436 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_crystalDim1440 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_FLOAT_in_crystalDim1452 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_crystalDim1456 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_FLOAT_in_crystalDim1468 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_ANGLEP_in_crystalAngP1545 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_crystalAngP1549 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_ANGLEL_in_crystalAngL1604 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_crystalAngL1608 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_PIXELSPERMICRON_in_crystalPPM1662 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_crystalPPM1664 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_UNITCELL_in_unitcell1762 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_unitcell1766 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_unitcell1770 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_unitcell1774 = new BitSet(new long[]{0x0000000200000002L}); public static final BitSet FOLLOW_FLOAT_in_unitcell1789 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_unitcell1793 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_unitcell1797 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_proteinConcentration1875 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_proteinConcentration1885 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_NUMMONOMERS_in_nummonomers2067 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_nummonomers2071 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_NUMRESIDUES_in_numresidues2148 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_numresidues2152 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_NUMRNA_in_numRNA2230 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_numRNA2234 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_NUMDNA_in_numDNA2287 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_numDNA2291 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_PROTEINHEAVYATOMS_in_heavyProteinAtoms2347 = new BitSet(new long[]{0x0000000008000000L}); public static final BitSet FOLLOW_ELEMENT_in_heavyProteinAtoms2352 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_heavyProteinAtoms2356 = new BitSet(new long[]{0x0000000008000002L}); public static final BitSet FOLLOW_SOLVENTHEAVYCONC_in_heavySolutionConc2503 = new BitSet(new long[]{0x0000000008000000L}); public static final BitSet FOLLOW_ELEMENT_in_heavySolutionConc2508 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_heavySolutionConc2512 = new BitSet(new long[]{0x0000000008000002L}); public static final BitSet FOLLOW_SOLVENTFRACTION_in_solventFraction2618 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_solventFraction2622 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_PDBNAME_in_pdb2719 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L}); public static final BitSet FOLLOW_STRING_in_pdb2723 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_WIREFRAMETYPE_in_wireframeType2760 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L}); public static final BitSet FOLLOW_STRING_in_wireframeType2764 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_MODELFILE_in_modelFile2852 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L}); public static final BitSet FOLLOW_STRING_in_modelFile2856 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_CALCULATEPEESCAPE_in_calculatePEEscape2923 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L}); public static final BitSet FOLLOW_STRING_in_calculatePEEscape2927 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_crystalContainerMaterial3039 = new BitSet(new long[]{0x0000500010000000L}); public static final BitSet FOLLOW_crystalContainerKeyword_in_crystalContainerMaterial3051 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_NONE_in_crystalContainerKeyword3244 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_MIXTURE_in_crystalContainerKeyword3253 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_ELEMENTAL_in_crystalContainerKeyword3261 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_CONTAINERTHICKNESS_in_containerThickness3401 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_containerThickness3405 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_containerMaterialMixture3516 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L}); public static final BitSet FOLLOW_STRING_in_containerMaterialMixture3526 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_containerMaterialElements3751 = new BitSet(new long[]{0x0000000008000000L}); public static final BitSet FOLLOW_ELEMENT_in_containerMaterialElements3762 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_containerMaterialElements3766 = new BitSet(new long[]{0x0000000008000002L}); public static final BitSet FOLLOW_CONTAINERDENSITY_in_containerDensity4001 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_containerDensity4005 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_sequenceFile4106 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L}); public static final BitSet FOLLOW_STRING_in_sequenceFile4116 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_CALCULATEFLESCAPE_in_calculateFLEscape4239 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L}); public static final BitSet FOLLOW_STRING_in_calculateFLEscape4243 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_FLRESOLUTION_in_flResolution4355 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_flResolution4359 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_PERESOLUTION_in_peResolution4441 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_peResolution4445 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_BEAM_in_beam4541 = new BitSet(new long[]{0x2040003920003000L,0x0000000000001400L}); public static final BitSet FOLLOW_beamLine_in_beam4543 = new BitSet(new long[]{0x2040003920003002L,0x0000000000001400L}); public static final BitSet FOLLOW_TYPE_in_beamLine4582 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L}); public static final BitSet FOLLOW_STRING_in_beamLine4586 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_beamFlux_in_beamLine4604 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_beamFWHM_in_beamLine4616 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_beamEnergy_in_beamLine4628 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_beamCollimation_in_beamLine4640 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_beamFile_in_beamLine4651 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_beamPixelSize_in_beamLine4672 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_FLUX_in_beamFlux4696 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamFlux4700 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_FWHM_in_beamFWHM4742 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamFWHM4746 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamFWHM4750 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_ENERGY_in_beamEnergy4792 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamEnergy4796 = new BitSet(new long[]{0x0000004000000002L}); public static final BitSet FOLLOW_KEV_in_beamEnergy4803 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_FILE_in_beamFile4881 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L}); public static final BitSet FOLLOW_STRING_in_beamFile4885 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_PIXELSIZE_in_beamPixelSize4932 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamPixelSize4936 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamPixelSize4940 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_COLLIMATION_in_beamCollimation5019 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_RECTANGULAR_in_beamCollimation5025 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamCollimation5029 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamCollimation5033 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_CIRCULAR_in_beamCollimation5040 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamCollimation5042 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_HORIZONTAL_in_beamCollimation5048 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamCollimation5052 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_VERTICAL_in_beamCollimation5059 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_beamCollimation5063 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_WEDGE_in_wedge5376 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_wedge5380 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_wedge5384 = new BitSet(new long[]{0x4000000080000080L,0x0000000000000280L}); public static final BitSet FOLLOW_wedgeLine_in_wedge5391 = new BitSet(new long[]{0x4000000080000082L,0x0000000000000280L}); public static final BitSet FOLLOW_wedgeExposure_in_wedgeLine5435 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_wedgeAngRes_in_wedgeLine5445 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_wedgeStartOffset_in_wedgeLine5456 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_wedgeTranslate_in_wedgeLine5466 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_wedgeRotAxBeamOffset_in_wedgeLine5476 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_EXPOSURETIME_in_wedgeExposure5493 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_wedgeExposure5497 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_ANGULARRESOLUTION_in_wedgeAngRes5579 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_wedgeAngRes5583 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_STARTOFFSET_in_wedgeStartOffset5690 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_wedgeStartOffset5694 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_wedgeStartOffset5698 = new BitSet(new long[]{0x0000000200000002L}); public static final BitSet FOLLOW_FLOAT_in_wedgeStartOffset5719 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_TRANSLATEPERDEGREE_in_wedgeTranslate5813 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_wedgeTranslate5817 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_wedgeTranslate5821 = new BitSet(new long[]{0x0000000200000002L}); public static final BitSet FOLLOW_FLOAT_in_wedgeTranslate5849 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_ROTAXBEAMOFFSET_in_wedgeRotAxBeamOffset5985 = new BitSet(new long[]{0x0000000200000000L}); public static final BitSet FOLLOW_FLOAT_in_wedgeRotAxBeamOffset5989 = new BitSet(new long[]{0x0000000000000002L}); }
package it.unibz.inf.ontop.iq.node.impl; import com.google.common.collect.*; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import it.unibz.inf.ontop.evaluator.ExpressionEvaluator; import it.unibz.inf.ontop.evaluator.TermNullabilityEvaluator; import it.unibz.inf.ontop.exception.MinorOntopInternalBugException; import it.unibz.inf.ontop.injection.IntermediateQueryFactory; import it.unibz.inf.ontop.injection.OntopModelSettings; import it.unibz.inf.ontop.iq.IQProperties; import it.unibz.inf.ontop.iq.IQTree; import it.unibz.inf.ontop.iq.IntermediateQuery; import it.unibz.inf.ontop.iq.UnaryIQTree; import it.unibz.inf.ontop.iq.exception.InvalidIntermediateQueryException; import it.unibz.inf.ontop.iq.exception.InvalidQueryNodeException; import it.unibz.inf.ontop.iq.exception.QueryNodeTransformationException; import it.unibz.inf.ontop.iq.node.*; import it.unibz.inf.ontop.iq.transform.IQTransformer; import it.unibz.inf.ontop.iq.transform.node.HeterogeneousQueryNodeTransformer; import it.unibz.inf.ontop.iq.transform.node.HomogeneousQueryNodeTransformer; import it.unibz.inf.ontop.model.term.functionsymbol.FunctionSymbol.FunctionalTermNullability; import it.unibz.inf.ontop.model.term.impl.ImmutabilityTools; import it.unibz.inf.ontop.substitution.SubstitutionFactory; import it.unibz.inf.ontop.substitution.impl.ImmutableSubstitutionTools; import it.unibz.inf.ontop.substitution.impl.ImmutableUnificationTools; import it.unibz.inf.ontop.model.term.*; import it.unibz.inf.ontop.substitution.ImmutableSubstitution; import it.unibz.inf.ontop.utils.CoreUtilsFactory; import it.unibz.inf.ontop.utils.ImmutableCollectors; import it.unibz.inf.ontop.utils.VariableGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.Optional; import java.util.stream.IntStream; import java.util.stream.Stream; import static it.unibz.inf.ontop.model.term.functionsymbol.ExpressionOperation.EQ; @SuppressWarnings({"OptionalUsedAsFieldOrParameterType", "BindingAnnotationWithoutInject"}) public class ConstructionNodeImpl extends CompositeQueryNodeImpl implements ConstructionNode { private static Logger LOGGER = LoggerFactory.getLogger(ConstructionNodeImpl.class); @SuppressWarnings("FieldCanBeLocal") private final TermNullabilityEvaluator nullabilityEvaluator; private final ImmutableSet<Variable> projectedVariables; private final ImmutableSubstitution<ImmutableTerm> substitution; private final ImmutableSet<Variable> childVariables; private final ImmutableUnificationTools unificationTools; private final ConstructionNodeTools constructionNodeTools; private final ImmutableSubstitutionTools substitutionTools; private final SubstitutionFactory substitutionFactory; private final IntermediateQueryFactory iqFactory; private static final String CONSTRUCTION_NODE_STR = "CONSTRUCT"; private final TermFactory termFactory; private final ValueConstant nullValue; private final ImmutabilityTools immutabilityTools; private final ExpressionEvaluator expressionEvaluator; private final CoreUtilsFactory coreUtilsFactory; @AssistedInject private ConstructionNodeImpl(@Assisted ImmutableSet<Variable> projectedVariables, @Assisted ImmutableSubstitution<ImmutableTerm> substitution, TermNullabilityEvaluator nullabilityEvaluator, ImmutableUnificationTools unificationTools, ConstructionNodeTools constructionNodeTools, ImmutableSubstitutionTools substitutionTools, SubstitutionFactory substitutionFactory, TermFactory termFactory, IntermediateQueryFactory iqFactory, ImmutabilityTools immutabilityTools, ExpressionEvaluator expressionEvaluator, CoreUtilsFactory coreUtilsFactory, OntopModelSettings settings) { super(substitutionFactory, iqFactory); this.projectedVariables = projectedVariables; this.substitution = substitution; this.nullabilityEvaluator = nullabilityEvaluator; this.unificationTools = unificationTools; this.constructionNodeTools = constructionNodeTools; this.substitutionTools = substitutionTools; this.substitutionFactory = substitutionFactory; this.termFactory = termFactory; this.nullValue = termFactory.getNullConstant(); this.iqFactory = iqFactory; this.immutabilityTools = immutabilityTools; this.expressionEvaluator = expressionEvaluator; this.coreUtilsFactory = coreUtilsFactory; this.childVariables = extractChildVariables(projectedVariables, substitution); if (settings.isTestModeEnabled()) validateNode(); } /** * Validates the node independently of its child */ private void validateNode() throws InvalidQueryNodeException { ImmutableSet<Variable> substitutionDomain = substitution.getDomain(); // The substitution domain must be a subset of the projectedVariables if (!projectedVariables.containsAll(substitutionDomain)) { throw new InvalidQueryNodeException("ConstructionNode: all the domain variables " + "of the substitution must be projected.\n" + toString()); } // The variables contained in the domain and in the range of the substitution must be disjoint if (substitutionDomain.stream() .anyMatch(childVariables::contains)) { throw new InvalidQueryNodeException("ConstructionNode: variables defined by the substitution cannot " + "be used for defining other variables.\n" + toString()); } // Substitution to non-projected variables is incorrect if (substitution.getImmutableMap().values().stream() .filter(v -> v instanceof Variable) .map(v -> (Variable) v) .anyMatch(v -> !projectedVariables.contains(v))) { throw new InvalidQueryNodeException( "ConstructionNode: substituting a variable " + "by a non-projected variable is incorrect.\n" + toString()); } } /** * Without modifiers nor substitution. */ @AssistedInject private ConstructionNodeImpl(@Assisted ImmutableSet<Variable> projectedVariables, TermNullabilityEvaluator nullabilityEvaluator, ImmutableUnificationTools unificationTools, ConstructionNodeTools constructionNodeTools, ImmutableSubstitutionTools substitutionTools, SubstitutionFactory substitutionFactory, TermFactory termFactory, IntermediateQueryFactory iqFactory, ImmutabilityTools immutabilityTools, ExpressionEvaluator expressionEvaluator, CoreUtilsFactory coreUtilsFactory) { super(substitutionFactory, iqFactory); this.projectedVariables = projectedVariables; this.nullabilityEvaluator = nullabilityEvaluator; this.unificationTools = unificationTools; this.substitutionTools = substitutionTools; this.substitution = substitutionFactory.getSubstitution(); this.termFactory = termFactory; this.iqFactory = iqFactory; this.immutabilityTools = immutabilityTools; this.expressionEvaluator = expressionEvaluator; this.constructionNodeTools = constructionNodeTools; this.substitutionFactory = substitutionFactory; this.nullValue = termFactory.getNullConstant(); this.childVariables = extractChildVariables(projectedVariables, substitution); this.coreUtilsFactory = coreUtilsFactory; validateNode(); } private static ImmutableSet<Variable> extractChildVariables(ImmutableSet<Variable> projectedVariables, ImmutableSubstitution<ImmutableTerm> substitution) { ImmutableSet<Variable> variableDefinedByBindings = substitution.getDomain(); Stream<Variable> variablesRequiredByBindings = substitution.getImmutableMap().values().stream() .flatMap(ImmutableTerm::getVariableStream); //return only the variables that are also used in the bindings for the child of the construction node return Stream.concat(projectedVariables.stream(), variablesRequiredByBindings) .filter(v -> !variableDefinedByBindings.contains(v)) .collect(ImmutableCollectors.toSet()); } @Override public ImmutableSet<Variable> getVariables() { return projectedVariables; } @Override public ImmutableSubstitution<ImmutableTerm> getSubstitution() { return substitution; } /** * Immutable fields, can be shared. */ @Override public ConstructionNode clone() { return iqFactory.createConstructionNode(projectedVariables, substitution); } @Override public ConstructionNode acceptNodeTransformer(HomogeneousQueryNodeTransformer transformer) throws QueryNodeTransformationException { return transformer.transform(this); } @Override public ImmutableSet<Variable> getChildVariables() { return childVariables; } @Override public NodeTransformationProposal acceptNodeTransformer(HeterogeneousQueryNodeTransformer transformer) { return transformer.transform(this); } @Override public ImmutableSet<Variable> getLocalVariables() { ImmutableSet.Builder<Variable> collectedVariableBuilder = ImmutableSet.builder(); collectedVariableBuilder.addAll(projectedVariables); ImmutableMap<Variable, ImmutableTerm> substitutionMap = substitution.getImmutableMap(); collectedVariableBuilder.addAll(substitutionMap.keySet()); for (ImmutableTerm term : substitutionMap.values()) { if (term instanceof Variable) { collectedVariableBuilder.add((Variable)term); } else if (term instanceof ImmutableFunctionalTerm) { collectedVariableBuilder.addAll(((ImmutableFunctionalTerm)term).getVariables()); } } return collectedVariableBuilder.build(); } @Override public boolean isVariableNullable(IntermediateQuery query, Variable variable) { if (getChildVariables().contains(variable)) return isChildVariableNullable(query, variable); return Optional.ofNullable(substitution.get(variable)) .map(t -> isTermNullable(query, t)) .orElseThrow(() -> new IllegalArgumentException("The variable " + variable + " is not projected by " + this)); } @Override public VariableNullability getVariableNullability(IQTree child) { VariableNullability childNullability = child.getVariableNullability(); VariableGenerator variableGenerator = coreUtilsFactory.createVariableGenerator( Sets.union(projectedVariables, child.getVariables()).immutableCopy()); /* * The substitutions are split by nesting level */ VariableNullability nullabilityBeforeProjectingOut = splitSubstitution(substitution, variableGenerator) .reduce(childNullability, (n, s) -> updateVariableNullability(s, n), (n1, n2) -> { throw new MinorOntopInternalBugException("vns are not expected to be combined"); }); /* * Projects away irrelevant variables */ ImmutableSet<ImmutableSet<Variable>> nullableGroups = nullabilityBeforeProjectingOut.getNullableGroups().stream() .map(g -> g.stream() .filter(projectedVariables::contains) .collect(ImmutableCollectors.toSet())) .filter(g -> !g.isEmpty()) .collect(ImmutableCollectors.toSet()); return new VariableNullabilityImpl(nullableGroups); } /* * TODO: explain */ private Stream<ImmutableSubstitution<ImmutableTerm>> splitSubstitution( ImmutableSubstitution<ImmutableTerm> substitution, VariableGenerator variableGenerator) { ImmutableMultimap<Variable, Integer> functionSubTermMultimap = substitution.getImmutableMap().entrySet().stream() .filter(e -> e.getValue() instanceof ImmutableFunctionalTerm) .flatMap(e -> { ImmutableList<? extends ImmutableTerm> subTerms = ((ImmutableFunctionalTerm) e.getValue()).getTerms(); return IntStream.range(0, subTerms.size()) .filter(i -> subTerms.get(i) instanceof ImmutableFunctionalTerm) .boxed() .map(i -> Maps.immutableEntry(e.getKey(), i)); }) .collect(ImmutableCollectors.toMultimap()); if (functionSubTermMultimap.isEmpty()) return Stream.of(substitution); ImmutableTable<Variable, Integer, Variable> subTermNames = functionSubTermMultimap.entries().stream() .map(e -> Tables.immutableCell(e.getKey(), e.getValue(), variableGenerator.generateNewVariable())) .collect(ImmutableCollectors.toTable()); ImmutableMap<Variable, ImmutableTerm> parentSubstitutionMap = substitution.getImmutableMap().entrySet().stream() .map(e -> Optional.ofNullable(functionSubTermMultimap.get(e.getKey())) .map(indexes -> { Variable v = e.getKey(); ImmutableFunctionalTerm def = (ImmutableFunctionalTerm) substitution.get(v); ImmutableList<ImmutableTerm> newArgs = IntStream.range(0, def.getArity()) .boxed() .map(i -> Optional.ofNullable((ImmutableTerm) subTermNames.get(v, i)) .orElseGet(() -> def.getTerm(i))) .collect(ImmutableCollectors.toList()); ImmutableTerm newDef = termFactory.getImmutableFunctionalTerm( def.getFunctionSymbol(), newArgs); return Maps.immutableEntry(v, newDef); }) .orElse(e)) .collect(ImmutableCollectors.toMap()); ImmutableSubstitution<ImmutableTerm> parentSubstitution = substitutionFactory.getSubstitution(parentSubstitutionMap); ImmutableSubstitution<ImmutableTerm> childSubstitution = substitutionFactory.getSubstitution( subTermNames.cellSet().stream() .collect(ImmutableCollectors.toMap( Table.Cell::getValue, c -> ((ImmutableFunctionalTerm) substitution.get(c.getRowKey())).getTerm(c.getColumnKey())))); return Stream.concat( // Recursive splitSubstitution(childSubstitution, variableGenerator), Stream.of(parentSubstitution)); } private VariableNullability updateVariableNullability( ImmutableSubstitution<ImmutableTerm> nonNestedSubstitution, VariableNullability childNullability) { // TODO: find a better name ImmutableMap<Variable, Variable> nullabilityBindings = nonNestedSubstitution.getImmutableMap().entrySet().stream() .flatMap(e -> evaluateTermNullability(e.getValue(), childNullability, e.getKey()) .map(Stream::of) .orElseGet(Stream::empty)) .collect(ImmutableCollectors.toMap()); return childNullability.appendNewVariables(nullabilityBindings); } private Optional<Map.Entry<Variable, Variable>> evaluateTermNullability( ImmutableTerm term, VariableNullability childNullability, Variable key) { if (term instanceof Constant) { return term.equals(nullValue) ? Optional.of(Maps.immutableEntry(key, key)) : Optional.empty(); } else if (term instanceof Variable) return Optional.of((Variable) term) .filter(childNullability::isPossiblyNullable) .map(v -> Maps.immutableEntry(key, v)); else { ImmutableFunctionalTerm functionalTerm = (ImmutableFunctionalTerm) term; FunctionalTermNullability results = functionalTerm.getFunctionSymbol().evaluateNullability( (ImmutableList<NonFunctionalTerm>) functionalTerm.getTerms(), childNullability); return results.isNullable() ? Optional.of(results.getBoundVariable() .map(v -> Maps.immutableEntry(key, v)) .orElseGet(() -> Maps.immutableEntry(key, key))) : Optional.empty(); } } @Override public boolean isConstructed(Variable variable, IQTree child) { return substitution.isDefining(variable) || (getChildVariables().contains(variable) && child.isConstructed(variable)); } @Override public IQTree liftIncompatibleDefinitions(Variable variable, IQTree child) { if (!childVariables.contains(variable)) { return iqFactory.createUnaryIQTree(this, child); } IQTree newChild = child.liftIncompatibleDefinitions(variable); QueryNode newChildRoot = newChild.getRootNode(); /* * Lift the union above the construction node */ if ((newChildRoot instanceof UnionNode) && ((UnionNode) newChildRoot).hasAChildWithLiftableDefinition(variable, newChild.getChildren())) { ImmutableList<IQTree> grandChildren = newChild.getChildren(); ImmutableList<IQTree> newChildren = grandChildren.stream() .map(c -> (IQTree) iqFactory.createUnaryIQTree(this, c)) .collect(ImmutableCollectors.toList()); UnionNode newUnionNode = iqFactory.createUnionNode(getVariables()); return iqFactory.createNaryIQTree(newUnionNode, newChildren); } return iqFactory.createUnaryIQTree(this, newChild); } @Override public IQTree propagateDownConstraint(ImmutableExpression constraint, IQTree child) { try { Optional<ImmutableExpression> childConstraint = computeChildConstraint(substitution, Optional.of(constraint)); IQTree newChild = childConstraint .map(child::propagateDownConstraint) .orElse(child); return iqFactory.createUnaryIQTree(this, newChild); } catch (EmptyTreeException e) { return iqFactory.createEmptyNode(projectedVariables); } } @Override public IQTree acceptTransformer(IQTree tree, IQTransformer transformer, IQTree child) { return transformer.transformConstruction(tree,this, child); } @Override public void validateNode(IQTree child) throws InvalidQueryNodeException, InvalidIntermediateQueryException { validateNode(); ImmutableSet<Variable> requiredChildVariables = getChildVariables(); ImmutableSet<Variable> childVariables = child.getVariables(); if (!childVariables.containsAll(requiredChildVariables)) { throw new InvalidIntermediateQueryException("This child " + child + " does not project all the variables " + "required by the CONSTRUCTION node (" + requiredChildVariables + ")\n" + this); } } @Override public ImmutableSet<ImmutableSubstitution<NonVariableTerm>> getPossibleVariableDefinitions(IQTree child) { ImmutableSet<ImmutableSubstitution<NonVariableTerm>> childDefs = child.getPossibleVariableDefinitions(); if (childDefs.isEmpty()) { ImmutableSubstitution<NonVariableTerm> def = substitution.getNonVariableTermFragment(); return def.isEmpty() ? ImmutableSet.of() : ImmutableSet.of(def); } return childDefs.stream() .map(childDef -> childDef.composeWith(substitution)) .map(s -> s.reduceDomainToIntersectionWith(projectedVariables)) .map(ImmutableSubstitution::getNonVariableTermFragment) .collect(ImmutableCollectors.toSet()); } /** * TODO: involve the function to reduce the number of false positive */ private boolean isNullable(ImmutableTerm term, ImmutableSet<Variable> nullableChildVariables) { if (term instanceof Constant) return term.equals(termFactory.getNullConstant()); // TODO: improve this else if (term.isGround()) return false; // TODO: improve this return term.getVariableStream() .anyMatch(nullableChildVariables::contains); } private boolean isChildVariableNullable(IntermediateQuery query, Variable variable) { return query.getFirstChild(this) .map(c -> c.isVariableNullable(query, variable)) .orElseThrow(() -> new InvalidIntermediateQueryException( "A construction node with child variables must have a child")); } private boolean isTermNullable(IntermediateQuery query, ImmutableTerm substitutionValue) { if (substitutionValue instanceof ImmutableFunctionalTerm) { ImmutableSet<Variable> nullableVariables = substitutionValue.getVariableStream() .filter(v -> isChildVariableNullable(query, v)) .collect(ImmutableCollectors.toSet()); return nullabilityEvaluator.isNullable(substitutionValue, nullableVariables); } else if (substitutionValue instanceof Constant) { return substitutionValue.equals(nullValue); } else if (substitutionValue instanceof Variable) { return isChildVariableNullable(query, (Variable)substitutionValue); } else { throw new IllegalStateException("Unexpected immutable term"); } } @Override public boolean isSyntacticallyEquivalentTo(QueryNode node) { return Optional.of(node) .filter(n -> n instanceof ConstructionNode) .map(n -> (ConstructionNode) n) .filter(n -> n.getVariables().equals(projectedVariables)) .filter(n -> n.getSubstitution().equals(substitution)) .isPresent(); } @Override public ImmutableSet<Variable> getLocallyRequiredVariables() { return getChildVariables(); } @Override public ImmutableSet<Variable> getRequiredVariables(IntermediateQuery query) { return getLocallyRequiredVariables(); } @Override public ImmutableSet<Variable> getLocallyDefinedVariables() { return substitution.getDomain(); } @Override public boolean isEquivalentTo(QueryNode queryNode) { if (!(queryNode instanceof ConstructionNode)) return false; ConstructionNode node = (ConstructionNode) queryNode; return projectedVariables.equals(node.getVariables()) && substitution.equals(node.getSubstitution()); } @Override public void acceptVisitor(QueryNodeVisitor visitor) { visitor.visit(this); } @Override public String toString() { // TODO: display the query modifiers return CONSTRUCTION_NODE_STR + " " + projectedVariables + " " + "[" + substitution + "]" ; } @Override public IQTree liftBinding(IQTree childIQTree, VariableGenerator variableGenerator, IQProperties currentIQProperties) { IQTree liftedChildIQTree = childIQTree.liftBinding(variableGenerator); QueryNode liftedChildRoot = liftedChildIQTree.getRootNode(); if (liftedChildRoot instanceof ConstructionNode) return liftBinding((ConstructionNode) liftedChildRoot, (UnaryIQTree) liftedChildIQTree, currentIQProperties); else if (liftedChildIQTree.isDeclaredAsEmpty()) { return iqFactory.createEmptyNode(projectedVariables); } else return iqFactory.createUnaryIQTree(this, liftedChildIQTree, currentIQProperties.declareLifted()); } @Override public IQTree applyDescendingSubstitution( ImmutableSubstitution<? extends VariableOrGroundTerm> descendingSubstitution, Optional<ImmutableExpression> constraint, IQTree child) { return applyDescendingSubstitution(descendingSubstitution, child, (c, r) -> propagateDescendingSubstitutionToChild(c, r, constraint)); } /** * * TODO: better handle the constraint * * Returns the new child */ private IQTree propagateDescendingSubstitutionToChild(IQTree child, PropagationResults<VariableOrGroundTerm> tauFPropagationResults, Optional<ImmutableExpression> constraint) throws EmptyTreeException { Optional<ImmutableExpression> descendingConstraint = computeChildConstraint(tauFPropagationResults.theta, constraint); return Optional.of(tauFPropagationResults.delta) .filter(delta -> !delta.isEmpty()) .map(delta -> child.applyDescendingSubstitution(delta, descendingConstraint)) .orElse(child); } @Override public IQTree applyDescendingSubstitutionWithoutOptimizing( ImmutableSubstitution<? extends VariableOrGroundTerm> descendingSubstitution, IQTree child) { return applyDescendingSubstitution(descendingSubstitution, child, (c, r) -> Optional.of(r.delta) .filter(delta -> !delta.isEmpty()) .map(c::applyDescendingSubstitutionWithoutOptimizing) .orElse(c)); } private IQTree applyDescendingSubstitution(ImmutableSubstitution<? extends VariableOrGroundTerm> tau, IQTree child, DescendingSubstitutionChildUpdateFunction updateChildFct) { ImmutableSet<Variable> newProjectedVariables = constructionNodeTools.computeNewProjectedVariables(tau, projectedVariables); ImmutableSubstitution<NonFunctionalTerm> tauC = tau.getNonFunctionalTermFragment(); ImmutableSubstitution<GroundFunctionalTerm> tauF = tau.getGroundFunctionalTermFragment(); try { PropagationResults<NonFunctionalTerm> tauCPropagationResults = propagateTauC(tauC, child); PropagationResults<VariableOrGroundTerm> tauFPropagationResults = propagateTauF(tauF, tauCPropagationResults); Optional<FilterNode> filterNode = tauFPropagationResults.filter .map(iqFactory::createFilterNode); IQTree newChild = updateChildFct.apply(child, tauFPropagationResults); Optional<ConstructionNode> constructionNode = Optional.of(tauFPropagationResults.theta) .filter(theta -> !(theta.isEmpty() && newProjectedVariables.equals(newChild.getVariables()))) .map(theta -> iqFactory.createConstructionNode(newProjectedVariables, theta)); IQTree filterTree = filterNode .map(n -> (IQTree) iqFactory.createUnaryIQTree(n, newChild)) .orElse(newChild); return constructionNode .map(n -> (IQTree) iqFactory.createUnaryIQTree(n, filterTree)) .orElse(filterTree); } catch (EmptyTreeException e) { return iqFactory.createEmptyNode(newProjectedVariables); } } private PropagationResults<NonFunctionalTerm> propagateTauC(ImmutableSubstitution<NonFunctionalTerm> tauC, IQTree child) throws EmptyTreeException { ImmutableSubstitution<NonFunctionalTerm> thetaC = substitution.getNonFunctionalTermFragment(); // Projected variables after propagating tauC ImmutableSet<Variable> vC = constructionNodeTools.computeNewProjectedVariables(tauC, projectedVariables); ImmutableSubstitution<NonFunctionalTerm> newEta = unificationTools.computeMGUS2(thetaC, tauC) .map(eta -> substitutionTools.prioritizeRenaming(eta, vC)) .orElseThrow(EmptyTreeException::new); ImmutableSubstitution<NonFunctionalTerm> thetaCBar = substitutionFactory.getSubstitution( newEta.getImmutableMap().entrySet().stream() .filter(e -> vC.contains(e.getKey())) .collect(ImmutableCollectors.toMap())); ImmutableSubstitution<NonFunctionalTerm> deltaC = extractDescendingSubstitution(newEta, v -> v, thetaC, thetaCBar, projectedVariables); ImmutableSubstitution<ImmutableFunctionalTerm> thetaF = substitution.getFunctionalTermFragment(); ImmutableMultimap<ImmutableTerm, ImmutableFunctionalTerm> m = thetaF.getImmutableMap().entrySet().stream() .collect(ImmutableCollectors.toMultimap( e -> deltaC.apply(e.getKey()), e -> deltaC.applyToFunctionalTerm(e.getValue()))); ImmutableSubstitution<ImmutableFunctionalTerm> thetaFBar = substitutionFactory.getSubstitution( m.asMap().entrySet().stream() .filter(e -> e.getKey() instanceof Variable) .filter(e -> !child.getVariables().contains(e.getKey())) .collect(ImmutableCollectors.toMap( e -> (Variable) e.getKey(), e -> e.getValue().iterator().next() ))); ImmutableSubstitution<ImmutableTerm> gamma = extractDescendingSubstitution(deltaC, thetaFBar::apply, thetaF, thetaFBar, projectedVariables); ImmutableSubstitution<NonFunctionalTerm> newDeltaC = gamma.getNonFunctionalTermFragment(); Optional<ImmutableExpression> f = computeF(m, thetaFBar, gamma, newDeltaC); return new PropagationResults<>(thetaCBar, thetaFBar, newDeltaC, f); } private Optional<ImmutableExpression> computeF(ImmutableMultimap<ImmutableTerm, ImmutableFunctionalTerm> m, ImmutableSubstitution<ImmutableFunctionalTerm> thetaFBar, ImmutableSubstitution<ImmutableTerm> gamma, ImmutableSubstitution<NonFunctionalTerm> newDeltaC) { ImmutableSet<Map.Entry<Variable, ImmutableFunctionalTerm>> thetaFBarEntries = thetaFBar.getImmutableMap().entrySet(); Stream<ImmutableExpression> thetaFRelatedExpressions = m.entries().stream() .filter(e -> !thetaFBarEntries.contains(e)) .map(e -> createEquality(thetaFBar.apply(e.getKey()), e.getValue())); Stream<ImmutableExpression> blockedExpressions = gamma.getImmutableMap().entrySet().stream() .filter(e -> !newDeltaC.isDefining(e.getKey())) .map(e -> createEquality(e.getKey(), e.getValue())); return immutabilityTools.foldBooleanExpressions(Stream.concat(thetaFRelatedExpressions, blockedExpressions)); } private PropagationResults<VariableOrGroundTerm> propagateTauF(ImmutableSubstitution<GroundFunctionalTerm> tauF, PropagationResults<NonFunctionalTerm> tauCPropagationResults) { ImmutableSubstitution<ImmutableTerm> thetaBar = tauCPropagationResults.theta; ImmutableSubstitution<VariableOrGroundTerm> delta = substitutionFactory.getSubstitution( tauF.getImmutableMap().entrySet().stream() .filter(e -> !thetaBar.isDefining(e.getKey())) .filter(e -> !tauCPropagationResults.delta.isDefining(e.getKey())) .collect(ImmutableCollectors.toMap( Map.Entry::getKey, e -> (VariableOrGroundTerm)e.getValue() ))) .composeWith2(tauCPropagationResults.delta); ImmutableSubstitution<ImmutableTerm> newTheta = substitutionFactory.getSubstitution( thetaBar.getImmutableMap().entrySet().stream() .filter(e -> !tauF.isDefining(e.getKey())) .collect(ImmutableCollectors.toMap())); Stream<ImmutableExpression> newConditionStream = Stream.concat( // tauF vs thetaBar tauF.getImmutableMap().entrySet().stream() .filter(e -> thetaBar.isDefining(e.getKey())) .map(e -> createEquality(thetaBar.apply(e.getKey()), tauF.apply(e.getValue()))), // tauF vs newDelta tauF.getImmutableMap().entrySet().stream() .filter(e -> tauCPropagationResults.delta.isDefining(e.getKey())) .map(e -> createEquality(tauCPropagationResults.delta.apply(e.getKey()), tauF.apply(e.getValue())))); Optional<ImmutableExpression> newF = immutabilityTools.foldBooleanExpressions(Stream.concat( tauCPropagationResults.filter .map(e -> e.flattenAND().stream()) .orElseGet(Stream::empty), newConditionStream)); return new PropagationResults<>(newTheta, delta, newF); } private Optional<ImmutableExpression> computeChildConstraint(ImmutableSubstitution<ImmutableTerm> theta, Optional<ImmutableExpression> initialConstraint) throws EmptyTreeException { Optional<ExpressionEvaluator.EvaluationResult> descendingConstraintResults = initialConstraint .map(theta::applyToBooleanExpression) .map(exp -> expressionEvaluator.clone().evaluateExpression(exp)); if (descendingConstraintResults .filter(ExpressionEvaluator.EvaluationResult::isEffectiveFalse) .isPresent()) throw new EmptyTreeException(); return descendingConstraintResults .flatMap(ExpressionEvaluator.EvaluationResult::getOptionalExpression); } /** * TODO: find a better name * */ private <T extends ImmutableTerm> ImmutableSubstitution<T> extractDescendingSubstitution( ImmutableSubstitution<? extends NonFunctionalTerm> substitution, java.util.function.Function<NonFunctionalTerm, T> valueTransformationFct, ImmutableSubstitution<? extends ImmutableTerm> partialTheta, ImmutableSubstitution<? extends ImmutableTerm> newPartialTheta, ImmutableSet<Variable> originalProjectedVariables) { return substitutionFactory.getSubstitution( substitution.getImmutableMap().entrySet().stream() .filter(e -> { Variable v = e.getKey(); return (!partialTheta.isDefining(v)) && ((!newPartialTheta.isDefining(v)) || originalProjectedVariables.contains(v)); }) .collect(ImmutableCollectors.toMap( e -> e.getKey(), e -> valueTransformationFct.apply(e.getValue()) ))); } private ImmutableExpression createEquality(ImmutableTerm t1, ImmutableTerm t2) { return termFactory.getImmutableExpression(EQ, t1, t2); } private IQTree liftBinding(ConstructionNode childConstructionNode, UnaryIQTree childIQ, IQProperties currentIQProperties) { AscendingSubstitutionNormalization ascendingNormalization = normalizeAscendingSubstitution( childConstructionNode.getSubstitution().composeWith(substitution), projectedVariables); ImmutableSubstitution<ImmutableTerm> newSubstitution = ascendingNormalization.getAscendingSubstitution(); IQTree grandChildIQTree = ascendingNormalization.normalizeChild(childIQ.getChild()); ConstructionNode newConstructionNode = iqFactory.createConstructionNode(projectedVariables, newSubstitution); return iqFactory.createUnaryIQTree(newConstructionNode, grandChildIQTree, currentIQProperties.declareLifted()); } private class EmptyTreeException extends Exception { } public static class PropagationResults<T extends VariableOrGroundTerm> { public final ImmutableSubstitution<T> delta; public final Optional<ImmutableExpression> filter; public final ImmutableSubstitution<ImmutableTerm> theta; /** * After tauC propagation */ PropagationResults(ImmutableSubstitution<NonFunctionalTerm> thetaCBar, ImmutableSubstitution<ImmutableFunctionalTerm> thetaFBar, ImmutableSubstitution<T> newDeltaC, Optional<ImmutableExpression> f) { this.theta = thetaFBar.composeWith(thetaCBar); this.delta = newDeltaC; this.filter = f; } /** * After tauF propagation */ PropagationResults(ImmutableSubstitution<ImmutableTerm> theta, ImmutableSubstitution<T> delta, Optional<ImmutableExpression> newF) { this.theta = theta; this.delta = delta; this.filter = newF; } } @FunctionalInterface private interface DescendingSubstitutionChildUpdateFunction { IQTree apply(IQTree child, PropagationResults<VariableOrGroundTerm> tauFPropagationResults) throws EmptyTreeException; } }
package org.protempa; import org.protempa.backend.BackendInitializationException; import org.protempa.backend.tsb.TermSourceBackend; import org.protempa.backend.ksb.KnowledgeSourceBackend; import org.protempa.backend.asb.AlgorithmSourceBackend; import org.protempa.backend.dsb.DataSourceBackend; import org.protempa.backend.InvalidConfigurationException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.protempa.backend.BackendInstanceSpec; import org.protempa.backend.BackendNewInstanceException; import org.protempa.backend.BackendProvider; import org.protempa.backend.BackendProviderSpecLoaderException; import org.protempa.backend.BackendProviderManager; import org.protempa.backend.BackendSpec; import org.protempa.backend.BackendSpecLoader; import org.protempa.backend.ConfigurationsLoadException; import org.protempa.backend.Configurations; import org.protempa.backend.ConfigurationsProviderManager; /** * * @author Andrew Post */ public final class SourceFactory { private final List<BackendInstanceSpec<AlgorithmSourceBackend>> algorithmSourceBackendInstanceSpecs; private final List<BackendInstanceSpec<DataSourceBackend>> dataSourceBackendInstanceSpecs; private final List<BackendInstanceSpec<KnowledgeSourceBackend>> knowledgeSourceBackendInstanceSpecs; private final List<BackendInstanceSpec<TermSourceBackend>> termSourceBackendInstanceSpecs; public SourceFactory(String configurationId) throws ConfigurationsLoadException, BackendProviderSpecLoaderException, InvalidConfigurationException { Logger logger = ProtempaUtil.logger(); logger.fine("Loading backend provider"); BackendProvider backendProvider = BackendProviderManager.getBackendProvider(); logger.log(Level.FINE, "Got backend provider {0}", backendProvider.getClass().getName()); logger.fine("Loading configurations"); Configurations configurations = ConfigurationsProviderManager.getConfigurations(); logger.fine("Got available configurations"); logger.fine("Loading configuration " + configurationId); BackendSpecLoader<AlgorithmSourceBackend> asl = backendProvider.getAlgorithmSourceBackendSpecLoader(); BackendSpecLoader<DataSourceBackend> dsl = backendProvider.getDataSourceBackendSpecLoader(); BackendSpecLoader<KnowledgeSourceBackend> ksl = backendProvider.getKnowledgeSourceBackendSpecLoader(); BackendSpecLoader<TermSourceBackend> tsl = backendProvider.getTermSourceBackendSpecLoader(); for (String specId : configurations.loadConfigurationIds(configurationId)) { if (!asl.hasSpec(specId) && !dsl.hasSpec(specId) && !ksl.hasSpec(specId) && !tsl.hasSpec(specId)) throw new InvalidConfigurationException( "The backend " + specId + " was not found"); } this.algorithmSourceBackendInstanceSpecs = new ArrayList<BackendInstanceSpec<AlgorithmSourceBackend>>(); for (BackendSpec backendSpec : asl) { this.algorithmSourceBackendInstanceSpecs .addAll(configurations.load(configurationId, backendSpec)); } this.dataSourceBackendInstanceSpecs = new ArrayList<BackendInstanceSpec<DataSourceBackend>>(); for (BackendSpec backendSpec : dsl) { this.dataSourceBackendInstanceSpecs .addAll(configurations.load(configurationId, backendSpec)); } this.knowledgeSourceBackendInstanceSpecs = new ArrayList<BackendInstanceSpec<KnowledgeSourceBackend>>(); for (BackendSpec backendSpec : ksl) { this.knowledgeSourceBackendInstanceSpecs .addAll(configurations.load(configurationId, backendSpec)); } this.termSourceBackendInstanceSpecs = new ArrayList<BackendInstanceSpec<TermSourceBackend>>(); for (BackendSpec backendSpec : tsl) { this.termSourceBackendInstanceSpecs .addAll(configurations.load(configurationId, backendSpec)); } logger.fine("Configuration " + configurationId + " loaded"); } public DataSource newDataSourceInstance() throws BackendInitializationException, BackendNewInstanceException { DataSourceBackend[] backends = new DataSourceBackend[ this.dataSourceBackendInstanceSpecs .size()]; for (int i = 0; i < backends.length; i++) { backends[i] = this.dataSourceBackendInstanceSpecs.get(i) .getInstance(); } return new DataSource(backends); } public KnowledgeSource newKnowledgeSourceInstance() throws BackendInitializationException, BackendNewInstanceException { KnowledgeSourceBackend[] backends = new KnowledgeSourceBackend[ this.knowledgeSourceBackendInstanceSpecs .size()]; for (int i = 0; i < backends.length; i++) { backends[i] = this.knowledgeSourceBackendInstanceSpecs.get(i) .getInstance(); } return new KnowledgeSource(backends); } public AlgorithmSource newAlgorithmSourceInstance() throws BackendInitializationException, BackendNewInstanceException { AlgorithmSourceBackend[] backends = new AlgorithmSourceBackend[ this.algorithmSourceBackendInstanceSpecs .size()]; for (int i = 0; i < backends.length; i++) { backends[i] = this.algorithmSourceBackendInstanceSpecs.get(i) .getInstance(); } return new AlgorithmSource(backends); } public TermSource newTermSourceInstance() throws BackendInitializationException, BackendNewInstanceException { TermSourceBackend[] backends = new TermSourceBackend[ this.termSourceBackendInstanceSpecs .size()]; for (int i = 0; i < backends.length; i++) { backends[i] = this.termSourceBackendInstanceSpecs.get(i) .getInstance(); } return new TermSource(backends); } }
package pp.arithmetic.leetcode; import pp.arithmetic.Util; import pp.arithmetic.model.TreeNode; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; public class _102_levelOrder { public static void main(String[] args) { _102_levelOrder levelOrder = new _102_levelOrder(); List<List<Integer>> lists = levelOrder.levelOrder(Util.generateTreeNode()); for (int i = 0; i < lists.size(); i++) { Util.printList(lists.get(i)); } List<List<Integer>> lists2 = levelOrder.levelOrder2(Util.generateTreeNode()); for (int i = 0; i < lists2.size(); i++) { Util.printList(lists2.get(i)); } } /** * * BFS * 1. * 2. * 3.treeNode * 4.1-3 * * 2-3 * {@link _102_levelOrder#levelOrder2(TreeNode)} * * @param root * @return */ public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; Queue<TreeNode> queue = new ArrayDeque<>(); queue.add(root); while (!queue.isEmpty()) { List<TreeNode> list = new ArrayList<>(); while (!queue.isEmpty()) { list.add(queue.poll()); } if (list.size() > 0) { List<Integer> addList = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { TreeNode treeNode = list.get(i); addList.add(treeNode.val); if (treeNode.left != null) queue.add(treeNode.left); if (treeNode.right != null) queue.add(treeNode.right); } result.add(addList); } } return result; } /** * 2-3 * * @param root * @return */ public List<List<Integer>> levelOrder2(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; Queue<TreeNode> queue = new ArrayDeque<>(); queue.add(root); while (!queue.isEmpty()) { List<Integer> addList = new ArrayList<>(); int depth = queue.size(); for (int i = 0; i < depth; i++) { TreeNode treeNode = queue.poll(); addList.add(treeNode.val); if (treeNode.left != null) queue.add(treeNode.left); if (treeNode.right != null) queue.add(treeNode.right); } if (addList.size() > 0) result.add(addList); } return result; } }
package se.z_app.zmote.gui; import java.io.File; import java.util.LinkedList; import java.util.concurrent.ExecutionException; import se.z_app.stb.EPG; import se.z_app.stb.MediaItem; import se.z_app.stb.api.RemoteControl; import se.z_app.zmote.webtv.MediaStreamer; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentSkipListMap; /** * The fragment from which one can play media form the phone, currently supports .mp3 music and .mp4 videos. * @author Christian Tennstedt & Marcus Widegren * */ public class PlayMediaFilesFragment extends Fragment { private MainTabActivity tab; private float screenWidth = 0; private View view_temp; private ProgressBar pb; private File tmpFile; /** * Constructor for the PlayMediaFilesFragment * @param mainTabActivity The tab */ public PlayMediaFilesFragment(MainTabActivity mainTabActivity) { this.tab = mainTabActivity; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view_temp = inflater.inflate(R.layout.fragment_stream_file, null); screenWidth = getResources().getDisplayMetrics().widthPixels; AsyncTask<Integer, Integer, ConcurrentSkipListMap> async = new AsyncSearch().execute(); //the program waits until this line is executed, we could make this better to load the fragment faster /*try { showResults(async.get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ // search(); return view_temp; } // private void search(){ // pb = (ProgressBar)view_temp.findViewById(R.id.progressLodingEpgChannelInformation); // EditText search_box = (EditText)view_temp.findViewById(R.id.search_box_webtv); // TextView resultText = (TextView) view_temp.findViewById(R.id.result_webtv); private void showResults(ConcurrentSkipListMap res){ // some layout stuff LinearLayout results_ly = (LinearLayout) view_temp.findViewById(R.id.search_results_ly); results_ly.removeAllViewsInLayout(); LinearLayout.LayoutParams item_container_params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); LinearLayout.LayoutParams item_params = new LinearLayout.LayoutParams((int)(screenWidth*0.85),LayoutParams.MATCH_PARENT); LinearLayout.LayoutParams icon_params = new LinearLayout.LayoutParams(64,64); LinearLayout.LayoutParams item_params2 = new LinearLayout.LayoutParams((int)(screenWidth*0.15),LayoutParams.MATCH_PARENT); while(!res.isEmpty()){ Object key = res.lastKey(); File fileToAdd = (File)res.remove(key); LinearLayout item_container = new LinearLayout(view_temp.getContext()); item_container.setBackgroundColor(0xFFCCCCCC); item_container.setPadding(4, 4, 4, 4); LinearLayout item2 = new LinearLayout(view_temp.getContext()); item2.setBackgroundColor(0xFF999999); item2.setMinimumHeight(30); item2.setClickable(true); LinearLayout item = new LinearLayout(view_temp.getContext()); item.setBackgroundColor(0xFF999999); item.setMinimumHeight(30); item.setClickable(true); ImageView icon = new ImageView(view_temp.getContext()); String fileName = fileToAdd.toString(); if (fileName.endsWith(".mp3")){ icon.setBackgroundResource(R.drawable.ic_music); } else if (fileName.endsWith(".mp4")){ icon.setBackgroundResource(R.drawable.ic_video); } else if (fileName.endsWith(".jpg")){ icon.setBackgroundResource(R.drawable.ic_photo); } else{ icon.setBackgroundResource(R.drawable.ic_action_search); } TextView title = new TextView(view_temp.getContext()); title.setText(fileToAdd.getName()); title.setPadding(10, 0, 0, 0); title.setTextColor(0xFF000000); item.addView(icon, icon_params); item.addView(title); item_container.addView(item, item_params); item_container.addView(item2, item_params2); results_ly.addView(item_container, item_container_params); tmpFile = fileToAdd; item.setOnClickListener(new View.OnClickListener() { File file = tmpFile; @Override public void onClick(View v) { tab.vibrate(); MediaItem item = MediaStreamer.instance().addFile(file); Log.i("files","launcing file "+ file.getAbsolutePath()); RemoteControl.instance().launch(item); } }); } } private class AsyncSearch extends AsyncTask<Integer, Integer, ConcurrentSkipListMap>{ private ConcurrentSkipListMap getResult(){ ConcurrentSkipListMap mediaFiles = new ConcurrentSkipListMap(); LinkedList<File> files = new LinkedList<File>(); files.addLast(Environment.getExternalStorageDirectory()); files.addLast(Environment.getDataDirectory()); files.addLast(Environment.getDownloadCacheDirectory()); Log.i("Files", "Starting scan..."); long time = System.currentTimeMillis(); while(!files.isEmpty()){ File file = files.removeFirst(); File children[] = file.listFiles(); if(children != null){ for (File child : children) { if(!child.isHidden()){ if(child.isDirectory()){ files.addLast(child); } else{ String filename = child.getName().toLowerCase(); if(filename.endsWith(".mp4") || filename.endsWith(".mp3") || filename.endsWith(".jpg")){ mediaFiles.put(child.lastModified(),child); Log.i("Files", "Found file..."+ filename); } } } } } } return mediaFiles; } @Override protected ConcurrentSkipListMap doInBackground(Integer... params) { return getResult(); } protected void onPostExecute(ConcurrentSkipListMap results) { view_temp.findViewById(R.id.progressBarStream).setVisibility(View.INVISIBLE); showResults(results); } } }
package gov.nih.nci.cagrid.data.utilities; import gov.nih.nci.cagrid.cqlresultset.CQLAttributeResult; import gov.nih.nci.cagrid.cqlresultset.CQLCountResult; import gov.nih.nci.cagrid.cqlresultset.CQLObjectResult; import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults; import gov.nih.nci.cagrid.cqlresultset.TargetAttribute; import gov.nih.nci.cagrid.data.mapping.Mappings; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import org.apache.axis.message.MessageElement; public class CQLResultsCreationUtil { /** * Creates a CQL Query Results object containing object results * * @param objects * The objects to serialize and place in the object results * @param targetName * The name of the targeted class which produced these results * @param classToQname * A Mapping from class name to QName * @return * A CQLQueryResults instance with its object results populated * * @throws ResultsCreationException */ public static CQLQueryResults createObjectResults(List objects, String targetName, Mappings classToQname) throws ResultsCreationException { CQLQueryResults results = new CQLQueryResults(); results.setTargetClassname(targetName); QName targetQName = getQname(targetName, classToQname); List objectResults = new ArrayList(); for (Iterator iter = objects.iterator(); iter.hasNext();) { MessageElement elem = new MessageElement(targetQName, iter.next()); objectResults.add(new CQLObjectResult(new MessageElement[] {elem})); } CQLObjectResult[] objectResultArray = new CQLObjectResult[objectResults.size()]; objectResults.toArray(objectResultArray); results.setObjectResult(objectResultArray); return results; } /** * Creates a CQL Query Results instance containing attribute results * * @param attribArrays * A List of String[], which are the values of the attributes. * These values must correspond both in number and in order of the * attribute names * @param targetClassname * The name of the class targeted * @param attribNames * The names of the attributes queried for * @return * A CQLQueryResults instance with its attribute results populated */ public static CQLQueryResults createAttributeResults(List attribArrays, String targetClassname, String[] attribNames) { CQLQueryResults results = new CQLQueryResults(); results.setTargetClassname(targetClassname); List<CQLAttributeResult> attribResults = new ArrayList<CQLAttributeResult>(); for (Iterator iter = attribArrays.iterator(); iter.hasNext();) { TargetAttribute[] attribs = new TargetAttribute[attribNames.length]; Object valueArray = iter.next(); String[] attribValues = new String[attribNames.length]; if (valueArray == null) { Arrays.fill(attribValues, null); } else if (valueArray.getClass().isArray()) { for (int j = 0; j < Array.getLength(valueArray); j++) { Object singleValue = Array.get(valueArray, j); attribValues[j] = singleValue == null ? null : singleValue.toString(); } } else { attribValues = new String[] {valueArray == null ? null : valueArray.toString()}; } for (int j = 0; j < attribNames.length; j++) { attribs[j] = new TargetAttribute(attribNames[j], attribValues[j]); } attribResults.add(new CQLAttributeResult(attribs)); } CQLAttributeResult[] attribResultArray = new CQLAttributeResult[attribResults.size()]; attribResults.toArray(attribResultArray); results.setAttributeResult(attribResultArray); return results; } /** * Creates a CQL Query Results object containing a single count result * * @param count * The total count of all items * @param targetClassname * The classname of the query target * @return * A CQLQueryResults instance with count results populated */ public static CQLQueryResults createCountResults(long count, String targetClassname) { CQLQueryResults results = new CQLQueryResults(); results.setTargetClassname(targetClassname); CQLCountResult countResult = new CQLCountResult(); countResult.setCount(count); results.setCountResult(countResult); return results; } private static QName getQname(String className, Mappings classMappings) { for (int i = 0; classMappings.getMapping() != null && i < classMappings.getMapping().length; i++) { if (classMappings.getMapping(i).getClassName().equals(className)) { return QName.valueOf(classMappings.getMapping(i).getQname()); } } return null; } }
package sergeysav.neuralnetwork.chess; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.concurrent.ExecutionException; import java.util.function.Supplier; import java.util.stream.Stream; import java.util.stream.StreamSupport; import sergeysav.neuralnetwork.NeuralNetwork; import sergeysav.neuralnetwork.chess.ChessTrainer.TrainingResult; /* * * Inputs 0-5 are type of piece at (0,0), Inputs (6-11) are type of piece at (1,0) * */ public class ChessAIMain { private static double trainingRatio = 0.75; private static BufferedWriter fileWriter; private static double LEARNING_K = 1e-3; private static double EPSILON = 1e-8; public static void main(String[] args) throws InterruptedException, ExecutionException, FileNotFoundException { Runtime.getRuntime().addShutdownHook(new Thread(()->{ if (fileWriter != null) { try { fileWriter.close(); } catch (Exception e) { e.printStackTrace(); } } })); try { fileWriter = new BufferedWriter(new FileWriter(new File("log.log"))); } catch (IOException e) { e.printStackTrace(); } print("Initializing games"); File gamesDirectory = new File("games"); List<File> trainingFiles = new ArrayList<File>(); List<File> testingFiles = new ArrayList<File>(); for (File pgnFile : gamesDirectory.listFiles()) { if (!pgnFile.isDirectory() && !pgnFile.isHidden() && pgnFile.getName().endsWith(".pgn")) { if (Math.random() <= trainingRatio) { trainingFiles.add(pgnFile); } else { testingFiles.add(pgnFile); } } } ChessStore loaded = null; if (args.length > 0 && new File("backups/" + args[0]).exists()) { print("Loading Neural Network from file"); loaded = ChessStore.load(new File("backups/" + args[0])); } NeuralNetwork network; ChessTrainer trainer; int startEpoch; Supplier<Stream<double[]>> trainingData = ()->{ //Generate a stream of double arrays for the training data Collections.shuffle(trainingFiles); return trainingFiles.stream().flatMap((f)->{ //Convert each file to a stream of transcripts List<Transcript> trans = new LinkedList<Transcript>(); readTranscripts(f, trans); return trans.stream(); }).flatMap((t)->StreamSupport.stream(t.spliterator(), false)).parallel(); }; Supplier<Stream<double[]>> testingData = ()->{ //Generate a stream of double arrays for the testing data Collections.shuffle(testingFiles); return testingFiles.stream().flatMap((f)->{ //Convert each file to a stream of transcripts List<Transcript> trans = new LinkedList<Transcript>(); readTranscripts(f, trans); return trans.stream(); }).flatMap((t)->StreamSupport.stream(t.spliterator(), false)).parallel(); }; if (loaded == null) { print("Creating Neural Network"); //Create a new neural network network = new NeuralNetwork(true, 384, 259, 259, 134); //384 inputs, 2 layers of 259 neurons, 134 outputs (128 tiles + 6 upgrade types) print("Creating Network Trainer"); trainer = new ChessTrainer(LEARNING_K, trainingData, testingData, network, EPSILON); startEpoch = 0; } else { network = loaded.network; network.init(); trainer = loaded.trainer; trainer.init(LEARNING_K, trainingData, testingData, network, EPSILON); startEpoch = loaded.getEpoch(); loaded = null; } ChessStore store = new ChessStore(); store.network = network; store.trainer = trainer; store.setEpoch(startEpoch); store.save(); print("Calculating if next epoch needed\n"); while (trainer.isNextEpochNeeded()) { print("Epoch " + (store.getEpoch()+1) + " starting"); trainer.performEpoch(store::save); print("Epoch completed"); store.setEpoch(store.getEpoch()+1);; store.save(); print("Calculating if next epoch needed\n"); } //I don't ever expect this code to be reached print("Training Completed"); TrainingResult result = trainer.getResult(); print("Took " + result.epochs + " epochs"); } private static void readTranscripts(File file, List<Transcript> transcripts) { int transcript = 0; try (Scanner scan = new Scanner(file)) { Transcript t = null; String moveList = null; while(scan.hasNextLine()) { String line = scan.nextLine(); if (line.startsWith("[Event \"")) { if (t != null) { transcript++; try { if (moveList != null) { populateTranscript(t, moveList); moveList = null; transcripts.add(t); } } catch (Exception e) { System.err.println("Error reading " + file.getName() + "#" + transcript); e.printStackTrace(); } } t = new Transcript(); } if (line.startsWith("1.")) { moveList = ""; } if (moveList != null) moveList += line + " "; } } catch (IOException e) { e.printStackTrace(); } } private static void populateTranscript(Transcript t, String moveList) { String old; do { old = moveList; moveList = moveList.replaceAll("(?:\\([^\\(\\)]*\\))", ""); //Remove areas enclosed in parenthesis moveList = moveList.replaceAll("(?:\\{[^\\{\\}]*\\})", ""); //Remove areas enclosed in braces } while (!old.equals(moveList)); moveList = moveList.replaceAll("(?:\\d+\\.\\.\\.)", ""); //Remove all elipses //if (moveList.contains("+")) checks++; //if (moveList.contains("#")) checkmates++; String[] moved = moveList.split("\\d*[\\\\.]\\s*"); ChessBoard board = new ChessBoard(); LinkedList<String> moves = t.getMoves(); for (int i = 1; i<moved.length; i++) { if (i == moved.length - 1) { String[] parts = moved[i].split("\\s+"); if (parts.length > 2) { String movew = board.getMoveConverted(parts[0], true); moves.add(movew); board.applyConvertedMove(movew); String moveb = board.getMoveConverted(parts[1], false); moves.add(moveb); board.applyConvertedMove(moveb); t.setOutcome(parts[2]); } else { String movew = board.getMoveConverted(parts[0], true); moves.add(movew); board.applyConvertedMove(movew); t.setOutcome(parts[1]); } } else { String[] steps = moved[i].split("\\s+"); String movew = board.getMoveConverted(steps[0], true); moves.add(movew); board.applyConvertedMove(movew); String moveb = board.getMoveConverted(steps[1], false); moves.add(moveb); board.applyConvertedMove(moveb); } } //games++; //ChessAIMain.moves += moves.size(); } public static void print(String arg) { String str = "[" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS")) + "] " + arg; try { fileWriter.write(str+"\n"); } catch (IOException e) { e.printStackTrace(); } System.out.println(str); } }
package com.jetbrains.python.actions; import com.intellij.ide.IdeBundle; import com.intellij.ide.IdeView; import com.intellij.ide.actions.CreateDirectoryOrPackageHandler; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.FileTemplateUtil; import com.intellij.ide.util.DirectoryChooserUtil; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiFileSystemItem; import com.jetbrains.python.PyNames; /** * @author yole */ public class CreatePackageAction extends DumbAwareAction { private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.actions.CreatePackageAction"); @Override public void actionPerformed(AnActionEvent e) { final IdeView view = e.getData(LangDataKeys.IDE_VIEW); if (view == null) { return; } final Project project = e.getData(PlatformDataKeys.PROJECT); final PsiDirectory directory = DirectoryChooserUtil.getOrChooseDirectory(view); if (directory == null) return; CreateDirectoryOrPackageHandler validator = new CreateDirectoryOrPackageHandler(project, directory, false, ".") { @Override protected void createDirectories(String subDirName) { super.createDirectories(subDirName); PsiFileSystemItem element = getCreatedElement(); if (element instanceof PsiDirectory) { createInitPyInHierarchy((PsiDirectory)element, directory); } } }; Messages.showInputDialog(project, IdeBundle.message("prompt.enter.new.package.name"), IdeBundle.message("title.new.package"), Messages.getQuestionIcon(), "", validator); final PsiFileSystemItem result = validator.getCreatedElement(); if (result != null) { view.selectElement(result); } } public static void createInitPyInHierarchy(PsiDirectory created, PsiDirectory ancestor) { do { createInitPy(created); created = created.getParent(); } while(created != null && created != ancestor); } private static void createInitPy(PsiDirectory directory) { final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance(); final FileTemplate template = fileTemplateManager.getInternalTemplate("Python Script"); if (directory.findFile(PyNames.INIT_DOT_PY) != null) { return; } if (template != null) { try { FileTemplateUtil.createFromTemplate(template, PyNames.INIT_DOT_PY, fileTemplateManager.getDefaultProperties(directory.getProject()), directory); } catch (Exception e) { LOG.error(e); } } else { final PsiFile file = PsiFileFactory.getInstance(directory.getProject()).createFileFromText(PyNames.INIT_DOT_PY, ""); directory.add(file); } } @Override public void update(AnActionEvent e) { boolean enabled = isEnabled(e); e.getPresentation().setVisible(enabled); e.getPresentation().setEnabled(enabled); } private static boolean isEnabled(AnActionEvent e) { Project project = e.getData(PlatformDataKeys.PROJECT); final IdeView ideView = e.getData(LangDataKeys.IDE_VIEW); if (project == null || ideView == null) { return false; } final PsiDirectory[] directories = ideView.getDirectories(); if (directories.length == 0) { return false; } return true; } }
package org.fxmisc.richtext; import static org.fxmisc.richtext.PopupAlignment.*; import static org.reactfx.EventStreams.*; import static org.reactfx.util.Tuples.*; import java.time.Duration; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.IntConsumer; import java.util.function.IntFunction; import java.util.function.IntSupplier; import java.util.function.IntUnaryOperator; import java.util.function.UnaryOperator; import java.util.stream.Stream; import javafx.beans.binding.Binding; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.beans.binding.ObjectBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableBooleanValue; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; import javafx.css.PseudoClass; import javafx.css.StyleableObjectProperty; import javafx.event.Event; import javafx.geometry.BoundingBox; import javafx.geometry.Bounds; import javafx.geometry.Insets; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.control.IndexRange; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.PopupWindow; import org.fxmisc.flowless.Cell; import org.fxmisc.flowless.VirtualFlow; import org.fxmisc.flowless.VirtualFlowHit; import org.fxmisc.flowless.Virtualized; import org.fxmisc.flowless.VirtualizedScrollPane; import org.fxmisc.richtext.CssProperties.EditableProperty; import org.fxmisc.undo.UndoManager; import org.fxmisc.undo.UndoManagerFactory; import org.reactfx.EventStream; import org.reactfx.EventStreams; import org.reactfx.StateMachine; import org.reactfx.Subscription; import org.reactfx.collection.LiveList; import org.reactfx.util.Tuple2; import org.reactfx.value.Val; import org.reactfx.value.Var; /** * Text editing control. Accepts user input (keyboard, mouse) and * provides API to assign style to text ranges. It is suitable for * syntax highlighting and rich-text editors. * * <p>Subclassing is allowed to define the type of style, e.g. inline * style or style classes.</p> * * <p>Note: Scroll bars no longer appear when the content spans outside * of the viewport. To add scroll bars, the area needs to be embedded in * a {@link VirtualizedScrollPane}. {@link AreaFactory} is provided to make * this more convenient.</p> * * <h3>Overriding keyboard shortcuts</h3> * * {@code StyledTextArea} comes with {@link #onKeyTypedProperty()} and * {@link #onKeyPressedProperty()} handlers installed to handle keyboard input. * Ordinary character input is handled by the {@code onKeyTyped} handler and * control key combinations (including Enter and Tab) are handled by the * {@code onKeyPressed} handler. To add or override some keyboard shortcuts, * but keep the rest in place, you would combine the default event handler with * a new one that adds or overrides some of the default key combinations. This * is how to bind {@code Ctrl+S} to the {@code save()} operation: * <pre> * {@code * import static javafx.scene.input.KeyCode.*; * import static javafx.scene.input.KeyCombination.*; * import static org.fxmisc.wellbehaved.event.EventPattern.*; * * import org.fxmisc.wellbehaved.event.EventHandlerHelper; * * EventHandler<? super KeyEvent> ctrlS = EventHandlerHelper * .on(keyPressed(S, CONTROL_DOWN)).act(event -> save()) * .create(); * * EventHandlerHelper.install(area.onKeyPressedProperty(), ctrlS); * } * </pre> * * @param <S> type of style that can be applied to text. */ public class StyledTextArea<PS, S> extends Region implements TextEditingArea<PS, S>, EditActions<PS, S>, ClipboardActions<PS, S>, NavigationActions<PS, S>, UndoActions, TwoDimensional, Virtualized { /** * Index range [0, 0). */ public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0); private static final PseudoClass HAS_CARET = PseudoClass.getPseudoClass("has-caret"); private static final PseudoClass FIRST_PAR = PseudoClass.getPseudoClass("first-paragraph"); private static final PseudoClass LAST_PAR = PseudoClass.getPseudoClass("last-paragraph"); /** * Background fill for highlighted text. */ private final StyleableObjectProperty<Paint> highlightFill = new CssProperties.HighlightFillProperty(this, Color.DODGERBLUE); /** * Text color for highlighted text. */ private final StyleableObjectProperty<Paint> highlightTextFill = new CssProperties.HighlightTextFillProperty(this, Color.WHITE); // editable property /** * Indicates whether this text area can be edited by the user. * Note that this property doesn't affect editing through the API. */ private final BooleanProperty editable = new EditableProperty<>(this); public final boolean isEditable() { return editable.get(); } public final void setEditable(boolean value) { editable.set(value); } public final BooleanProperty editableProperty() { return editable; } // wrapText property /** * When a run of text exceeds the width of the text region, * then this property indicates whether the text should wrap * onto another line. */ private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText"); public final boolean isWrapText() { return wrapText.get(); } public final void setWrapText(boolean value) { wrapText.set(value); } public final BooleanProperty wrapTextProperty() { return wrapText; } // undo manager @Override public UndoManager getUndoManager() { return model.getUndoManager(); } @Override public void setUndoManager(UndoManagerFactory undoManagerFactory) { model.setUndoManager(undoManagerFactory); } /** * Popup window that will be positioned by this text area relative to the * caret or selection. Use {@link #popupAlignmentProperty()} to specify * how the popup should be positioned relative to the caret or selection. * Use {@link #popupAnchorOffsetProperty()} or * {@link #popupAnchorAdjustmentProperty()} to further adjust the position. */ private final ObjectProperty<PopupWindow> popupWindow = new SimpleObjectProperty<>(); public void setPopupWindow(PopupWindow popup) { popupWindow.set(popup); } public PopupWindow getPopupWindow() { return popupWindow.get(); } public ObjectProperty<PopupWindow> popupWindowProperty() { return popupWindow; } /** @deprecated Use {@link #setPopupWindow(PopupWindow)}. */ @Deprecated public void setPopupAtCaret(PopupWindow popup) { popupWindow.set(popup); } /** @deprecated Use {@link #getPopupWindow()}. */ @Deprecated public PopupWindow getPopupAtCaret() { return popupWindow.get(); } /** @deprecated Use {@link #popupWindowProperty()}. */ @Deprecated public ObjectProperty<PopupWindow> popupAtCaretProperty() { return popupWindow; } /** * Specifies further offset (in pixels) of the popup window from the * position specified by {@link #popupAlignmentProperty()}. * * <p>If {@link #popupAnchorAdjustmentProperty()} is also specified, then * it overrides the offset set by this property. */ private final ObjectProperty<Point2D> popupAnchorOffset = new SimpleObjectProperty<>(); public void setPopupAnchorOffset(Point2D offset) { popupAnchorOffset.set(offset); } public Point2D getPopupAnchorOffset() { return popupAnchorOffset.get(); } public ObjectProperty<Point2D> popupAnchorOffsetProperty() { return popupAnchorOffset; } /** * Specifies how to adjust the popup window's anchor point. The given * operator is invoked with the screen position calculated according to * {@link #popupAlignmentProperty()} and should return a new screen * position. This position will be used as the popup window's anchor point. * * <p>Setting this property overrides {@link #popupAnchorOffsetProperty()}. */ private final ObjectProperty<UnaryOperator<Point2D>> popupAnchorAdjustment = new SimpleObjectProperty<>(); public void setPopupAnchorAdjustment(UnaryOperator<Point2D> f) { popupAnchorAdjustment.set(f); } public UnaryOperator<Point2D> getPopupAnchorAdjustment() { return popupAnchorAdjustment.get(); } public ObjectProperty<UnaryOperator<Point2D>> popupAnchorAdjustmentProperty() { return popupAnchorAdjustment; } /** * Defines where the popup window given in {@link #popupWindowProperty()} * is anchored, i.e. where its anchor point is positioned. This position * can further be adjusted by {@link #popupAnchorOffsetProperty()} or * {@link #popupAnchorAdjustmentProperty()}. */ private final ObjectProperty<PopupAlignment> popupAlignment = new SimpleObjectProperty<>(CARET_TOP); public void setPopupAlignment(PopupAlignment pos) { popupAlignment.set(pos); } public PopupAlignment getPopupAlignment() { return popupAlignment.get(); } public ObjectProperty<PopupAlignment> popupAlignmentProperty() { return popupAlignment; } /** * Defines how long the mouse has to stay still over the text before a * {@link MouseOverTextEvent} of type {@code MOUSE_OVER_TEXT_BEGIN} is * fired on this text area. When set to {@code null}, no * {@code MouseOverTextEvent}s are fired on this text area. * * <p>Default value is {@code null}. */ private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null); public void setMouseOverTextDelay(Duration delay) { mouseOverTextDelay.set(delay); } public Duration getMouseOverTextDelay() { return mouseOverTextDelay.get(); } public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; } /** * Defines how to handle an event in which the user has selected some text, dragged it to a * new location within the area, and released the mouse at some character {@code index} * within the area. * * <p>By default, this will relocate the selected text to the character index where the mouse * was released. To override it, use {@link #setOnSelectionDrop(IntConsumer)}. */ private Property<IntConsumer> onSelectionDrop = new SimpleObjectProperty<>(this::moveSelectedText); public final void setOnSelectionDrop(IntConsumer consumer) { onSelectionDrop.setValue(consumer); } public final IntConsumer getOnSelectionDrop() { return onSelectionDrop.getValue(); } private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null); public void setParagraphGraphicFactory(IntFunction<? extends Node> factory) { paragraphGraphicFactory.set(factory); } public IntFunction<? extends Node> getParagraphGraphicFactory() { return paragraphGraphicFactory.get(); } public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; } /** * Indicates whether the initial style should also be used for plain text * inserted into this text area. When {@code false}, the style immediately * preceding the insertion position is used. Default value is {@code false}. */ public BooleanProperty useInitialStyleForInsertionProperty() { return model.useInitialStyleForInsertionProperty(); } public void setUseInitialStyleForInsertion(boolean value) { model.setUseInitialStyleForInsertion(value); } public boolean getUseInitialStyleForInsertion() { return model.getUseInitialStyleForInsertion(); } private Optional<Tuple2<Codec<PS>, Codec<S>>> styleCodecs = Optional.empty(); /** * Sets codecs to encode/decode style information to/from binary format. * Providing codecs enables clipboard actions to retain the style information. */ public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<S> textStyleCodec) { styleCodecs = Optional.of(t(paragraphStyleCodec, textStyleCodec)); } @Override public Optional<Tuple2<Codec<PS>, Codec<S>>> getStyleCodecs() { return styleCodecs; } /** * The <em>estimated</em> scrollX value. This can be set in order to scroll the content. * Value is only accurate when area does not wrap lines and uses the same font size * throughout the entire area. */ @Override public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); } public double getEstimatedScrollX() { return virtualFlow.estimatedScrollXProperty().getValue(); } public void setEstimatedScrollX(double value) { virtualFlow.estimatedScrollXProperty().setValue(value); } /** * The <em>estimated</em> scrollY value. This can be set in order to scroll the content. * Value is only accurate when area does not wrap lines and uses the same font size * throughout the entire area. */ @Override public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); } public double getEstimatedScrollY() { return virtualFlow.estimatedScrollYProperty().getValue(); } public void setEstimatedScrollY(double value) { virtualFlow.estimatedScrollYProperty().setValue(value); } // text @Override public final String getText() { return model.getText(); } @Override public final ObservableValue<String> textProperty() { return model.textProperty(); } // rich text @Override public final StyledDocument<PS, S> getDocument() { return model.getDocument(); } // length @Override public final int getLength() { return model.getLength(); } @Override public final ObservableValue<Integer> lengthProperty() { return model.lengthProperty(); } // caret position @Override public final int getCaretPosition() { return model.getCaretPosition(); } @Override public final ObservableValue<Integer> caretPositionProperty() { return model.caretPositionProperty(); } // selection anchor @Override public final int getAnchor() { return model.getAnchor(); } @Override public final ObservableValue<Integer> anchorProperty() { return model.anchorProperty(); } // selection @Override public final IndexRange getSelection() { return model.getSelection(); } @Override public final ObservableValue<IndexRange> selectionProperty() { return model.selectionProperty(); } // selected text @Override public final String getSelectedText() { return model.getSelectedText(); } @Override public final ObservableValue<String> selectedTextProperty() { return model.selectedTextProperty(); } // current paragraph index @Override public final int getCurrentParagraph() { return model.getCurrentParagraph(); } @Override public final ObservableValue<Integer> currentParagraphProperty() { return model.currentParagraphProperty(); } // caret column @Override public final int getCaretColumn() { return model.getCaretColumn(); } @Override public final ObservableValue<Integer> caretColumnProperty() { return model.caretColumnProperty(); } // paragraphs @Override public LiveList<Paragraph<PS, S>> getParagraphs() { return model.getParagraphs(); } // beingUpdated public ObservableBooleanValue beingUpdatedProperty() { return model.beingUpdatedProperty(); } public boolean isBeingUpdated() { return model.isBeingUpdated(); } // total width estimate /** * The <em>estimated</em> width of the entire document. Accurate when area does not wrap lines and * uses the same font size throughout the entire area. Value is only supposed to be <em>set</em> by * the skin, not the user. */ @Override public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); } public double getTotalWidthEstimate() { return virtualFlow.totalWidthEstimateProperty().getValue(); } // total height estimate /** * The <em>estimated</em> height of the entire document. Accurate when area does not wrap lines and * uses the same font size throughout the entire area. Value is only supposed to be <em>set</em> by * the skin, not the user. */ @Override public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); } public double getTotalHeightEstimate() { return virtualFlow.totalHeightEstimateProperty().getValue(); } // text changes @Override public final EventStream<PlainTextChange> plainTextChanges() { return model.plainTextChanges(); } // rich text changes @Override public final EventStream<RichTextChange<PS, S>> richChanges() { return model.richChanges(); } private final StyledTextAreaBehavior behavior; private Subscription subscriptions = () -> {}; private final Binding<Boolean> caretVisible; private final Val<UnaryOperator<Point2D>> _popupAnchorAdjustment; private final VirtualFlow<Paragraph<PS, S>, Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>> virtualFlow; // used for two-level navigation, where on the higher level are // paragraphs and on the lower level are lines within a paragraph private final TwoLevelNavigator navigator; private boolean followCaretRequested = false; /** * model */ private final StyledTextAreaModel<PS, S> model; /** * @return this area's {@link StyledTextAreaModel} */ final StyledTextAreaModel<PS, S> getModel() { return model; } /** * The underlying document that can be displayed by multiple {@code StyledTextArea}s. */ public final EditableStyledDocument<PS, S> getContent() { return model.getContent(); } /** * Style used by default when no other style is provided. */ public final S getInitialTextStyle() { return model.getInitialTextStyle(); } /** * Style used by default when no other style is provided. */ public final PS getInitialParagraphStyle() { return model.getInitialParagraphStyle(); } /** * Style applicator used by the default skin. */ private final BiConsumer<? super TextExt, S> applyStyle; public final BiConsumer<? super TextExt, S> getApplyStyle() { return applyStyle; } /** * Style applicator used by the default skin. */ private final BiConsumer<TextFlow, PS> applyParagraphStyle; public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; } /** * Indicates whether style should be preserved on undo/redo, * copy/paste and text move. * TODO: Currently, only undo/redo respect this flag. */ public final boolean isPreserveStyle() { return model.isPreserveStyle(); } /** * Creates a text area with empty text content. * * @param initialTextStyle style to use in places where no other style is * specified (yet). * @param applyStyle function that, given a {@link Text} node and * a style, applies the style to the text node. This function is * used by the default skin to apply style to text nodes. * @param initialParagraphStyle style to use in places where no other style is * specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. */ public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle, S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle ) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, applyStyle, true); } public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle, S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle, boolean preserveStyle ) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, applyStyle, new EditableStyledDocumentImpl<>(initialParagraphStyle, initialTextStyle), preserveStyle); } /** * The same as {@link #StyledTextArea(Object, BiConsumer, Object, BiConsumer)} except that * this constructor can be used to create another {@code StyledTextArea} object that * shares the same {@link EditableStyledDocument}. */ public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle, S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle, EditableStyledDocument<PS, S> document ) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, applyStyle, document, true); } public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle, S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle, EditableStyledDocument<PS, S> document, boolean preserveStyle ) { this.model = new StyledTextAreaModel<>(initialParagraphStyle, initialTextStyle, document, preserveStyle); this.applyStyle = applyStyle; this.applyParagraphStyle = applyParagraphStyle; // allow tab traversal into area setFocusTraversable(true); this.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))); getStyleClass().add("styled-text-area"); getStylesheets().add(StyledTextArea.class.getResource("styled-text-area.css").toExternalForm()); // keeps track of currently used non-empty cells @SuppressWarnings("unchecked") ObservableSet<ParagraphBox<PS, S>> nonEmptyCells = FXCollections.observableSet(); // Initialize content virtualFlow = VirtualFlow.createVertical( getParagraphs(), par -> { Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = createCell( par, applyStyle, applyParagraphStyle); nonEmptyCells.add(cell.getNode()); return cell.beforeReset(() -> nonEmptyCells.remove(cell.getNode())) .afterUpdateItem(p -> nonEmptyCells.add(cell.getNode())); }); getChildren().add(virtualFlow); // initialize navigator IntSupplier cellCount = () -> getParagraphs().size(); IntUnaryOperator cellLength = i -> virtualFlow.getCell(i).getNode().getLineCount(); navigator = new TwoLevelNavigator(cellCount, cellLength); // follow the caret every time the caret position or paragraphs change EventStream<?> caretPosDirty = invalidationsOf(caretPositionProperty()); EventStream<?> paragraphsDirty = invalidationsOf(getParagraphs()); EventStream<?> selectionDirty = invalidationsOf(selectionProperty()); // need to reposition popup even when caret hasn't moved, but selection has changed (been deselected) EventStream<?> caretDirty = merge(caretPosDirty, paragraphsDirty, selectionDirty); subscribeTo(caretDirty, x -> requestFollowCaret()); // whether or not to animate the caret BooleanBinding blinkCaret = focusedProperty() .and(editableProperty()) .and(disabledProperty().not()); manageBinding(blinkCaret); // The caret is visible in periodic intervals, // but only when blinkCaret is true. caretVisible = EventStreams.valuesOf(blinkCaret) .flatMap(blink -> blink ? booleanPulse(Duration.ofMillis(500), caretDirty) : EventStreams.valuesOf(Val.constant(false))) .toBinding(false); manageBinding(caretVisible); // Adjust popup anchor by either a user-provided function, // or user-provided offset, or don't adjust at all. Val<UnaryOperator<Point2D>> userOffset = Val.map( popupAnchorOffsetProperty(), offset -> anchor -> anchor.add(offset)); _popupAnchorAdjustment = Val.orElse( popupAnchorAdjustmentProperty(), userOffset) .orElseConst(UnaryOperator.identity()); // dispatch MouseOverTextEvents when mouseOverTextDelay is not null EventStreams.valuesOf(mouseOverTextDelayProperty()) .flatMap(delay -> delay != null ? mouseOverTextEvents(nonEmptyCells, delay) : EventStreams.never()) .subscribe(evt -> Event.fireEvent(this, evt)); behavior = new StyledTextAreaBehavior(this); } /** * Returns caret bounds relative to the viewport, i.e. the visual bounds * of the embedded VirtualFlow. */ Optional<Bounds> getCaretBounds() { return virtualFlow.getCellIfVisible(getCurrentParagraph()) .map(c -> { Bounds cellBounds = c.getNode().getCaretBounds(); return virtualFlow.cellToViewport(c, cellBounds); }); } /** * Returns x coordinate of the caret in the current paragraph. */ ParagraphBox.CaretOffsetX getCaretOffsetX() { int idx = getCurrentParagraph(); return getCell(idx).getCaretOffsetX(); } double getViewportHeight() { return virtualFlow.getHeight(); } CharacterHit hit(ParagraphBox.CaretOffsetX x, TwoDimensional.Position targetLine) { int parIdx = targetLine.getMajor(); ParagraphBox<PS, S> cell = virtualFlow.getCell(parIdx).getNode(); CharacterHit parHit = cell.hitTextLine(x, targetLine.getMinor()); return parHit.offset(getParagraphOffset(parIdx)); } CharacterHit hit(ParagraphBox.CaretOffsetX x, double y) { VirtualFlowHit<Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>> hit = virtualFlow.hit(0.0, y); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hitText(x, cellOffset.getY()); return parHit.offset(parOffset); } } /** * Helpful for determining which letter is at point x, y: * <pre> * {@code * StyledTextArea area = // creation code * area.addEventHandler(MouseEvent.MOUSE_PRESSED, (MouseEvent e) -> { * CharacterHit hit = area.hit(e.getX(), e.getY()); * int characterPosition = hit.getInsertionIndex(); * * // move the caret to that character's position * area.moveTo(characterPosition, SelectionPolicy.CLEAR); * }} * </pre> */ public CharacterHit hit(double x, double y) { VirtualFlowHit<Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>> hit = virtualFlow.hit(x, y); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hit(cellOffset); return parHit.offset(parOffset); } } /** * Returns the current line as a two-level index. * The major number is the paragraph index, the minor * number is the line number within the paragraph. * * <p>This method has a side-effect of bringing the current * paragraph to the viewport if it is not already visible. */ TwoDimensional.Position currentLine() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx); int lineIdx = cell.getNode().getCurrentLineIndex(); return _position(parIdx, lineIdx); } TwoDimensional.Position _position(int par, int line) { return navigator.position(par, line); } @Override public final String getText(int start, int end) { return model.getText(start, end); } @Override public String getText(int paragraph) { return model.getText(paragraph); } public Paragraph<PS, S> getParagraph(int index) { return model.getParagraph(index); } @Override public StyledDocument<PS, S> subDocument(int start, int end) { return model.subDocument(start, end); } @Override public StyledDocument<PS, S> subDocument(int paragraphIndex) { return model.subDocument(paragraphIndex); } /** * Returns the selection range in the given paragraph. */ public IndexRange getParagraphSelection(int paragraph) { return model.getParagraphSelection(paragraph); } /** * Returns the style of the character with the given index. * If {@code index} points to a line terminator character, * the last style used in the paragraph terminated by that * line terminator is returned. */ public S getStyleOfChar(int index) { return model.getStyleOfChar(index); } /** * Returns the style at the given position. That is the style of the * character immediately preceding {@code position}, except when * {@code position} points to a paragraph boundary, in which case it * is the style at the beginning of the latter paragraph. * * <p>In other words, most of the time {@code getStyleAtPosition(p)} * is equivalent to {@code getStyleOfChar(p-1)}, except when {@code p} * points to a paragraph boundary, in which case it is equivalent to * {@code getStyleOfChar(p)}. */ public S getStyleAtPosition(int position) { return model.getStyleAtPosition(position); } /** * Returns the range of homogeneous style that includes the given position. * If {@code position} points to a boundary between two styled ranges, then * the range preceding {@code position} is returned. If {@code position} * points to a boundary between two paragraphs, then the first styled range * of the latter paragraph is returned. */ public IndexRange getStyleRangeAtPosition(int position) { return model.getStyleRangeAtPosition(position); } /** * Returns the styles in the given character range. */ public StyleSpans<S> getStyleSpans(int from, int to) { return model.getStyleSpans(from, to); } /** * Returns the styles in the given character range. */ public StyleSpans<S> getStyleSpans(IndexRange range) { return getStyleSpans(range.getStart(), range.getEnd()); } /** * Returns the style of the character with the given index in the given * paragraph. If {@code index} is beyond the end of the paragraph, the * style at the end of line is returned. If {@code index} is negative, it * is the same as if it was 0. */ public S getStyleOfChar(int paragraph, int index) { return model.getStyleOfChar(paragraph, index); } /** * Returns the style at the given position in the given paragraph. * This is equivalent to {@code getStyleOfChar(paragraph, position-1)}. */ public S getStyleAtPosition(int paragraph, int position) { return model.getStyleAtPosition(paragraph, position); } /** * Returns the range of homogeneous style that includes the given position * in the given paragraph. If {@code position} points to a boundary between * two styled ranges, then the range preceding {@code position} is returned. */ public IndexRange getStyleRangeAtPosition(int paragraph, int position) { return model.getStyleRangeAtPosition(paragraph, position); } /** * Returns styles of the whole paragraph. */ public StyleSpans<S> getStyleSpans(int paragraph) { return model.getStyleSpans(paragraph); } /** * Returns the styles in the given character range of the given paragraph. */ public StyleSpans<S> getStyleSpans(int paragraph, int from, int to) { return model.getStyleSpans(paragraph, from, to); } /** * Returns the styles in the given character range of the given paragraph. */ public StyleSpans<S> getStyleSpans(int paragraph, IndexRange range) { return getStyleSpans(paragraph, range.getStart(), range.getEnd()); } @Override public Position position(int row, int col) { return model.position(row, col); } @Override public Position offsetToPosition(int charOffset, Bias bias) { return model.offsetToPosition(charOffset, bias); } void scrollBy(Point2D deltas) { virtualFlow.scrollXBy(deltas.getX()); virtualFlow.scrollYBy(deltas.getY()); } void show(double y) { virtualFlow.show(y); } void showCaretAtBottom() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(); double y = caretBounds.getMaxY(); virtualFlow.showAtOffset(parIdx, getViewportHeight() - y); } void showCaretAtTop() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(); double y = caretBounds.getMinY(); virtualFlow.showAtOffset(parIdx, -y); } void requestFollowCaret() { followCaretRequested = true; requestLayout(); } private void followCaret() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(); double graphicWidth = cell.getNode().getGraphicPrefWidth(); Bounds region = extendLeft(caretBounds, graphicWidth); virtualFlow.show(parIdx, region); } /** * Sets style for the given character range. */ public void setStyle(int from, int to, S style) { model.setStyle(from, to, style); } /** * Sets style for the whole paragraph. */ public void setStyle(int paragraph, S style) { model.setStyle(paragraph, style); } /** * Sets style for the given range relative in the given paragraph. */ public void setStyle(int paragraph, int from, int to, S style) { model.setStyle(paragraph, from, to, style); } /** * Set multiple style ranges at once. This is equivalent to * <pre> * for(StyleSpan{@code <S>} span: styleSpans) { * setStyle(from, from + span.getLength(), span.getStyle()); * from += span.getLength(); * } * </pre> * but the actual implementation is more efficient. */ public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) { model.setStyleSpans(from, styleSpans); } /** * Set multiple style ranges of a paragraph at once. This is equivalent to * <pre> * for(StyleSpan{@code <S>} span: styleSpans) { * setStyle(paragraph, from, from + span.getLength(), span.getStyle()); * from += span.getLength(); * } * </pre> * but the actual implementation is more efficient. */ public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) { model.setStyleSpans(paragraph, from, styleSpans); } /** * Sets style for the whole paragraph. */ public void setParagraphStyle(int paragraph, PS paragraphStyle) { model.setParagraphStyle(paragraph, paragraphStyle); } /** * Resets the style of the given range to the initial style. */ public void clearStyle(int from, int to) { model.clearStyle(from, to); } /** * Resets the style of the given paragraph to the initial style. */ public void clearStyle(int paragraph) { model.clearStyle(paragraph); } /** * Resets the style of the given range in the given paragraph * to the initial style. */ public void clearStyle(int paragraph, int from, int to) { model.clearStyle(paragraph, from, to); } /** * Resets the style of the given paragraph to the initial style. */ public void clearParagraphStyle(int paragraph) { model.clearParagraphStyle(paragraph); } @Override public void replaceText(int start, int end, String text) { model.replaceText(start, end, text); } @Override public void replace(int start, int end, StyledDocument<PS, S> replacement) { model.replace(start, end, replacement); } @Override public void selectRange(int anchor, int caretPosition) { model.selectRange(anchor, caretPosition); } /** * {@inheritDoc} * @deprecated You probably meant to use {@link #moveTo(int)}. This method will be made * package-private in the future */ @Deprecated @Override public void positionCaret(int pos) { model.positionCaret(pos); } public void dispose() { subscriptions.unsubscribe(); model.dispose(); behavior.dispose(); virtualFlow.dispose(); } @Override protected void layoutChildren() { virtualFlow.resize(getWidth(), getHeight()); if(followCaretRequested) { followCaretRequested = false; followCaret(); } // position popup PopupWindow popup = getPopupWindow(); PopupAlignment alignment = getPopupAlignment(); UnaryOperator<Point2D> adjustment = _popupAnchorAdjustment.getValue(); if(popup != null) { positionPopup(popup, alignment, adjustment); } } private Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> createCell( Paragraph<PS, S> paragraph, BiConsumer<? super TextExt, S> applyStyle, BiConsumer<TextFlow, PS> applyParagraphStyle) { ParagraphBox<PS, S> box = new ParagraphBox<>(paragraph, applyParagraphStyle, applyStyle); box.highlightFillProperty().bind(highlightFill); box.highlightTextFillProperty().bind(highlightTextFill); box.wrapTextProperty().bind(wrapTextProperty()); box.graphicFactoryProperty().bind(paragraphGraphicFactoryProperty()); box.graphicOffset.bind(virtualFlow.breadthOffsetProperty()); Val<Boolean> hasCaret = Val.combine( box.indexProperty(), currentParagraphProperty(), (bi, cp) -> bi.intValue() == cp.intValue()); Subscription hasCaretPseudoClass = hasCaret.values().subscribe(value -> box.pseudoClassStateChanged(HAS_CARET, value)); Subscription firstParPseudoClass = box.indexProperty().values().subscribe(idx -> box.pseudoClassStateChanged(FIRST_PAR, idx == 0)); Subscription lastParPseudoClass = EventStreams.combine( box.indexProperty().values(), getParagraphs().sizeProperty().values() ).subscribe(in -> in.exec((i, n) -> box.pseudoClassStateChanged(LAST_PAR, i == n-1))); // caret is visible only in the paragraph with the caret Val<Boolean> cellCaretVisible = hasCaret.flatMap(x -> x ? caretVisible : Val.constant(false)); box.caretVisibleProperty().bind(cellCaretVisible); // bind cell's caret position to area's caret column, // when the cell is the one with the caret box.caretPositionProperty().bind(hasCaret.flatMap(has -> has ? caretColumnProperty() : Val.constant(0))); // keep paragraph selection updated ObjectBinding<IndexRange> cellSelection = Bindings.createObjectBinding(() -> { int idx = box.getIndex(); return idx != -1 ? getParagraphSelection(idx) : StyledTextArea.EMPTY_RANGE; }, selectionProperty(), box.indexProperty()); box.selectionProperty().bind(cellSelection); return new Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>() { @Override public ParagraphBox<PS, S> getNode() { return box; } @Override public void updateIndex(int index) { box.setIndex(index); } @Override public void dispose() { box.highlightFillProperty().unbind(); box.highlightTextFillProperty().unbind(); box.wrapTextProperty().unbind(); box.graphicFactoryProperty().unbind(); box.graphicOffset.unbind(); hasCaretPseudoClass.unsubscribe(); firstParPseudoClass.unsubscribe(); lastParPseudoClass.unsubscribe(); box.caretVisibleProperty().unbind(); box.caretPositionProperty().unbind(); box.selectionProperty().unbind(); cellSelection.dispose(); } }; } private ParagraphBox<PS, S> getCell(int index) { return virtualFlow.getCell(index).getNode(); } private EventStream<MouseOverTextEvent> mouseOverTextEvents(ObservableSet<ParagraphBox<PS, S>> cells, Duration delay) { return merge(cells, c -> c.stationaryIndices(delay).map(e -> e.unify( l -> l.map((pos, charIdx) -> MouseOverTextEvent.beginAt(c.localToScreen(pos), getParagraphOffset(c.getIndex()) + charIdx)), r -> MouseOverTextEvent.end()))); } private int getParagraphOffset(int parIdx) { return position(parIdx, 0).toOffset(); } private void positionPopup( PopupWindow popup, PopupAlignment alignment, UnaryOperator<Point2D> adjustment) { Optional<Bounds> bounds = null; switch(alignment.getAnchorObject()) { case CARET: bounds = getCaretBoundsOnScreen(); break; case SELECTION: bounds = getSelectionBoundsOnScreen(); break; } bounds.ifPresent(b -> { double x = 0, y = 0; switch(alignment.getHorizontalAlignment()) { case LEFT: x = b.getMinX(); break; case H_CENTER: x = (b.getMinX() + b.getMaxX()) / 2; break; case RIGHT: x = b.getMaxX(); break; } switch(alignment.getVerticalAlignment()) { case TOP: y = b.getMinY(); case V_CENTER: y = (b.getMinY() + b.getMaxY()) / 2; break; case BOTTOM: y = b.getMaxY(); break; } Point2D anchor = adjustment.apply(new Point2D(x, y)); popup.setAnchorX(anchor.getX()); popup.setAnchorY(anchor.getY()); }); } private Optional<Bounds> getCaretBoundsOnScreen() { return virtualFlow.getCellIfVisible(getCurrentParagraph()) .map(c -> c.getNode().getCaretBoundsOnScreen()); } private Optional<Bounds> getSelectionBoundsOnScreen() { IndexRange selection = getSelection(); if(selection.getLength() == 0) { return getCaretBoundsOnScreen(); } Bounds[] bounds = virtualFlow.visibleCells().stream() .map(c -> c.getNode().getSelectionBoundsOnScreen()) .filter(Optional::isPresent) .map(Optional::get) .toArray(Bounds[]::new); if(bounds.length == 0) { return Optional.empty(); } double minX = Stream.of(bounds).mapToDouble(Bounds::getMinX).min().getAsDouble(); double maxX = Stream.of(bounds).mapToDouble(Bounds::getMaxX).max().getAsDouble(); double minY = Stream.of(bounds).mapToDouble(Bounds::getMinY).min().getAsDouble(); double maxY = Stream.of(bounds).mapToDouble(Bounds::getMaxY).max().getAsDouble(); return Optional.of(new BoundingBox(minX, minY, maxX-minX, maxY-minY)); } private <T> void subscribeTo(EventStream<T> src, Consumer<T> cOnsumer) { manageSubscription(src.subscribe(cOnsumer)); } private void manageSubscription(Subscription subscription) { subscriptions = subscriptions.and(subscription); } private void manageBinding(Binding<?> binding) { subscriptions = subscriptions.and(binding::dispose); } private static Bounds extendLeft(Bounds b, double w) { if(w == 0) { return b; } else { return new BoundingBox( b.getMinX() - w, b.getMinY(), b.getWidth() + w, b.getHeight()); } } private static EventStream<Boolean> booleanPulse(Duration duration, EventStream<?> restartImpulse) { EventStream<?> ticks = EventStreams.restartableTicks(duration, restartImpulse); return StateMachine.init(false) .on(restartImpulse.withDefaultEvent(null)).transition((state, impulse) -> true) .on(ticks).transition((state, tick) -> !state) .toStateStream(); } }
package scal.io.liger; import android.content.Context; import android.content.res.AssetManager; import android.os.Environment; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import scal.io.liger.model.Dependency; import scal.io.liger.model.StoryPath; import scal.io.liger.model.StoryPathLibrary; /** * @author Matt Bogner * @author Josh Steiner */ public class JsonHelper { private static final String TAG = "JsonHelper"; private static final String LIGER_DIR = "Liger"; private static File selectedJSONFile = null; private static String selectedJSONPath = null; private static ArrayList<String> jsonFileNamesList = null; private static ArrayList<File> jsonFileList = null; private static ArrayList<String> jsonPathList = null; private static HashMap<String, String> jsonKeyToPath = null; private static String sdLigerFilePath = null; //private static String language = null; // TEMP // TEMP - for gathering insance files to test references public static ArrayList<String> getInstancePaths() { ArrayList<String> results = new ArrayList<String>(); File jsonFolder = new File(getSdLigerFilePath()); // check for nulls (uncertain as to cause of nulls) if ((jsonFolder != null) && (jsonFolder.listFiles() != null)) { for (File jsonFile : jsonFolder.listFiles()) { if (jsonFile.getName().contains("-instance") && !jsonFile.isDirectory()) { Log.d("FILES", "FOUND INSTANCE PATH: " + jsonFile.getPath()); results.add(jsonFile.getPath()); } } } else { Log.d("FILES", getSdLigerFilePath() + " WAS NULL OR listFiles() RETURNED NULL, CANNOT GATHER INSTANCE PATHS"); } return results; } public static ArrayList<String> getLibraryInstancePaths() { ArrayList<String> results = new ArrayList<String>(); File jsonFolder = new File(getSdLigerFilePath()); // check for nulls (uncertain as to cause of nulls) if ((jsonFolder != null) && (jsonFolder.listFiles() != null)) { for (File jsonFile : jsonFolder.listFiles()) { if (jsonFile.getName().contains("-library-instance") && !jsonFile.isDirectory()) { Log.d("FILES", "FOUND LIBRARY INSTANCE PATH: " + jsonFile.getPath()); results.add(jsonFile.getPath()); } } } else { Log.d("FILES", getSdLigerFilePath() + " WAS NULL OR listFiles() RETURNED NULL, CANNOT GATHER INSTANCE PATHS"); } return results; } public static String loadJSONFromPath(String jsonPath, String language) { String jsonString = ""; String sdCardState = Environment.getExternalStorageState(); String localizedFilePath = jsonPath; // check language setting and insert country code if necessary if (language != null) { // just in case, check whether country code has already been inserted if (jsonPath.lastIndexOf("-" + language + jsonPath.substring(jsonPath.lastIndexOf("."))) < 0) { localizedFilePath = jsonPath.substring(0, jsonPath.lastIndexOf(".")) + "-" + language + jsonPath.substring(jsonPath.lastIndexOf(".")); } Log.d("LANGUAGE", "loadJSONFromPath() - LOCALIZED PATH: " + localizedFilePath); } if (sdCardState.equals(Environment.MEDIA_MOUNTED)) { try { File jsonFile = new File(jsonPath); InputStream jsonStream = new FileInputStream(jsonFile); File localizedFile = new File(localizedFilePath); // if there is a file at the localized path, use that instead if ((localizedFile.exists()) && (!jsonPath.equals(localizedFilePath))) { Log.d("LANGUAGE", "loadJSONFromPath() - USING LOCALIZED FILE: " + localizedFilePath); jsonStream = new FileInputStream(localizedFile); } int size = jsonStream.available(); byte[] buffer = new byte[size]; jsonStream.read(buffer); jsonStream.close(); jsonString = new String(buffer); } catch (IOException e) { Log.e(TAG, "READING JSON FILE FROM SD CARD FAILED: " + e.getMessage()); } } else { System.err.println("SD CARD NOT FOUND"); } return jsonString; } public static String loadJSON(Context context, String language) { // check for file // paths to actual files should fully qualified // paths within zip files should be relative // (or at least not resolve to actual files) File checkFile = new File(selectedJSONPath); //if (selectedJSONFile.exists()) { // return loadJSON(selectedJSONFile, language); //} else { if (checkFile.exists()) { return loadJSON(checkFile, language); } else { return loadJSONFromZip(selectedJSONPath, context, language); } } public static String loadJSON(File file, String language) { if(null == file) { return null; } String jsonString = ""; String sdCardState = Environment.getExternalStorageState(); String localizedFilePath = file.getPath(); // check language setting and insert country code if necessary if (language != null) { // just in case, check whether country code has already been inserted if (file.getPath().lastIndexOf("-" + language + file.getPath().substring(file.getPath().lastIndexOf("."))) < 0) { localizedFilePath = file.getPath().substring(0, file.getPath().lastIndexOf(".")) + "-" + language + file.getPath().substring(file.getPath().lastIndexOf(".")); } Log.d("LANGUAGE", "loadJSON() - LOCALIZED PATH: " + localizedFilePath); } if (sdCardState.equals(Environment.MEDIA_MOUNTED)) { try { InputStream jsonStream = new FileInputStream(file); File localizedFile = new File(localizedFilePath); // if there is a file at the localized path, use that instead if ((localizedFile.exists()) && (!file.getPath().equals(localizedFilePath))) { Log.d("LANGUAGE", "loadJSON() - USING LOCALIZED FILE: " + localizedFilePath); jsonStream = new FileInputStream(localizedFile); } int size = jsonStream.available(); byte[] buffer = new byte[size]; jsonStream.read(buffer); jsonStream.close(); jsonString = new String(buffer); } catch (IOException e) { Log.e(TAG, "READING JSON FILE FRON SD CARD FAILED: " + e.getMessage()); } } else { Log.e(TAG, "SD CARD NOT FOUND"); } return jsonString; } // NEW // merged with regular loadJSON method /* public static String loadJSONFromZip(Context context, String language) { return loadJSONFromZip(selectedJSONPath, context, language); } */ public static String loadJSONFromZip(String jsonFilePath, Context context, String language) { Log.d(" *** TESTING *** ", "NEW METHOD loadJSONFromZip CALLED FOR " + jsonFilePath); if(null == jsonFilePath) { return null; } String jsonString = ""; String localizedFilePath = jsonFilePath; // check language setting and insert country code if necessary if (language != null) { // just in case, check whether country code has already been inserted if (jsonFilePath.lastIndexOf("-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."))) < 0) { localizedFilePath = jsonFilePath.substring(0, jsonFilePath.lastIndexOf(".")) + "-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf(".")); } Log.d("LANGUAGE", "loadJSONFromZip() - LOCALIZED PATH: " + localizedFilePath); } // removed sd card check as expansion file should not be located on sd card try { InputStream jsonStream = ZipHelper.getFileInputStream(localizedFilePath, context); // if there is no result with the localized path, retry with default path if ((jsonStream == null) && (!jsonFilePath.equals(localizedFilePath))) { jsonStream = ZipHelper.getFileInputStream(jsonFilePath, context); } else { Log.d("LANGUAGE", "loadJSONFromZip() - USING LOCALIZED FILE: " + localizedFilePath); } if (jsonStream == null) return null; int size = jsonStream.available(); byte[] buffer = new byte[size]; jsonStream.read(buffer); jsonStream.close(); jsonString = new String(buffer); } catch (IOException ioe) { Log.e(TAG, "reading json file " + jsonFilePath + " from ZIP file failed: " + ioe.getMessage()); } return jsonString; } public static String getSdLigerFilePath() { return sdLigerFilePath; } private static void copyFilesToSdCard(Context context, String basePath) { copyFileOrDir(context, basePath, ""); // copy all files in assets folder in my project } private static void copyFileOrDir(Context context, String assetFromPath, String baseToPath) { AssetManager assetManager = context.getAssets(); String assets[] = null; try { Log.i("tag", "copyFileOrDir() "+assetFromPath); assets = assetManager.list(assetFromPath); if (assets.length == 0) { copyFile(context, assetFromPath, baseToPath); } else { String fullPath = baseToPath + assetFromPath; Log.i("tag", "path="+fullPath); File dir = new File(fullPath); if (!dir.exists() && !assetFromPath.startsWith("images") && !assetFromPath.startsWith("sounds") && !assetFromPath.startsWith("webkit")) if (!dir.mkdirs()) Log.i("tag", "could not create dir "+fullPath); for (int i = 0; i < assets.length; ++i) { String p; if (assetFromPath.equals("")) p = ""; else p = assetFromPath + "/"; if (!assetFromPath.startsWith("images") && !assetFromPath.startsWith("sounds") && !assetFromPath.startsWith("webkit")) copyFileOrDir(context, p + assets[i], baseToPath); } } } catch (IOException ex) { Log.e("tag", "I/O Exception", ex); } } private static void copyFile(Context context, String fromFilename, String baseToPath) { AssetManager assetManager = context.getAssets(); if (fromFilename.endsWith(".obb")) return; // let's not copy .obb files, they get copied elseware InputStream in = null; OutputStream out = null; String newFileName = null; try { Log.i("tag", "copyFile() "+fromFilename); in = assetManager.open(fromFilename); if (fromFilename.endsWith(".jpg")) // extension was added to avoid compression on APK file newFileName = baseToPath + fromFilename.substring(0, fromFilename.length()-4); else newFileName = baseToPath + fromFilename; out = new FileOutputStream(newFileName); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", "Exception in copyFile() of "+newFileName); Log.e("tag", "Exception in copyFile() "+e.toString()); } } private static void copyObbFile(Context context, String fromFilename, String toPath) { AssetManager assetManager = context.getAssets(); InputStream in = null; OutputStream out = null; try { Log.i("tag", "copyObbFile() "+fromFilename); in = assetManager.open(fromFilename); out = new FileOutputStream(toPath); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", "Exception in copyObbFile() of "+toPath); Log.e("tag", "Exception in copyObbFile() "+e.toString()); } } public static void setupFileStructure(Context context) { String sdCardState = Environment.getExternalStorageState(); if (sdCardState.equals(Environment.MEDIA_MOUNTED)) { // FIXME we need to remove this, it seems like the popup stuff requires it even though we acutally read files from .obb not the Liger folder // need to switch to context-based external directory // String sdCardFolderPath = Environment.getExternalStorageDirectory().getPath(); String sdCardFolderPath = context.getExternalFilesDir(null).getPath(); // sdLigerFilePath = sdCardFolderPath + File.separator + LIGER_DIR + File.separator; sdLigerFilePath = sdCardFolderPath + File.separator; Log.d("FILES", "NEW EXTERNAL DIRECTORY: " + sdLigerFilePath); new File(sdLigerFilePath).mkdirs(); // based on http://stackoverflow.com/questions/4447477/android-how-to-copy-files-from-assets-folder-to-sdcard/8366081#8366081 // copyFilesToSdCard(context, sdLigerFilePath); // this used to copy all assets to /sdcard/Liger // copy the zipped assets to the right folder String inputAssetFilename = "main.1.obb"; // FIXME we should parse this out from the assets so its always right String zipPath = ZipHelper.getExtensionFolderPath(context); String zipFilename = ZipHelper.getExtensionZipFilename(context, inputAssetFilename); String zipFullpath = zipPath + zipFilename; // Log.d("JsonHelper", "copying obb file '" + inputAssetFilename + "' to '" + zipFullpath + "'"); // new File(zipPath).mkdirs(); // FIXME check size & datestamp and don't copy if it exists? maybe we can check hash? key? // copyObbFile(context, inputAssetFilename, zipFullpath); } else { Log.e(TAG, "SD CARD NOT FOUND"); // FIXME don't bury errors in logs, we should let this crash } } private static void setupJSONFileList() { // HARD CODING LIST // rebuild list to pick up new save files // if (jsonFileNamesList == null) { File ligerFile_1 = new File(sdLigerFilePath + "/default/default_library/default_library.json"); File ligerFile_2 = new File(sdLigerFilePath + "/default/learning_guide_1/learning_guide_1.json"); File ligerFile_3 = new File(sdLigerFilePath + "/default/learning_guide_2/learning_guide_2.json"); File ligerFile_4 = new File(sdLigerFilePath + "/default/learning_guide_3/learning_guide_3.json"); File ligerFile_5 = new File(sdLigerFilePath + "/default/learning_guide_library.json"); File ligerFile_6 = new File(sdLigerFilePath + "/default/learning_guide_library_SAVE.json"); File ligerFile_7 = new File(sdLigerFilePath + "/default/learning_guide_1/learning_guide_1_library.json"); File ligerFile_8 = new File(sdLigerFilePath + "/default/learning_guide_2/learning_guide_2_library.json"); File ligerFile_9= new File(sdLigerFilePath + "/default/learning_guide_3/learning_guide_3_library.json"); jsonFileNamesList = new ArrayList<String>(); jsonFileNamesList.add(ligerFile_1.getName()); jsonFileNamesList.add(ligerFile_2.getName()); jsonFileNamesList.add(ligerFile_3.getName()); jsonFileNamesList.add(ligerFile_4.getName()); jsonFileNamesList.add(ligerFile_5.getName()); jsonFileNamesList.add(ligerFile_6.getName()); jsonFileNamesList.add(ligerFile_7.getName()); jsonFileNamesList.add(ligerFile_8.getName()); jsonFileNamesList.add(ligerFile_9.getName()); jsonFileList = new ArrayList<File>(); jsonFileList.add(ligerFile_1); jsonFileList.add(ligerFile_2); jsonFileList.add(ligerFile_3); jsonFileList.add(ligerFile_4); jsonFileList.add(ligerFile_5); jsonFileList.add(ligerFile_6); jsonFileList.add(ligerFile_7); jsonFileList.add(ligerFile_8); jsonFileList.add(ligerFile_9); jsonPathList = new ArrayList<String>(); jsonPathList.add("default/default_library/default_library.json"); jsonPathList.add("default/learning_guide_1/learning_guide_1.json"); jsonPathList.add("default/learning_guide_2/learning_guide_2.json"); jsonPathList.add("default/learning_guide_3/learning_guide_3.json"); jsonPathList.add("default/learning_guide_library.json"); jsonPathList.add("default/learning_guide_library_SAVE.json"); jsonPathList.add("default/learning_guide_1/learning_guide_1_library.json"); jsonPathList.add("default/learning_guide_2/learning_guide_2_library.json"); jsonPathList.add("default/learning_guide_3/learning_guide_3_library.json"); jsonKeyToPath = new HashMap<String, String>(); jsonKeyToPath.put("default_library", "default/default_library/default_library.json"); jsonKeyToPath.put("learning_guide_1.json", "default/learning_guide_1/learning_guide_1.json"); jsonKeyToPath.put("learning_guide_2.json", "default/learning_guide_2/learning_guide_2.json"); jsonKeyToPath.put("learning_guide_3.json", "default/learning_guide_3/learning_guide_3.json"); jsonKeyToPath.put("learning_guide_library", "default/learning_guide_library.json"); jsonKeyToPath.put("learning_guide_library_SAVE", "default/learning_guide_library_SAVE.json"); jsonKeyToPath.put("learning_guide_1_library", "default/learning_guide_1/learning_guide_1_library.json"); jsonKeyToPath.put("learning_guide_2_library", "default/learning_guide_2/learning_guide_2_library.json"); jsonKeyToPath.put("learning_guide_3_library", "default/learning_guide_3/learning_guide_3_library.json"); for (File jsonFile : getLibraryInstanceFiles()) { jsonFileNamesList.add(jsonFile.getName()); jsonFileList.add(jsonFile); jsonPathList.add(jsonFile.getPath()); jsonKeyToPath.put(jsonFile.getName(), jsonFile.getPath()); } } public static ArrayList<File> getInstanceFiles() { ArrayList<File> results = new ArrayList<File>(); File jsonFolder = new File(getSdLigerFilePath()); // check for nulls (uncertain as to cause of nulls) if ((jsonFolder != null) && (jsonFolder.listFiles() != null)) { for (File jsonFile : jsonFolder.listFiles()) { if (jsonFile.getName().contains("-instance") && !jsonFile.isDirectory()) { Log.d("FILES", "FOUND INSTANCE FILE: " + jsonFile.getName()); File localFile = new File(jsonFile.getPath()); results.add(localFile); } } } else { Log.d("FILES", getSdLigerFilePath() + " WAS NULL OR listFiles() RETURNED NULL, CANNOT GATHER INSTANCE FILES"); } return results; } public static ArrayList<File> getLibraryInstanceFiles() { ArrayList<File> results = new ArrayList<File>(); File jsonFolder = new File(getSdLigerFilePath()); // check for nulls (uncertain as to cause of nulls) if ((jsonFolder != null) && (jsonFolder.listFiles() != null)) { for (File jsonFile : jsonFolder.listFiles()) { if (jsonFile.getName().contains("-library-instance") && !jsonFile.isDirectory()) { Log.d("FILES", "FOUND LIBRARY INSTANCE FILE: " + jsonFile.getName()); File localFile = new File(jsonFile.getPath()); results.add(localFile); } } } else { Log.d("FILES", getSdLigerFilePath() + " WAS NULL OR listFiles() RETURNED NULL, CANNOT GATHER INSTANCE FILES"); } return results; } public static String[] getJSONFileList() { //ensure path has been set if(null == sdLigerFilePath) { return null; } setupJSONFileList(); /* File ligerDir = new File(sdLigerFilePath); if (ligerDir != null) { for (File file : ligerDir.listFiles()) { if (file.getName().endsWith(".json")) { jsonFileNamesList.add(file.getName()); jsonFileList.add(file); } } } File defaultLigerDir = new File(sdLigerFilePath + "/default/"); if (defaultLigerDir != null) { for (File file : defaultLigerDir.listFiles()) { if (file.getName().endsWith(".json")) { jsonFileNamesList.add(file.getName()); jsonFileList.add(file); } } } */ return jsonFileNamesList.toArray(new String[jsonFileNamesList.size()]); } public static String getJsonPathByKey(String key) { setupJSONFileList(); if (jsonKeyToPath.containsKey(key)) { return jsonKeyToPath.get(key); } else { return null; } } public static File setSelectedJSONFile(int index) { selectedJSONFile = jsonFileList.get(index); return selectedJSONFile; } public static String setSelectedJSONPath(int index) { selectedJSONPath = jsonPathList.get(index); return selectedJSONPath; } private static void addFileToSDCard(InputStream jsonInputStream, String filePath) { OutputStream outputStream = null; try { // write the inputStream to a FileOutputStream outputStream = new FileOutputStream(new File(sdLigerFilePath + filePath)); int read = 0; byte[] bytes = new byte[1024]; while ((read = jsonInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } } catch (IOException e) { e.printStackTrace(); } finally { if (jsonInputStream != null) { try { jsonInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static StoryPathLibrary loadStoryPathLibrary(String jsonFilePath, ArrayList<String> referencedFiles, Context context, String language) { String storyPathLibraryJson = ""; String sdCardState = Environment.getExternalStorageState(); String localizedFilePath = jsonFilePath; // check language setting and insert country code if necessary if (language != null) { // just in case, check whether country code has already been inserted if (jsonFilePath.lastIndexOf("-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."))) < 0) { localizedFilePath = jsonFilePath.substring(0, jsonFilePath.lastIndexOf(".")) + "-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf(".")); } Log.d("LANGUAGE", "loadStoryPathLibrary() - LOCALIZED PATH: " + localizedFilePath); } File f = new File(localizedFilePath); if ((!f.exists()) && (!localizedFilePath.equals(jsonFilePath))) { f = new File(jsonFilePath); } else { Log.d("LANGUAGE", "loadStoryPathLibrary() - USING LOCALIZED FILE: " + localizedFilePath); } if (sdCardState.equals(Environment.MEDIA_MOUNTED)) { try { InputStream jsonStream = new FileInputStream(f); int size = jsonStream.available(); byte[] buffer = new byte[size]; jsonStream.read(buffer); jsonStream.close(); storyPathLibraryJson = new String(buffer); } catch (IOException ioe) { Log.e(TAG, "reading json file " + jsonFilePath + " from SD card failed: " + ioe.getMessage()); return null; } } else { Log.e(TAG, "SD card not found"); return null; } return deserializeStoryPathLibrary(storyPathLibraryJson, f.getPath(), referencedFiles, context); } // NEW public static StoryPathLibrary loadStoryPathLibraryFromZip(String jsonFilePath, ArrayList<String> referencedFiles, Context context, String language) { Log.d(" *** TESTING *** ", "NEW METHOD loadStoryPathLibraryFromZip CALLED FOR " + jsonFilePath); String storyPathLibraryJson = ""; String localizedFilePath = jsonFilePath; // check language setting and insert country code if necessary if (language != null) { // just in case, check whether country code has already been inserted if (jsonFilePath.lastIndexOf("-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."))) < 0) { localizedFilePath = jsonFilePath.substring(0, jsonFilePath.lastIndexOf(".")) + "-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf(".")); } Log.d("LANGUAGE", "loadStoryPathLibraryFromZip() - LOCALIZED PATH: " + localizedFilePath); } // removed sd card check as expansion file should not be located on sd card try { InputStream jsonStream = ZipHelper.getFileInputStream(localizedFilePath, context); // if there is no result with the localized path, retry with default path if ((jsonStream == null) && (!localizedFilePath.equals(jsonFilePath))) { jsonStream = ZipHelper.getFileInputStream(jsonFilePath, context); } else { Log.d("LANGUAGE", "loadStoryPathLibraryFromZip() - USING LOCALIZED FILE: " + localizedFilePath); } int size = jsonStream.available(); byte[] buffer = new byte[size]; jsonStream.read(buffer); jsonStream.close(); storyPathLibraryJson = new String(buffer); } catch (IOException ioe) { Log.e(TAG, "reading json file " + jsonFilePath + " from ZIP file failed: " + ioe.getMessage()); return null; } return deserializeStoryPathLibrary(storyPathLibraryJson, jsonFilePath, referencedFiles, context); } public static StoryPathLibrary deserializeStoryPathLibrary(String storyPathLibraryJson, String jsonFilePath, ArrayList<String> referencedFiles, Context context) { GsonBuilder gBuild = new GsonBuilder(); gBuild.registerTypeAdapter(StoryPathLibrary.class, new StoryPathLibraryDeserializer()); Gson gson = gBuild.excludeFieldsWithoutExposeAnnotation().create(); StoryPathLibrary storyPathLibrary = gson.fromJson(storyPathLibraryJson, StoryPathLibrary.class); // a story path library model must have a file location to manage relative paths // if it is loaded from a saved state, the location should already be set if ((jsonFilePath == null) || (jsonFilePath.length() == 0)) { if ((storyPathLibrary.getFileLocation() == null) || (storyPathLibrary.getFileLocation().length() == 0)) { Log.e(TAG, "file location for story path library " + storyPathLibrary.getId() + " could not be determined"); return null; } } else { File checkFile = new File(jsonFilePath); if (!checkFile.exists()) { storyPathLibrary.setFileLocation(jsonFilePath); // FOR NOW, DON'T SAVE ACTIAL FILE LOCATIONS } } // construct and insert dependencies for (String referencedFile : referencedFiles) { Dependency dependency = new Dependency(); dependency.setDependencyFile(referencedFile); // extract id from path/file name // assumes format <path/library id>-instance-<timestamp>.json // assumes path/library id doesn't not contain "-" String derivedId = referencedFile.substring(referencedFile.lastIndexOf(File.separator) + 1); derivedId = derivedId.substring(0, derivedId.indexOf("-")); dependency.setDependencyId(derivedId); storyPathLibrary.addDependency(dependency); Log.d("FILES", "DEPENDENCY: " + derivedId + " -> " + referencedFile); } storyPathLibrary.setCardReferences(); storyPathLibrary.initializeObservers(); storyPathLibrary.setContext(context); return storyPathLibrary; } public static String getStoryPathLibrarySaveFileName(StoryPathLibrary storyPathLibrary) { Log.d(" *** TESTING *** ", "NEW METHOD getStoryPathLibrarySaveFileName CALLED FOR " + storyPathLibrary.getId()); Date timeStamp = new Date(); //String jsonFilePath = storyPathLibrary.buildZipPath(storyPathLibrary.getId() + "_" + timeStamp.getTime() + ".json"); //TEMP String jsonFilePath = storyPathLibrary.buildTargetPath(storyPathLibrary.getId() + "-library-instance-" + timeStamp.getTime() + ".json"); return jsonFilePath; } public static boolean saveStoryPathLibrary(StoryPathLibrary storyPathLibrary, String jsonFilePath) { Log.d(" *** TESTING *** ", "NEW METHOD saveStoryPathLibrary CALLED FOR " + storyPathLibrary.getId() + " -> " + jsonFilePath); String sdCardState = Environment.getExternalStorageState(); if (sdCardState.equals(Environment.MEDIA_MOUNTED)) { try { File storyPathLibraryFile = new File(jsonFilePath + ".swap"); // NEED TO WRITE TO SWAP AND COPY if (storyPathLibraryFile.exists()) { storyPathLibraryFile.delete(); } storyPathLibraryFile.createNewFile(); FileOutputStream storyPathLibraryStream = new FileOutputStream(storyPathLibraryFile); String storyPathLibraryJson = serializeStoryPathLibrary(storyPathLibrary); byte storyPathLibraryData[] = storyPathLibraryJson.getBytes(); storyPathLibraryStream.write(storyPathLibraryData); storyPathLibraryStream.flush(); storyPathLibraryStream.close(); Process p = Runtime.getRuntime().exec("mv " + jsonFilePath + ".swap " + jsonFilePath); } catch (IOException ioe) { Log.e(TAG, "writing json file " + jsonFilePath + " to SD card failed: " + ioe.getMessage()); return false; } } else { Log.e(TAG, "SD card not found"); return false; } // update file location // TEMP - this will break references to content in zip file. unsure what to do... // storyPathLibrary.setFileLocation(jsonFilePath); return true; } public static String serializeStoryPathLibrary(StoryPathLibrary storyPathLibrary) { Log.d(" *** TESTING *** ", "NEW METHOD serializeStoryPathLibrary CALLED FOR " + storyPathLibrary.getId()); GsonBuilder gBuild = new GsonBuilder(); Gson gson = gBuild.excludeFieldsWithoutExposeAnnotation().create(); String storyPathLibraryJson = gson.toJson(storyPathLibrary); return storyPathLibraryJson; } public static StoryPath loadStoryPath(String jsonFilePath, StoryPathLibrary storyPathLibrary, ArrayList<String> referencedFiles, Context context, String language) { String storyPathJson = ""; String sdCardState = Environment.getExternalStorageState(); String localizedFilePath = jsonFilePath; // check language setting and insert country code if necessary if (language != null) { // just in case, check whether country code has already been inserted if (jsonFilePath.lastIndexOf("-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."))) < 0) { localizedFilePath = jsonFilePath.substring(0, jsonFilePath.lastIndexOf(".")) + "-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf(".")); } Log.d("LANGUAGE", "loadStoryPath() - LOCALIZED PATH: " + localizedFilePath); } File f = new File(localizedFilePath); if ((!f.exists()) && (!localizedFilePath.equals(jsonFilePath))) { f = new File(jsonFilePath); } else { Log.d("LANGUAGE", "loadStoryPath() - USING LOCALIZED FILE: " + localizedFilePath); } if (sdCardState.equals(Environment.MEDIA_MOUNTED)) { try { InputStream jsonStream = new FileInputStream(f); int size = jsonStream.available(); byte[] buffer = new byte[size]; jsonStream.read(buffer); jsonStream.close(); storyPathJson = new String(buffer); } catch (IOException ioe) { Log.e(TAG, "reading json file " + jsonFilePath + " from SD card failed: " + ioe.getMessage()); return null; } } else { Log.e(TAG, "SD card not found"); return null; } return deserializeStoryPath(storyPathJson, f.getPath(), storyPathLibrary, referencedFiles, context); } // NEW public static StoryPath loadStoryPathFromZip(String jsonFilePath, StoryPathLibrary storyPathLibrary, ArrayList<String> referencedFiles, Context context, String language) { Log.d(" *** TESTING *** ", "NEW METHOD loadStoryPathFromZip CALLED FOR " + jsonFilePath); String storyPathJson = ""; String localizedFilePath = jsonFilePath; // check language setting and insert country code if necessary if (language != null) { // just in case, check whether country code has already been inserted if (jsonFilePath.lastIndexOf("-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."))) < 0) { localizedFilePath = jsonFilePath.substring(0, jsonFilePath.lastIndexOf(".")) + "-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf(".")); } Log.d("LANGUAGE", "loadStoryPathFromZip() - LOCALIZED PATH: " + localizedFilePath); } // removed sd card check as expansion file should not be located on sd card try { InputStream jsonStream = ZipHelper.getFileInputStream(localizedFilePath, context); // if there is no result with the localized path, retry with default path if ((jsonStream == null) && (!localizedFilePath.equals(jsonFilePath))) { jsonStream = ZipHelper.getFileInputStream(jsonFilePath, context); } else { Log.d("LANGUAGE", "loadStoryPathFromZip() - USING LOCALIZED FILE: " + localizedFilePath); } int size = jsonStream.available(); byte[] buffer = new byte[size]; jsonStream.read(buffer); jsonStream.close(); storyPathJson = new String(buffer); } catch (IOException ioe) { Log.e(TAG, "reading json file " + jsonFilePath + " from ZIP file failed: " + ioe.getMessage()); return null; } return deserializeStoryPath(storyPathJson, jsonFilePath, storyPathLibrary, referencedFiles, context); } public static StoryPath deserializeStoryPath(String storyPathJson, String jsonFilePath, StoryPathLibrary storyPathLibrary, ArrayList<String> referencedFiles, Context context) { GsonBuilder gBuild = new GsonBuilder(); gBuild.registerTypeAdapter(StoryPath.class, new StoryPathDeserializer()); Gson gson = gBuild.excludeFieldsWithoutExposeAnnotation().create(); StoryPath storyPath = gson.fromJson(storyPathJson, StoryPath.class); // a story path model must have a file location to manage relative paths // if it is loaded from a saved state, the location should already be set if ((jsonFilePath == null) || (jsonFilePath.length() == 0)) { if ((storyPath.getFileLocation() == null) || (storyPath.getFileLocation().length() == 0)) { Log.e(TAG, "file location for story path " + storyPath.getId() + " could not be determined"); } } else { File checkFile = new File(jsonFilePath); if (!checkFile.exists()) { storyPath.setFileLocation(jsonFilePath); // FOR NOW, DON'T SAVE ACTIAL FILE LOCATIONS } } storyPath.setCardReferences(); storyPath.initializeObservers(); storyPath.setStoryPathLibrary(storyPathLibrary); // THIS MAY HAVE UNINTENDED CONSEQUENCES... if (storyPath.getStoryPathLibraryFile() == null) { storyPath.setStoryPathLibraryFile(storyPathLibrary.getFileLocation()); } // construct and insert dependencies for (String referencedFile : referencedFiles) { Dependency dependency = new Dependency(); dependency.setDependencyFile(referencedFile); // extract id from path/file name // assumes format <path/library id>-instance-<timestamp>.json // assumes path/library id doesn't not contain "-" String derivedId = referencedFile.substring(referencedFile.lastIndexOf(File.separator) + 1); derivedId = derivedId.substring(0, derivedId.indexOf("-")); dependency.setDependencyId(derivedId); storyPath.addDependency(dependency); Log.d("FILES", "DEPENDENCY: " + derivedId + " -> " + referencedFile); } storyPath.setContext(context); return storyPath; } public static String getStoryPathSaveFileName(StoryPath storyPath) { Log.d(" *** TESTING *** ", "NEW METHOD getStoryPathSaveFileName CALLED FOR " + storyPath.getId()); Date timeStamp = new Date(); //String jsonFilePath = storyPath.buildZipPath(storyPath.getId() + "_" + timeStamp.getTime() + ".json"); //TEMP String jsonFilePath = storyPath.buildTargetPath(storyPath.getId() + "-instance-" + timeStamp.getTime() + ".json"); return jsonFilePath; } public static boolean saveStoryPath(StoryPath storyPath, String jsonFilePath) { Log.d(" *** TESTING *** ", "NEW METHOD getStoryPathSaveFileName CALLED FOR " + storyPath.getId() + " -> " + jsonFilePath); String sdCardState = Environment.getExternalStorageState(); if (sdCardState.equals(Environment.MEDIA_MOUNTED)) { try { File storyPathFile = new File(jsonFilePath + ".swap"); // NEED TO WRITE TO SWAP AND COPY if (storyPathFile.exists()) { storyPathFile.delete(); } storyPathFile.createNewFile(); FileOutputStream storyPathStream = new FileOutputStream(storyPathFile); String storyPathJson = serializeStoryPath(storyPath); byte storyPathData[] = storyPathJson.getBytes(); storyPathStream.write(storyPathData); storyPathStream.flush(); storyPathStream.close(); Process p = Runtime.getRuntime().exec("mv " + jsonFilePath + ".swap " + jsonFilePath); } catch (IOException ioe) { Log.e(TAG, "writing json file " + jsonFilePath + " to SD card failed: " + ioe.getMessage()); return false; } } else { Log.e(TAG, "SD card not found"); return false; } // update file location // TEMP - this will break references to content in zip file. unsure what to do... // storyPath.setFileLocation(jsonFilePath); return true; } public static String serializeStoryPath(StoryPath storyPath) { Log.d(" *** TESTING *** ", "NEW METHOD serializeStoryPath CALLED FOR " + storyPath.getId()); GsonBuilder gBuild = new GsonBuilder(); Gson gson = gBuild.excludeFieldsWithoutExposeAnnotation().create(); // set aside references to prevent circular dependencies when serializing /* Context tempContext = storyPath.getContext(); StoryPathLibrary tempStoryPathLibrary = storyPath.getStoryPathLibrary(); storyPath.setContext(null); storyPath.setStoryPathLibrary(null); storyPath.clearObservers(); storyPath.clearCardReferences(); */ String storyPathJson = gson.toJson(storyPath); // restore references /* storyPath.setCardReferences(); storyPath.initializeObservers(); storyPath.setStoryPathLibrary(tempStoryPathLibrary); storyPath.setContext(tempContext); */ return storyPathJson; } }