answer
stringlengths
17
10.2M
package pl.pwr.hiervis.ui.control; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import pl.pwr.hiervis.util.Utils; import prefuse.Display; import prefuse.Visualization; import prefuse.controls.AbstractZoomControl; import prefuse.controls.WheelZoomControl; import prefuse.visual.VisualItem; public class ZoomScrollControl extends AbstractZoomControl { private double zoomStep; private int zoomDirection = -1; private int modifierMask = 0; public ZoomScrollControl() { this( 0.1, 10, 0.1 ); } public ZoomScrollControl( double min, double max, double step ) { setZoomOverItem( true ); setScrollDownZoomsOut( true ); setMinScale( min ); setMaxScale( max ); setZoomStep( step ); } /** * @return the value the zoom will be incremented by each time the user scrolls. */ public double getZoomStep() { return zoomStep; } /** * @param step * the value the zoom will be incremented by each time the user scrolls. */ public void setZoomStep( double step ) { if ( step <= 0 ) { throw new IllegalArgumentException( String.format( "step must be a positive number (%s)", step ) ); } zoomStep = step; } /** * @return true if scrolling the mouse wheel down causes the display to zoom out, false otherwise. */ public boolean getScrollDownZoomsOut() { return zoomDirection == -1; } /** * Sets the zoom behavior in response to mouse scrolls. * * @param scrollDownZoomsOut * If true, scrolling the mouse wheel down will cause the display to zoom out. * If false, scrolling the mouse wheel down will cause the display to zoom in. */ public void setScrollDownZoomsOut( boolean scrollDownZoomsOut ) { zoomDirection = scrollDownZoomsOut ? -1 : 1; } /** * @return whether the Alt key has to be held down while scrolling for zooming to occur. */ public boolean isModifierAlt() { return ( modifierMask & InputEvent.ALT_DOWN_MASK ) != 0; } /** * @return whether the Shift key has to be held down while scrolling for zooming to occur. */ public boolean isModifierShift() { return ( modifierMask & InputEvent.SHIFT_DOWN_MASK ) != 0; } /** * @return whether the Control key has to be held down while scrolling for zooming to occur. */ public boolean isModifierControl() { return ( modifierMask & InputEvent.CTRL_DOWN_MASK ) != 0; } /** * @return whether the Meta key has to be held down while scrolling for zooming to occur. */ public boolean isModifierMeta() { return ( modifierMask & InputEvent.META_DOWN_MASK ) != 0; } /** * @param alt * if true, Alt key will need to be held down */ public void setModifierAlt( boolean alt ) { modifierMask = alt ? ( modifierMask | InputEvent.ALT_DOWN_MASK ) : ( modifierMask & ~InputEvent.ALT_DOWN_MASK ); } /** * @param shift * if true, Shift key will need to be held down */ public void setModifierShift( boolean shift ) { modifierMask = shift ? ( modifierMask | InputEvent.SHIFT_DOWN_MASK ) : ( modifierMask & ~InputEvent.SHIFT_DOWN_MASK ); } /** * @param ctrl * if true, Control key will need to be held down */ public void setModifierControl( boolean ctrl ) { modifierMask = ctrl ? ( modifierMask | InputEvent.CTRL_DOWN_MASK ) : ( modifierMask & ~InputEvent.CTRL_DOWN_MASK ); } /** * @param meta * if true, Meta key will need to be held down */ public void setModifierMeta( boolean meta ) { modifierMask = meta ? ( modifierMask | InputEvent.META_DOWN_MASK ) : ( modifierMask & ~InputEvent.META_DOWN_MASK ); } /** * Sets modifiers that need to be down while scrolling for zooming to occur. * * @param alt * if true, Alt key will need to be held down * @param shift * if true, Shift key will need to be held down * @param ctrl * if true, Control key will need to be held down * @param meta * if true, Meta key will need to be held down */ public void setModifiers( boolean alt, boolean shift, boolean ctrl, boolean meta ) { modifierMask = 0 | ( alt ? InputEvent.ALT_DOWN_MASK : 0 ) | ( shift ? InputEvent.SHIFT_DOWN_MASK : 0 ) | ( ctrl ? InputEvent.CTRL_DOWN_MASK : 0 ) | ( meta ? InputEvent.META_DOWN_MASK : 0 ); } @Override public void itemWheelMoved( VisualItem item, MouseWheelEvent e ) { if ( m_zoomOverItem ) mouseWheelMoved( e ); } @Override public void mousePressed( MouseEvent e ) { Display d = (Display)e.getComponent(); d.requestFocus(); } @Override public void mouseWheelMoved( MouseWheelEvent e ) { if ( ( e.getModifiersEx() & modifierMask ) == modifierMask ) { Display d = (Display)e.getComponent(); d.requestFocus(); double zoomDelta = 1 + zoomDirection * zoomStep * e.getWheelRotation(); zoom( d, e.getPoint(), zoomDelta, false ); } } @Override public void keyPressed( KeyEvent e ) { // TODO: Remove this from here. Instead, make this a keybind that's bound to Frame housing the display // using SwingUIUtils.installOperation if ( e.isControlDown() && ( e.getKeyCode() == KeyEvent.VK_NUMPAD0 || e.getKeyCode() == KeyEvent.VK_0 ) ) { Utils.fitToBounds( (Display)e.getComponent(), Visualization.ALL_ITEMS, 0, 500 ); } } }
package nu.yona.app.utils; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MobileNumberFormatterTests { @Test public void formatPhoneNumber_keepsCorrectNumber() { String input = "+31612345678"; String expected = "+31612345678"; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } @Test public void formatPhoneNumber_fixesLeadingZeroInDutchNumber() { String input = "+310612345678"; String expected = "+31612345678"; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } @Test public void formatPhoneNumber_removesSpaces() { String input = "+316012 345 67"; String expected = "+31601234567"; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } @Test public void formatPhoneNumber_addsDutchCountryCodeToLeadingSix() { String input = "612345678"; String expected = "+31612345678"; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } @Test public void formatPhoneNumber_addsDutchCountryCodeToLeadingZeroSixAndRemovesZero() { String input = "0612345678"; String expected = "+31612345678"; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } @Test public void formatPhoneNumber_removesSpacesAndAddsDutchCountryCode() { String input = "6123 4567 8"; String expected = "+31612345678"; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } @Test public void formatPhoneNumber_formatsNonDutchNumber() { String input = "+45 612345678"; String expected = "+45612345678"; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } @Test public void formatPhoneNumber_shortNumber() { String input = "+31 456789"; String expected = "+31456789"; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } @Test public void formatPhoneNumber_veryShortNumber() { String input = "+31 456"; String expected = "+31456"; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } @Test public void formatPhoneNumber_onlyCountryCode() { String input = "+31"; String expected = "+31"; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } @Test public void formatPhoneNumber_empty() { String input = ""; String expected = ""; assertEquals(expected, MobileNumberFormatter.formatDutchAndInternationalNumber(input)); } }
package org.jboss.as.test.integration.web.security.servlet.methods; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.io.IOException; import java.net.URL; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpTrace; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests whether the <deny-uncovered-http-methods/> tag in web.xml behavior is correct. * * @author Jan Tymel */ @RunWith(Arquillian.class) @RunAsClient public class DenyUncoveredHttpMethodsTestCase { @ArquillianResource(SecuredServlet.class) URL deploymentURL; @Test public void testCorrectUserAndPassword() throws Exception { HttpGet httpGet = new HttpGet(getURL()); HttpResponse response = getHttpResponse(httpGet); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_UNAUTHORIZED)); } @Test public void testHeadMethod() throws Exception { HttpHead httpHead = new HttpHead(getURL()); HttpResponse response = getHttpResponse(httpHead); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_UNAUTHORIZED)); } @Test public void testTraceMethod() throws Exception { HttpTrace httpTrace = new HttpTrace(getURL()); HttpResponse response = getHttpResponse(httpTrace); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_METHOD_NOT_ALLOWED)); } @Test public void testPostMethod() throws Exception { HttpPost httpPost = new HttpPost(getURL()); HttpResponse response = getHttpResponse(httpPost); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN)); } @Test public void testPutMethod() throws Exception { HttpPut httpPut = new HttpPut(getURL()); HttpResponse response = getHttpResponse(httpPut); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN)); } @Test public void testDeleteMethod() throws Exception { HttpDelete httpDelete = new HttpDelete(getURL()); HttpResponse response = getHttpResponse(httpDelete); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN)); } @Test public void testOptionsMethod() throws Exception { HttpOptions httpOptions = new HttpOptions(getURL()); HttpResponse response = getHttpResponse(httpOptions); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN)); } /** * Tests whether the <deny-uncovered-http-methods/> tag filters methods before the servlet is called. This test creates * custom HTTP method and tries to invoke it. If <deny-uncovered-http-methods/> works correctly status code 403 should be * returned. 403 should be returned also in case the servlet returns anything else for unknown HTTP methods as well. * * @throws Exception */ @Test public void testCustomMethod() throws Exception { HttpUriRequest request = new HttpGet(getURL()) { @Override public String getMethod() { return "customMethod"; } }; HttpResponse response = getHttpResponse(request); assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN)); } private HttpResponse getHttpResponse(HttpUriRequest request) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); return response; } private int statusCodeOf(HttpResponse response) { return response.getStatusLine().getStatusCode(); } private String getURL() { return deploymentURL.toString() + "secured/"; } @Deployment public static WebArchive deployment() throws IOException { WebArchive war = ShrinkWrap.create(WebArchive.class, "deny-uncovered-http-methods.war"); war.addClass(SecuredServlet.class); Package warPackage = DenyUncoveredHttpMethodsTestCase.class.getPackage(); war.setWebXML(warPackage, "web.xml"); return war; } }
package de.ptb.epics.eve.editor.views.motoraxisview.addmultiplycomposite; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Date; import javax.xml.datatype.Duration; import org.apache.log4j.Logger; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.beans.BeansObservables; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.SelectObservableValue; import org.eclipse.jface.databinding.fieldassist.ControlDecorationSupport; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import de.ptb.epics.eve.data.DataTypes; import de.ptb.epics.eve.data.scandescription.Axis; import de.ptb.epics.eve.data.scandescription.PositionMode; import de.ptb.epics.eve.data.scandescription.axismode.AddMultiplyMode; import de.ptb.epics.eve.data.scandescription.axismode.AdjustParameter; import de.ptb.epics.eve.editor.views.motoraxisview.MotorAxisViewComposite; import de.ptb.epics.eve.util.swt.DoubleVerifyListener; import de.ptb.epics.eve.util.swt.IntegerVerifyListener; /** * @author Marcus Michalsky * @since 1.7 */ public class AddMultiplyComposite extends MotorAxisViewComposite implements PropertyChangeListener { private static final Logger LOGGER = Logger .getLogger(AddMultiplyComposite.class.getName()); private Axis axis; private AddMultiplyMode<?> addMultiplyMode; /* * VerifyListeners deactivated. They interfer with verify listeners set * by the databinding framework resulting in no calculations are written * to the AdjustParameter field. */ private Button startRadioButton; private Text startText; private ControlDecoration startTextControlDecoration; private SelectionListener startTextControlDecorationSelectionListener; private VerifyListener startTextVerifyListener; private FocusListener startTextFocusListener; private Button stopRadioButton; private Text stopText; private ControlDecoration stopTextControlDecoration; private SelectionListener stopTextControlDecorationSelectionListener; private VerifyListener stopTextVerifyListener; private FocusListener stopTextFocusListener; private Button stepwidthRadioButton; private Text stepwidthText; private ControlDecoration stepwidthTextControlDecoration; private SelectionListener stepwidhtTextControlDecorationSelectionListener; private VerifyListener stepwidthTextVerifyListener; private FocusListener stepwidthTextFocusListener; private Button stepcountRadioButton; private Text stepcountText; private VerifyListener stepcountTextVerifyListener; private FocusListener stepcountTextFocusListener; private Button mainAxisCheckBox; private Binding selectBinding; private SelectObservableValue selectionTargetObservable; private IObservableValue selectionModelObservable; private Binding startBinding; private IObservableValue startTargetObservable; private IObservableValue startModelObservable; private ControlDecorationSupport startDecoration; private Binding stopBinding; private IObservableValue stopTargetObservable; private IObservableValue stopModelObservable; private ControlDecorationSupport stopDecoration; private Binding stepwidthBinding; private IObservableValue stepwidthTargetObservable; private IObservableValue stepwidthModelObservable; private ControlDecorationSupport stepwidthDecoration; private Binding stepcountBinding; private IObservableValue stepcountTargetObservable; private IObservableValue stepcountModelObservable; private ControlDecorationSupport stepcountDecoration; private Binding mainAxisBinding; private IObservableValue mainAxisTargetObservable; private IObservableValue mainAxisModelObservable; private Image contentProposalImage; private final String descriptionText = "Click to open Date Selector"; /** * Constructor. * * @param parent the parent * @param style the style */ public AddMultiplyComposite(final Composite parent, final int style) { super(parent, style); this.contentProposalImage = FieldDecorationRegistry.getDefault() .getFieldDecoration( FieldDecorationRegistry.DEC_CONTENT_PROPOSAL) .getImage(); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; this.setLayout(gridLayout); // initialize start elements this.startRadioButton = new Button(this, SWT.RADIO); this.startRadioButton.setText("Start:"); this.startText = new Text(this, SWT.BORDER); GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.horizontalIndent = 7; gridData.grabExcessHorizontalSpace = true; this.startText.setLayoutData(gridData); this.startTextControlDecoration = new ControlDecoration(this.startText, SWT.LEFT | SWT.BOTTOM); this.startTextControlDecoration.setImage(contentProposalImage); this.startTextControlDecoration.setDescriptionText(this.descriptionText); this.startTextControlDecoration.setShowOnlyOnFocus(true); this.startTextControlDecorationSelectionListener = new DateTimeProposalSelectionListener(this.startText); this.startTextControlDecoration.addSelectionListener( startTextControlDecorationSelectionListener); this.startTextFocusListener = new TextFocusListener(startText); // end of: initialize start elements // initialize stop elements this.stopRadioButton = new Button(this, SWT.RADIO); this.stopRadioButton.setText("Stop:"); this.stopText = new Text(this, SWT.BORDER); gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.horizontalIndent = 7; gridData.grabExcessHorizontalSpace = true; this.stopText.setLayoutData(gridData); this.stopTextControlDecoration = new ControlDecoration(this.stopText, SWT.LEFT | SWT.BOTTOM); this.stopTextControlDecoration.setImage(contentProposalImage); this.stopTextControlDecoration.setDescriptionText(this.descriptionText); this.stopTextControlDecoration.setShowOnlyOnFocus(true); this.stopTextControlDecorationSelectionListener = new DateTimeProposalSelectionListener(this.stopText); this.stopTextControlDecoration.addSelectionListener( stopTextControlDecorationSelectionListener); this.stopTextFocusListener = new TextFocusListener(stopText); // end of: initialize stop elements // initialize step width elements this.stepwidthRadioButton = new Button(this, SWT.RADIO); this.stepwidthRadioButton.setText("Stepwidth:"); this.stepwidthText = new Text(this, SWT.BORDER); gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.horizontalIndent = 7; gridData.grabExcessHorizontalSpace = true; this.stepwidthText.setLayoutData(gridData); this.stepwidthTextControlDecoration = new ControlDecoration( this.stepwidthText, SWT.LEFT | SWT.BOTTOM); this.stepwidthTextControlDecoration.setImage(contentProposalImage); this.stepwidthTextControlDecoration .setDescriptionText(this.descriptionText); this.stepwidthTextControlDecoration.setShowOnlyOnFocus(true); this.stepwidhtTextControlDecorationSelectionListener = new DateTimeProposalSelectionListener(this.stepwidthText); this.stepwidthTextControlDecoration.addSelectionListener( stepwidhtTextControlDecorationSelectionListener); this.stepwidthTextFocusListener = new TextFocusListener(stepwidthText); // end of: initialize step width elements // initialize step count elements this.stepcountRadioButton = new Button(this, SWT.RADIO); this.stepcountRadioButton.setText("Stepcount:"); this.stepcountText = new Text(this, SWT.BORDER); gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.horizontalIndent = 7; gridData.grabExcessHorizontalSpace = true; this.stepcountText.setLayoutData(gridData); this.stepcountTextFocusListener = new TextFocusListener(stepcountText); // end of: initialize step count elements this.mainAxisCheckBox = new Button(this, SWT.CHECK); this.mainAxisCheckBox.setText("Main Axis"); gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; gridData.horizontalSpan = 2; this.mainAxisCheckBox.setLayoutData(gridData); this.addMultiplyMode = null; this.axis = null; LOGGER.debug("composite created"); } /** * {@inheritDoc} */ @Override public void dispose() { this.reset(); super.dispose(); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void setAxis(Axis axis) { this.reset(); if (axis == null) { return; } if (!(axis.getMode() instanceof AddMultiplyMode)) { LOGGER.warn("invalid axis mode"); return; } this.axis = axis; switch(axis.getType()) { case DOUBLE: this.addMultiplyMode = (AddMultiplyMode<Double>)axis.getMode(); break; case INT: this.addMultiplyMode = (AddMultiplyMode<Integer>)axis.getMode(); break; case DATETIME: if (axis.getPositionMode().equals(PositionMode.ABSOLUTE)) { this.addMultiplyMode = (AddMultiplyMode<Date>)axis.getMode(); this.startTextControlDecoration.show(); this.stopTextControlDecoration.show(); } else if (axis.getPositionMode().equals(PositionMode.RELATIVE)) { this.addMultiplyMode = (AddMultiplyMode<Duration>)axis.getMode(); this.startTextControlDecoration.show(); this.stopTextControlDecoration.show(); this.stepwidthTextControlDecoration.show(); } break; default: LOGGER.warn("wrong axis type"); return; } this.addMultiplyMode.addPropertyChangeListener( AddMultiplyMode.ADJUST_PARAMETER_PROP, this); this.axis.getMotorAxis().addPropertyChangeListener("highlimit", this); this.axis.getMotorAxis().addPropertyChangeListener("lowlimit", this); this.axis.addPropertyChangeListener("positionMode", this); this.createBinding(); this.setEnabled(); } /** * {@inheritDoc} */ @Override protected void createBinding() { LOGGER.debug("create bindings"); this.selectionTargetObservable = new SelectObservableValue(); this.selectionTargetObservable.addOption(AdjustParameter.START, SWTObservables.observeSelection(this.startRadioButton)); this.selectionTargetObservable.addOption(AdjustParameter.STOP, SWTObservables.observeSelection(this.stopRadioButton)); this.selectionTargetObservable.addOption(AdjustParameter.STEPWIDTH, SWTObservables.observeSelection(this.stepwidthRadioButton)); this.selectionTargetObservable.addOption(AdjustParameter.STEPCOUNT, SWTObservables.observeSelection(this.stepcountRadioButton)); this.selectionModelObservable = BeansObservables.observeValue( this.addMultiplyMode, AddMultiplyMode.ADJUST_PARAMETER_PROP); UpdateValueStrategy targetToModel = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); UpdateValueStrategy modelToTarget = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); this.selectBinding = context.bindValue(selectionTargetObservable, selectionModelObservable, targetToModel, modelToTarget); this.startTargetObservable = SWTObservables.observeText(startText, SWT.Modify); this.startModelObservable = BeansObservables.observeValue( this.addMultiplyMode, AddMultiplyMode.START_PROP); UpdateValueStrategy startTargetToModel = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); startTargetToModel.setConverter(new TargetToModelConverter( this.addMultiplyMode.getType(), this.addMultiplyMode.getAxis())); startTargetToModel.setAfterGetValidator( new TargetToModelAfterGetValidator( this.addMultiplyMode.getType(), this.addMultiplyMode .getAxis())); startTargetToModel.setAfterConvertValidator( new TargetToModelAfterConvertValidator( this.addMultiplyMode.getAxis())); UpdateValueStrategy startModelToTarget = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); startModelToTarget.setConverter(new ModelToTargetConverter( this.addMultiplyMode.getType(), this.addMultiplyMode.getAxis(), false)); startModelToTarget.setAfterGetValidator(new ModelToTargetValidator( this.addMultiplyMode.getType())); this.startBinding = context.bindValue(startTargetObservable, startModelObservable, startTargetToModel, startModelToTarget); this.startDecoration = ControlDecorationSupport.create( this.startBinding, SWT.LEFT | SWT.TOP); this.stopTargetObservable = SWTObservables.observeText(stopText, SWT.Modify); this.stopModelObservable = BeansObservables.observeValue( this.addMultiplyMode, AddMultiplyMode.STOP_PROP); UpdateValueStrategy stopTargetToModel = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); stopTargetToModel.setConverter(new TargetToModelConverter( this.addMultiplyMode.getType(), this.addMultiplyMode.getAxis())); stopTargetToModel.setAfterGetValidator( new TargetToModelAfterGetValidator( this.addMultiplyMode.getType(), this.addMultiplyMode .getAxis())); stopTargetToModel.setAfterConvertValidator( new TargetToModelAfterConvertValidator( this.addMultiplyMode.getAxis())); UpdateValueStrategy stopModelToTarget = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); stopModelToTarget.setConverter(new ModelToTargetConverter( this.addMultiplyMode.getType(), this.addMultiplyMode.getAxis(), false)); stopModelToTarget.setAfterGetValidator(new ModelToTargetValidator( this.addMultiplyMode.getType())); this.stopBinding = context.bindValue(stopTargetObservable, stopModelObservable, stopTargetToModel, stopModelToTarget); this.stopDecoration = ControlDecorationSupport.create(this.stopBinding, SWT.LEFT | SWT.TOP); this.stepwidthTargetObservable = SWTObservables.observeText( stepwidthText, SWT.Modify); this.stepwidthModelObservable = BeansObservables.observeValue( this.addMultiplyMode, AddMultiplyMode.STEPWIDTH_PROP); UpdateValueStrategy stepwidthTargetToModel = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); stepwidthTargetToModel.setConverter(new TargetToModelConverter( this.addMultiplyMode.getType(), this.addMultiplyMode.getAxis())); stepwidthTargetToModel.setAfterGetValidator(new TargetToModelAfterGetValidator( this.addMultiplyMode.getType(), this.addMultiplyMode.getAxis())); UpdateValueStrategy stepwidthModelToTarget = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); stepwidthModelToTarget.setConverter(new ModelToTargetConverter( this.addMultiplyMode.getType(), this.addMultiplyMode.getAxis(), true)); stepwidthModelToTarget.setAfterGetValidator(new ModelToTargetValidator( this.addMultiplyMode.getType())); this.stepwidthBinding = context.bindValue(stepwidthTargetObservable, stepwidthModelObservable, stepwidthTargetToModel, stepwidthModelToTarget); this.stepwidthDecoration = ControlDecorationSupport.create( this.stepwidthBinding, SWT.LEFT | SWT.TOP); this.stepcountTargetObservable = SWTObservables.observeText( stepcountText, SWT.Modify); this.stepcountModelObservable = BeansObservables.observeValue( this.addMultiplyMode, AddMultiplyMode.STEPCOUNT_PROP); UpdateValueStrategy stepcountTargetToModel = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); stepcountTargetToModel.setConverter(new TargetToModelConverter( DataTypes.DOUBLE, this.addMultiplyMode.getAxis())); stepcountTargetToModel.setAfterGetValidator(new TargetToModelAfterGetValidator( DataTypes.DOUBLE, this.addMultiplyMode.getAxis())); UpdateValueStrategy stepcountModelToTarget = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); stepcountModelToTarget.setConverter(new ModelToTargetConverter( DataTypes.DOUBLE, this.addMultiplyMode.getAxis(), false)); stepcountModelToTarget.setAfterGetValidator(new ModelToTargetValidator( DataTypes.DOUBLE)); this.stepcountBinding = context.bindValue(stepcountTargetObservable, stepcountModelObservable, stepcountTargetToModel, stepcountModelToTarget); this.stepcountDecoration = ControlDecorationSupport.create( this.stepcountBinding, SWT.LEFT); this.mainAxisTargetObservable = SWTObservables .observeSelection(mainAxisCheckBox); this.mainAxisModelObservable = BeansObservables.observeValue( this.addMultiplyMode, AddMultiplyMode.MAIN_AXIS_PROP); UpdateValueStrategy mainAxisTargetToModel = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); UpdateValueStrategy mainAxisModelToTarget = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); this.mainAxisBinding = context.bindValue(mainAxisTargetObservable, mainAxisModelObservable, mainAxisTargetToModel, mainAxisModelToTarget); switch (this.addMultiplyMode.getType()) { case DOUBLE: this.startTextVerifyListener = new DoubleVerifyListener( this.startText); this.stopTextVerifyListener = new DoubleVerifyListener( this.stopText); this.stepwidthTextVerifyListener = new DoubleVerifyListener( this.stepwidthText); this.stepcountTextVerifyListener = new DoubleVerifyListener( this.stepcountText); break; case INT: this.startTextVerifyListener = new IntegerVerifyListener( this.startText); this.stopTextVerifyListener = new IntegerVerifyListener( this.stopText); this.stepwidthTextVerifyListener = new IntegerVerifyListener( this.stepwidthText); this.stepcountTextVerifyListener = new IntegerVerifyListener( this.stepcountText); break; default: break; } /* this.startText.addVerifyListener(startTextVerifyListener); this.stopText.addVerifyListener(stopTextVerifyListener); this.stepwidthText.addVerifyListener(stepwidthTextVerifyListener); this.stepcountText.addVerifyListener(stepcountTextVerifyListener); */ this.startText.addFocusListener(startTextFocusListener); this.stopText.addFocusListener(stopTextFocusListener); this.stepwidthText.addFocusListener(stepwidthTextFocusListener); this.stepcountText.addFocusListener(stepcountTextFocusListener); } /** * {@inheritDoc} */ @Override protected void reset() { if (this.addMultiplyMode != null) { LOGGER.debug("remove bindings"); this.startText.removeFocusListener(startTextFocusListener); this.stopText.removeFocusListener(stopTextFocusListener); this.stepwidthText.removeFocusListener(stepwidthTextFocusListener); this.stepcountText.removeFocusListener(stepcountTextFocusListener); /* this.startText.removeVerifyListener(startTextVerifyListener); this.stopText.removeVerifyListener(stopTextVerifyListener); this.stepwidthText.removeVerifyListener(stepwidthTextVerifyListener); this.stepcountText.removeVerifyListener(stepcountTextVerifyListener); */ this.addMultiplyMode.removePropertyChangeListener( AddMultiplyMode.ADJUST_PARAMETER_PROP, this); this.selectBinding.dispose(); this.selectionTargetObservable.dispose(); this.selectionModelObservable.dispose(); this.startBinding.dispose(); this.startTargetObservable.dispose(); this.startModelObservable.dispose(); if (this.startDecoration != null) { this.startDecoration.dispose(); } this.stopBinding.dispose(); this.stopTargetObservable.dispose(); this.stopModelObservable.dispose(); if (this.stopDecoration != null) { this.stopDecoration.dispose(); } this.stepwidthBinding.dispose(); this.stepwidthTargetObservable.dispose(); this.stepwidthModelObservable.dispose(); if (this.stepwidthDecoration != null) { this.stepwidthDecoration.dispose(); } this.stepcountBinding.dispose(); this.stepcountTargetObservable.dispose(); this.stepcountModelObservable.dispose(); if (this.stepcountDecoration != null) { this.stepcountDecoration.dispose(); } this.mainAxisBinding.dispose(); this.mainAxisTargetObservable.dispose(); this.mainAxisModelObservable.dispose(); this.startTextControlDecoration.hide(); this.stopTextControlDecoration.hide(); this.stepwidthTextControlDecoration.hide(); } if (this.axis != null) { this.axis.getMotorAxis().removePropertyChangeListener("highlimit", this); this.axis.getMotorAxis().removePropertyChangeListener("lowlimit", this); this.axis.removePropertyChangeListener("positionMode", this); } this.addMultiplyMode = null; this.axis = null; this.redraw(); } private void setEnabled() { if (this.addMultiplyMode == null) { return; } this.startText.setEnabled(true); this.stopText.setEnabled(true); this.stepwidthText.setEnabled(true); this.stepcountText.setEnabled(true); this.stepcountRadioButton.setEnabled(true); this.mainAxisCheckBox.setEnabled(true); switch (this.addMultiplyMode.getAdjustParameter()) { case START: this.startText.setEnabled(false); break; case STEPCOUNT: this.stepcountText.setEnabled(false); break; case STEPWIDTH: this.stepwidthText.setEnabled(false); break; case STOP: this.stopText.setEnabled(false); break; } // if an axis (other than this one) is set as main axis, // its step count is used if (this.addMultiplyMode.getReferenceAxis() != null) { this.stepcountText.setEnabled(false); this.stepcountRadioButton.setEnabled(false); this.mainAxisCheckBox.setEnabled(false); } } /** * calculate the height to see all entries of this composite * * @return the needed height of Composite to see all entries */ public int getTargetHeight() { return (mainAxisCheckBox.getBounds().y + mainAxisCheckBox.getBounds().height + 5); } /** * calculate the width to see all entries of this composite * * @return the needed width of Composite to see all entries */ public int getTargetWidth() { return (mainAxisCheckBox.getBounds().x + mainAxisCheckBox.getBounds().width + 5); } /** * {@inheritDoc} */ @Override public void propertyChange(PropertyChangeEvent e) { LOGGER.debug(e.getPropertyName()); if (e.getPropertyName().equals(AddMultiplyMode.ADJUST_PARAMETER_PROP)) { this.setEnabled(); } else if (e.getPropertyName().equals("highlimit") || e.getPropertyName().equals("lowlimit")) { this.startBinding.updateTargetToModel(); this.stopBinding.updateTargetToModel(); } else if (e.getPropertyName().equals("positionMode")) { this.setAxis(this.axis); } } /** * @author Marcus Michalsky * @since 1.7 */ private class TextFocusListener implements FocusListener { private Text widget; /** * @param widget the widget to observe */ public TextFocusListener(Text widget) { this.widget = widget; } /** * {@inheritDoc} */ @Override public void focusGained(FocusEvent e) { } /** * {@inheritDoc} */ @Override public void focusLost(FocusEvent e) { LOGGER.debug("focus lost"); if (this.widget == startText) { //startText.removeVerifyListener(startTextVerifyListener); startBinding.updateModelToTarget(); startBinding.validateTargetToModel(); /*MessageDialog.openWarning(getShell(), "Restored Value", "Restored last valid value for 'start' of " + addMultiplyMode.getAxis().getMotorAxis().getName());*/ //startText.addVerifyListener(startTextVerifyListener); } else if (this.widget == stopText) { //stopText.removeVerifyListener(stopTextVerifyListener); stopBinding.updateModelToTarget(); stopBinding.validateTargetToModel(); /*MessageDialog.openWarning(getShell(), "Restored Value", "Restored last valid value for 'stop' of " + addMultiplyMode.getAxis().getMotorAxis().getName());*/ //stopText.addVerifyListener(stopTextVerifyListener); } else if (this.widget == stepwidthText) { //stepwidthText.removeVerifyListener(stepwidthTextVerifyListener); stepwidthBinding.updateModelToTarget(); /*MessageDialog.openWarning(getShell(), "Restored Value", "Restored last valid value for 'stepwidth' of " + addMultiplyMode.getAxis().getMotorAxis().getName());*/ //stepwidthText.addVerifyListener(stepwidthTextVerifyListener); } else if (this.widget == stepcountText) { //stepcountText.removeVerifyListener(stepcountTextVerifyListener); stepcountBinding.updateModelToTarget(); /*MessageDialog.openWarning(getShell(), "Restored Value", "Restored last valid value for 'stepcount' of " + addMultiplyMode.getAxis().getMotorAxis().getName());*/ //stepcountText.addVerifyListener(stepcountTextVerifyListener); } } } /** * @author Marcus Michalsky * @since 1.7 */ private class DateTimeProposalSelectionListener implements SelectionListener { private Text text; /** * @param text the text field to fill */ public DateTimeProposalSelectionListener(Text text) { this.text = text; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void widgetSelected(SelectionEvent e) { switch (axis.getPositionMode()) { case ABSOLUTE: DateSelectorDialog dialog = new DateSelectorDialog(getShell()); dialog.open(); if (dialog.getReturnCode() == Dialog.OK) { LOGGER.debug("OK"); LOGGER.debug(dialog.getDate()); if (this.text == startText) { ((AddMultiplyMode<Date>) axis.getMode()).setStart(dialog .getDate()); } else if (this.text == stopText) { ((AddMultiplyMode<Date>) axis.getMode()).setStop(dialog .getDate()); } } else { LOGGER.debug("cancel"); } break; case RELATIVE: DurationSelectorDialog durationDialog = new DurationSelectorDialog(getShell()); durationDialog.open(); if (durationDialog.getReturnCode() == Dialog.OK) { LOGGER.debug("OK"); LOGGER.debug(durationDialog.getDuration()); if (this.text == startText) { ((AddMultiplyMode<Duration>) axis.getMode()) .setStart(durationDialog.getDuration()); } else if (this.text == stopText) { ((AddMultiplyMode<Duration>) axis.getMode()) .setStop(durationDialog.getDuration()); } else if (this.text == stepwidthText) { ((AddMultiplyMode<Duration>) axis.getMode()) .setStepwidth(durationDialog.getDuration()); } } else { LOGGER.debug("cancel"); } break; } } /** * {@inheritDoc} */ @Override public void widgetDefaultSelected(SelectionEvent e) { } } }
package com.intellij.ide.actions.searcheverywhere; import com.google.common.collect.Lists; import com.intellij.find.findUsages.PsiElement2UsageTargetAdapter; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiElement; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.*; import com.intellij.ui.components.JBCheckBox; import com.intellij.ui.components.JBList; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.components.fields.ExtendableTextField; import com.intellij.usageView.UsageInfo; import com.intellij.usages.*; import com.intellij.util.Alarm; import com.intellij.util.text.MatcherHolder; import com.intellij.util.ui.DialogUtil; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.StatusText; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.components.BorderLayoutPanel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.DocumentEvent; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.*; import java.util.List; import java.util.stream.Collectors; /** * @author Konstantin Bulenkov * @author Mikhail.Sokolov */ public class SearchEverywhereUI extends BorderLayoutPanel implements Disposable { private static final Logger LOG = Logger.getInstance(SearchEverywhereUI.class); public static final int SINGLE_CONTRIBUTOR_ELEMENTS_LIMIT = 30; public static final int MULTIPLE_CONTRIBUTORS_ELEMENTS_LIMIT = 15; private final List<SearchEverywhereContributor> allContributors; private final Project myProject; private SETab mySelectedTab; private final JTextField mySearchField; private final JCheckBox myNonProjectCB; private final List<SETab> myTabs = new ArrayList<>(); private final JBList<Object> myResultsList = new JBList<>(); private final SearchListModel myListModel = new SearchListModel(); //todo using in different threads? #UX-1 private CalcThread myCalcThread; private volatile ActionCallback myCurrentWorker = ActionCallback.DONE; private int myCalcThreadRestartRequestId = 0; private final Object myWorkerRestartRequestLock = new Object(); private final Alarm listOperationsAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, ApplicationManager.getApplication()); private Runnable searchFinishedHandler = () -> {}; public SearchEverywhereUI(Project project, List<SearchEverywhereContributor> serviceContributors, List<SearchEverywhereContributor> contributors) { withMinimumWidth(670); withPreferredWidth(670); withBackground(JBUI.CurrentTheme.SearchEverywhere.dialogBackground()); myProject = project; allContributors = new ArrayList<>(); allContributors.addAll(serviceContributors); allContributors.addAll(contributors); myNonProjectCB = new JBCheckBox(); myNonProjectCB.setOpaque(false); myNonProjectCB.setFocusable(false); JPanel contributorsPanel = createTabPanel(contributors); JPanel settingsPanel = createSettingsPanel(); mySearchField = createSearchField(); JPanel suggestionsPanel = createSuggestionsPanel(); myResultsList.setModel(myListModel); myResultsList.setCellRenderer(new CompositeCellRenderer()); ScrollingUtil.installActions(myResultsList, getSearchField()); JPanel topPanel = new JPanel(new BorderLayout()); topPanel.setOpaque(false); topPanel.add(contributorsPanel, BorderLayout.WEST); topPanel.add(settingsPanel, BorderLayout.EAST); topPanel.add(mySearchField, BorderLayout.SOUTH); WindowMoveListener moveListener = new WindowMoveListener(this); topPanel.addMouseListener(moveListener); topPanel.addMouseMotionListener(moveListener); addToTop(topPanel); addToCenter(suggestionsPanel); initSearchActions(); } private JPanel createSuggestionsPanel() { JPanel pnl = new JPanel(new BorderLayout()); pnl.setOpaque(false); pnl.setBorder(JBUI.Borders.customLine(JBUI.CurrentTheme.SearchEverywhere.searchFieldBorderColor(), 1, 0, 0, 0)); JScrollPane resultsScroll = new JBScrollPane(myResultsList); resultsScroll.setBorder(null); resultsScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); resultsScroll.setPreferredSize(JBUI.size(670, JBUI.CurrentTheme.SearchEverywhere.maxListHeght())); pnl.add(resultsScroll, BorderLayout.CENTER); String hint = IdeBundle.message("searcheverywhere.history.shortcuts.hint", KeymapUtil.getKeystrokeText(SearchTextField.ALT_SHOW_HISTORY_KEYSTROKE), KeymapUtil.getKeystrokeText(SearchTextField.SHOW_HISTORY_KEYSTROKE)); JLabel hintLabel = new JLabel(hint); hintLabel.setOpaque(false); hintLabel.setForeground(JBColor.GRAY); pnl.add(hintLabel, BorderLayout.SOUTH); return pnl; } public JTextField getSearchField() { return mySearchField; } public void setUseNonProjectItems(boolean use) { myNonProjectCB.setSelected(use); } public boolean isUseNonProjectItems() { return myNonProjectCB.isSelected(); } public void switchToContributor(String contributorID) { SETab selectedTab = myTabs.stream() .filter(tab -> tab.getID().equals(contributorID)) .findAny() .orElseThrow(() -> new IllegalArgumentException(String.format("Contributor %s is not supported", contributorID))); switchToTab(selectedTab); } public void setSearchFinishedHandler(@NotNull Runnable searchFinishedHandler) { this.searchFinishedHandler = searchFinishedHandler; } public String getSelectedContributorID() { return mySelectedTab.getID(); } @Override public void dispose() { stopSearching(); } private void switchToNextTab() { int currentIndex = myTabs.indexOf(mySelectedTab); SETab nextTab = currentIndex == myTabs.size() - 1 ? myTabs.get(0) : myTabs.get(currentIndex + 1); switchToTab(nextTab); } private void switchToTab(SETab tab) { mySelectedTab = tab; String text = tab.getContributor() .map(SearchEverywhereContributor::includeNonProjectItemsText) .orElse(IdeBundle.message("checkbox.include.non.project.items", IdeUICustomization.getInstance().getProjectConceptName())); if (text.indexOf(UIUtil.MNEMONIC) != -1) { DialogUtil.setTextWithMnemonic(myNonProjectCB, text); } else { myNonProjectCB.setText(text); myNonProjectCB.setDisplayedMnemonicIndex(-1); myNonProjectCB.setMnemonic(0); } myNonProjectCB.setSelected(false); repaint(); rebuildList(); } private boolean isAllTabSelected() { return SearchEverywhereContributor.ALL_CONTRIBUTORS_GROUP_ID.equals(getSelectedContributorID()); } private JTextField createSearchField() { ExtendableTextField searchField = new ExtendableTextField() { @Override public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.height = JBUI.scale(29); return size; } }; ExtendableTextField.Extension searchExtension = new ExtendableTextField.Extension() { @Override public Icon getIcon(boolean hovered) { return AllIcons.Actions.Search; } @Override public boolean isIconBeforeText() { return true; } }; ExtendableTextField.Extension hintExtension = new ExtendableTextField.Extension() { private final TextIcon icon; { icon = new TextIcon(IdeBundle.message("searcheverywhere.switch.scope.hint"), JBColor.GRAY, null, 0); icon.setFont(RelativeFont.SMALL.derive(getFont())); } @Override public Icon getIcon(boolean hovered) { return icon; } }; searchField.setExtensions(searchExtension, hintExtension); //todo gap between icon and text #UX-1 Insets insets = JBUI.CurrentTheme.SearchEverywhere.searchFieldInsets(); Border empty = JBUI.Borders.empty(insets.top, insets.left, insets.bottom, insets.right); Border topLine = JBUI.Borders.customLine(JBUI.CurrentTheme.SearchEverywhere.searchFieldBorderColor(), 1, 0, 0, 0); searchField.setBorder(JBUI.Borders.merge(empty, topLine, true)); searchField.setBackground(JBUI.CurrentTheme.SearchEverywhere.searchFieldBackground()); searchField.setFocusTraversalKeysEnabled(false); return searchField; } private JPanel createSettingsPanel() { JPanel res = new JPanel(); BoxLayout bl = new BoxLayout(res, BoxLayout.X_AXIS); res.setLayout(bl); res.setOpaque(false); res.add(myNonProjectCB); res.add(Box.createHorizontalStrut(JBUI.scale(19))); AnAction pinAction = new ShowInFindToolWindowAction(); ActionButton pinButton = new ActionButton(pinAction, pinAction.getTemplatePresentation(), ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE); res.add(pinButton); res.add(Box.createHorizontalStrut(JBUI.scale(10))); AnAction emptyAction = new AnAction(AllIcons.General.Filter) { @Override public void actionPerformed(AnActionEvent e) {} }; ActionButton filterButton = new ActionButton(emptyAction, emptyAction.getTemplatePresentation(), ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE); res.add(filterButton); res.add(Box.createHorizontalStrut(JBUI.scale(10))); return res; } @NotNull private JPanel createTabPanel(List<SearchEverywhereContributor> contributors) { JPanel contributorsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); contributorsPanel.setOpaque(false); SETab allTab = new SETab(null); contributorsPanel.add(allTab); myTabs.add(allTab); contributors.forEach(contributor -> { SETab tab = new SETab(contributor); contributorsPanel.add(tab); myTabs.add(tab); }); switchToTab(allTab); return contributorsPanel; } private class SETab extends JLabel { private final SearchEverywhereContributor myContributor; public SETab(SearchEverywhereContributor contributor) { super(contributor == null ? IdeBundle.message("searcheverywhere.allelements.tab.name") : contributor.getGroupName()); myContributor = contributor; Insets insets = JBUI.CurrentTheme.SearchEverywhere.tabInsets(); setBorder(JBUI.Borders.empty(insets.top, insets.left, insets.bottom, insets.right)); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { switchToTab(SETab.this); } }); } public String getID() { return getContributor() .map(SearchEverywhereContributor::getSearchProviderId) .orElse(SearchEverywhereContributor.ALL_CONTRIBUTORS_GROUP_ID); } public Optional<SearchEverywhereContributor> getContributor() { return Optional.ofNullable(myContributor); } @Override public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.height = JBUI.scale(29); return size; } @Override public boolean isOpaque() { return mySelectedTab == this; } @Override public Color getBackground() { return mySelectedTab == this ? JBUI.CurrentTheme.SearchEverywhere.selectedTabColor() : super.getBackground(); } } private void rebuildList() { assert EventQueue.isDispatchThread() : "Must be EDT"; if (myCalcThread != null && !myCurrentWorker.isProcessed()) { myCurrentWorker = myCalcThread.cancel(); } if (myCalcThread != null && !myCalcThread.isCanceled()) { myCalcThread.cancel(); } String pattern = getSearchPattern(); MinusculeMatcher matcher = NameUtil.buildMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE); MatcherHolder.associateMatcher(myResultsList, matcher); //assert project != null; //myRenderer.myProject = project; synchronized (myWorkerRestartRequestLock) { // this lock together with RestartRequestId should be enough to prevent two CalcThreads running at the same time final int currentRestartRequest = ++myCalcThreadRestartRequestId; myCurrentWorker.doWhenProcessed(() -> { synchronized (myWorkerRestartRequestLock) { if (currentRestartRequest != myCalcThreadRestartRequestId) { return; } myCalcThread = new CalcThread(myProject, pattern, null); myCurrentWorker = myCalcThread.start(); } }); } } private String getSearchPattern() { return mySearchField != null ? mySearchField.getText() : ""; } private void initSearchActions() { mySearchField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_TAB && e.getModifiers() == 0) { switchToNextTab(); e.consume(); } if (e.getKeyCode() == KeyEvent.VK_ENTER) { elementSelected(myResultsList.getSelectedIndex(), e.getModifiers()); } } }); AnAction escape = ActionManager.getInstance().getAction("EditorEscape"); DumbAwareAction.create(__ -> { stopSearching(); searchFinishedHandler.run(); }).registerCustomShortcutSet(escape == null ? CommonShortcuts.ESCAPE : escape.getShortcutSet(), this); mySearchField.getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { rebuildList(); } }); myNonProjectCB.addItemListener(e -> rebuildList()); myResultsList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { e.consume(); final int i = myResultsList.locationToIndex(e.getPoint()); if (i != -1) { myResultsList.setSelectedIndex(i); elementSelected(i, e.getModifiers()); } } } }); } private void elementSelected(int i, int modifiers) { SearchEverywhereContributor contributor = myListModel.getContributorForIndex(i); if (myListModel.isMoreElement(i)) { showMoreElements(contributor); } else { gotoSelectedItem(myListModel.getElementAt(i), contributor, modifiers); } } private void showMoreElements(SearchEverywhereContributor contributor) { synchronized (myWorkerRestartRequestLock) { // this lock together with RestartRequestId should be enough to prevent two CalcThreads running at the same time final int currentRestartRequest = ++myCalcThreadRestartRequestId; myCurrentWorker.doWhenProcessed(() -> { synchronized (myWorkerRestartRequestLock) { if (currentRestartRequest != myCalcThreadRestartRequestId) { return; } myCalcThread = new CalcThread(myProject, getSearchPattern(), contributor); myCurrentWorker = myCalcThread.start(); } }); } } private void gotoSelectedItem(Object value, SearchEverywhereContributor contributor, int modifiers) { boolean closePopup = contributor.processSelectedItem(myProject, value, modifiers); if (closePopup) { stopSearching(); searchFinishedHandler.run(); } else { myResultsList.repaint(); } } private void stopSearching() { listOperationsAlarm.cancelAllRequests(); if (myCalcThread != null && !myCalcThread.isCanceled()) { myCalcThread.cancel(); } } @SuppressWarnings("Duplicates") //todo remove suppress #UX-1 private class CalcThread implements Runnable { private final Project project; private final String pattern; private final ProgressIndicator myProgressIndicator = new ProgressIndicatorBase(); private final ActionCallback myDone = new ActionCallback(); private final SearchEverywhereContributor contributorToExpand; public CalcThread(@NotNull Project project, @NotNull String pattern, @Nullable SearchEverywhereContributor expand) { this.project = project; this.pattern = pattern; contributorToExpand = expand; } @Override public void run() { try { check(); if (contributorToExpand == null) { resetList(); } else { showMore(contributorToExpand); } } catch (ProcessCanceledException ignore) { myDone.setRejected(); } catch (Exception e) { LOG.error(e); myDone.setRejected(); } finally { if (!isCanceled()) { listOperationsAlarm.addRequest(() -> myResultsList.getEmptyText().setText(StatusText.DEFAULT_EMPTY_TEXT), 0); } if (!myDone.isProcessed()) { myDone.setDone(); } } } private void resetList() { listOperationsAlarm.cancelAllRequests(); listOperationsAlarm.addRequest(() -> { Dimension oldSize = getPreferredSize(); myResultsList.getEmptyText().setText("Searching..."); myListModel.clear(); Dimension newSize = getPreferredSize(); firePropertyChange("preferredSize", oldSize, newSize); }, 200); SearchEverywhereContributor selectedContributor = mySelectedTab.getContributor().orElse(null); if (selectedContributor != null) { addContributorItems(selectedContributor, SINGLE_CONTRIBUTOR_ELEMENTS_LIMIT, true); } else { boolean clearBefore = true; for (SearchEverywhereContributor contributor : allContributors) { addContributorItems(contributor, MULTIPLE_CONTRIBUTORS_ELEMENTS_LIMIT, clearBefore); clearBefore = false; } } } private void showMore(SearchEverywhereContributor contributor) { int delta = isAllTabSelected() ? MULTIPLE_CONTRIBUTORS_ELEMENTS_LIMIT : SINGLE_CONTRIBUTOR_ELEMENTS_LIMIT; int size = myListModel.getItemsForContributor(contributor) + delta; addContributorItems(contributor, size, false); } private void addContributorItems(SearchEverywhereContributor contributor, int count, boolean clearBefore) { if (!DumbService.getInstance(project).isDumb()) { ApplicationManager.getApplication().runReadAction(() -> { ContributorSearchResult<Object> results = contributor.search(project, pattern, isUseNonProjectItems(), myProgressIndicator, count); if (clearBefore) { listOperationsAlarm.cancelAllRequests(); } listOperationsAlarm.addRequest(() -> { if (isCanceled()) { return; } Dimension oldSize = getPreferredSize(); if (clearBefore) { myListModel.clear(); } List<Object> itemsToAdd = results.getItems().stream() .filter(o -> !myListModel.contains(o)) .collect(Collectors.toList()); if (!itemsToAdd.isEmpty()) { myListModel.addElements(itemsToAdd, contributor, results.hasMoreItems()); ScrollingUtil.ensureSelectionExists(myResultsList); } firePropertyChange("preferredSize", oldSize, getPreferredSize()); }, 0); }); } } protected void check() { myProgressIndicator.checkCanceled(); if (myDone.isRejected()) throw new ProcessCanceledException(); assert myCalcThread == this : "There are two CalcThreads running before one of them was cancelled"; } private boolean isCanceled() { return myProgressIndicator.isCanceled() || myDone.isRejected(); } public ActionCallback cancel() { myProgressIndicator.cancel(); //myDone.setRejected(); return myDone; } public ActionCallback start() { ApplicationManager.getApplication().executeOnPooledThread(this); return myDone; } } private class CompositeCellRenderer implements ListCellRenderer<Object> { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (myListModel.isMoreElement(index)) { return moreRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } SearchEverywhereContributor contributor = myListModel.getContributorForIndex(index); Component component = contributor.getElementsRenderer(myProject) .getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (isAllTabSelected() && myListModel.isGroupFirstItem(index)) { return groupTitleRenderer.withDisplayedData(contributor.getGroupName(), component); } return component; } } private final MoreRenderer moreRenderer = new MoreRenderer(); public static class MoreRenderer extends JPanel implements ListCellRenderer<Object> { final JLabel label; private MoreRenderer() { super(new BorderLayout()); label = groupInfoLabel("... more"); add(label, BorderLayout.CENTER); } @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setBackground(UIUtil.getListBackground(isSelected)); return this; } } private final GroupTitleRenderer groupTitleRenderer = new GroupTitleRenderer(); public static class GroupTitleRenderer extends JPanel { private final JLabel titleLabel; private final BorderLayout myLayout = new BorderLayout(); public GroupTitleRenderer() { setLayout(myLayout); setBackground(UIUtil.getListBackground(false)); titleLabel = groupInfoLabel("Group"); SeparatorComponent separatorComponent = new SeparatorComponent(titleLabel.getPreferredSize().height / 2, UIUtil.getLabelDisabledForeground(), null); JPanel topPanel = JBUI.Panels.simplePanel(5, 0) .addToCenter(separatorComponent) .addToLeft(titleLabel) .withBorder(JBUI.Borders.empty()) .withBackground(UIUtil.getListBackground()); add(topPanel, BorderLayout.NORTH); } public GroupTitleRenderer withDisplayedData(String title, Component itemContent) { titleLabel.setText(title); Component prevContent = myLayout.getLayoutComponent(BorderLayout.CENTER); if (prevContent != null) { remove(prevContent); } add(itemContent, BorderLayout.CENTER); return this; } } private static class SearchListModel extends AbstractListModel<Object> { private static final Object MORE_ELEMENT = new Object(); private final List<Pair<Object, SearchEverywhereContributor>> listElements = new ArrayList<>(); @Override public int getSize() { return listElements.size(); } @Override public Object getElementAt(int index) { return listElements.get(index).first; } public Collection<Object> getFoundItems(SearchEverywhereContributor contributor) { return listElements.stream() .filter(pair -> pair.second == contributor && pair.first != MORE_ELEMENT) .map(pair -> pair.getFirst()) .collect(Collectors.toList()); } public boolean hasMoreElements(SearchEverywhereContributor contributor) { return listElements.stream() .anyMatch(pair -> pair.first == MORE_ELEMENT && pair.second == contributor); } public void addElements(List<Object> items, SearchEverywhereContributor contributor, boolean hasMore) { if (items.isEmpty()) { return; } List<Pair<Object, SearchEverywhereContributor>> pairsToAdd = items.stream() .map(o -> Pair.create(o, contributor)) .collect(Collectors.toList()); int insertPoint = contributors().lastIndexOf(contributor); int startIndex; int endIndex; if (insertPoint < 0) { // no items of this contributor startIndex = listElements.size(); listElements.addAll(pairsToAdd); if (hasMore) { listElements.add(Pair.create(MORE_ELEMENT, contributor)); } endIndex = listElements.size() - 1; } else { // contributor elements already exists in list if (isMoreElement(insertPoint)) { listElements.remove(insertPoint); } else { insertPoint += 1; } startIndex = insertPoint; endIndex = startIndex + pairsToAdd.size(); listElements.addAll(insertPoint, pairsToAdd); if (hasMore) { listElements.add(insertPoint + pairsToAdd.size(), Pair.create(MORE_ELEMENT, contributor)); endIndex += 1; } } fireIntervalAdded(this, startIndex, endIndex); } public void clear() { int index = listElements.size() - 1; listElements.clear(); if (index >= 0) { fireIntervalRemoved(this, 0, index); } } public boolean contains(Object val) { return values().contains(val); } public boolean isMoreElement(int index) { return listElements.get(index).first == MORE_ELEMENT; } public SearchEverywhereContributor getContributorForIndex(int index) { return listElements.get(index).second; } public boolean isGroupFirstItem(int index) { return index == 0 || listElements.get(index).second != listElements.get(index - 1).second; } public int getItemsForContributor(SearchEverywhereContributor contributor) { List<SearchEverywhereContributor> contributorsList = contributors(); int first = contributorsList.indexOf(contributor); int last = contributorsList.lastIndexOf(contributor); if (isMoreElement(last)) { last -= 1; } return last - first + 1; } @NotNull private List<SearchEverywhereContributor> contributors() { return Lists.transform(listElements, pair -> pair.getSecond()); } @NotNull private List<Object> values() { return Lists.transform(listElements, pair -> pair.getFirst()); } } private class ShowInFindToolWindowAction extends DumbAwareAction { public ShowInFindToolWindowAction() { super(IdeBundle.message("searcheverywhere.show.in.find.window.button.name"), IdeBundle.message("searcheverywhere.show.in.find.window.button.name"), AllIcons.General.Pin_tab); } @Override public void actionPerformed(AnActionEvent e) { stopSearching(); Collection<SearchEverywhereContributor> contributors = isAllTabSelected() ? allContributors : Collections.singleton(mySelectedTab.getContributor().get()); contributors = contributors.stream() .filter(SearchEverywhereContributor::showInFindResults) .collect(Collectors.toList()); if (contributors.isEmpty()) { return; } String searchText = getSearchPattern(); boolean everywhere = isUseNonProjectItems(); String contributorsString = contributors.stream() .map(SearchEverywhereContributor::getGroupName) .collect(Collectors.joining(", ")); UsageViewPresentation presentation = new UsageViewPresentation(); String tabCaptionText = IdeBundle.message("searcheverywhere.found.matches.title", searchText, contributorsString); presentation.setCodeUsagesString(tabCaptionText); presentation.setUsagesInGeneratedCodeString(IdeBundle.message("searcheverywhere.found.matches.generated.code.title", searchText, contributorsString)); presentation.setTargetsNodeText(IdeBundle.message("searcheverywhere.found.targets.title", searchText, contributorsString)); presentation.setTabName(tabCaptionText); presentation.setTabText(tabCaptionText); Collection<Usage> usages = new LinkedHashSet<>(); Collection<PsiElement> targets = new LinkedHashSet<>(); Collection<Object> cached = contributors.stream() .flatMap(contributor -> myListModel.getFoundItems(contributor).stream()) .collect(Collectors.toList()); fillUsages(cached, usages, targets); Collection<SearchEverywhereContributor> contributorsForAdditionalSearch; contributorsForAdditionalSearch = contributors.stream() .filter(contributor -> myListModel.hasMoreElements(contributor)) .collect(Collectors.toList()); searchFinishedHandler.run(); if (!contributorsForAdditionalSearch.isEmpty()) { ProgressManager.getInstance().run(new Task.Modal(myProject, tabCaptionText, true) { private final ProgressIndicator progressIndicator = new ProgressIndicatorBase(); @Override public void run(@NotNull ProgressIndicator indicator) { contributorsForAdditionalSearch.forEach(contributor -> { if (!progressIndicator.isCanceled()) { ApplicationManager.getApplication().runReadAction(() -> { //todo overflow #UX-1 List<Object> foundElements = contributor.search(myProject, searchText, everywhere, progressIndicator); fillUsages(foundElements, usages, targets); }); } }); } @Override public void onCancel() { progressIndicator.cancel(); } @Override public void onSuccess() { showInFindWindow(targets, usages, presentation); } @Override public void onThrowable(@NotNull Throwable error) { progressIndicator.cancel(); } }); } else { showInFindWindow(targets, usages, presentation); } } private void fillUsages(Collection<Object> foundElements, Collection<Usage> usages, Collection<PsiElement> targets) { foundElements.stream() .filter(o -> o instanceof PsiElement) .forEach(o -> { PsiElement element = (PsiElement)o; if (element.getTextRange() != null) { UsageInfo usageInfo = new UsageInfo(element); usages.add(new UsageInfo2UsageAdapter(usageInfo)); } else { targets.add(element); } }); } private void showInFindWindow(Collection<PsiElement> targets, Collection<Usage> usages, UsageViewPresentation presentation) { UsageTarget[] targetsArray = targets.isEmpty() ? UsageTarget.EMPTY_ARRAY : PsiElement2UsageTargetAdapter.convert(PsiUtilCore.toPsiElementArray(targets)); Usage[] usagesArray = usages.toArray(Usage.EMPTY_ARRAY); UsageViewManager.getInstance(myProject).showUsages(targetsArray, usagesArray, presentation); } } private static JLabel groupInfoLabel(String text) { JLabel label = new JLabel(text); label.setForeground(UIUtil.getLabelDisabledForeground()); label.setFont(UIUtil.getLabelFont().deriveFont(UIUtil.getFontSize(UIUtil.FontSize.SMALL))); label.setOpaque(false); return label; } }
package de.phonostar; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import android.content.Context; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.inputmethod.InputMethodManager; import android.os.SystemClock; import android.view.View; import java.lang.String; public class SoftKeyboard extends CordovaPlugin { private float xpos; private float ypos; public SoftKeyboard() { webView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { xpos = (float) event.getX(); ypos = (float) event.getY(); return true; } }); } public void showKeyBoard() { InputMethodManager mgr = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); mgr.showSoftInput(webView, InputMethodManager.SHOW_IMPLICIT); ((InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(webView, 0); } public void hideKeyBoard() { InputMethodManager mgr = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(webView.getWindowToken(), 0); } public boolean isKeyBoardShowing() { int heightDiff = webView.getRootView().getHeight() - webView.getHeight(); return (100 < heightDiff); // if more than 100 pixels, its probably a keyboard... } public boolean sendTap(final int posx, final int posy, final CallbackContext callbackContext) { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { boolean up, down; up = webView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, posx, posy, 0)); down = webView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, posx, posy, 0)); if (!down || !up) { callbackContext.error("Failed sending key up+down event for coords " + posx + ", " + posy); } else { callbackContext.success("Succesfully sent key up+down event for coords " + posx + ", " + posy); } } }); return true; } public boolean sendKey(final int keyCode, final CallbackContext callbackContext) { /* if (!isKeyBoardShowing()) { callbackContext.error("Unable to send key press for " + keyCode + ": Softkeyboard is not showing"); return false; } */ cordova.getActivity().runOnUiThread(new Runnable() { public void run() { boolean downResult, upResult; downResult = webView.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); if (!downResult) { callbackContext.error("Failed sending keydown event for key " + keyCode); return; } upResult = webView.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyCode)); if (upResult) { callbackContext.success("Last event's coords were: " + xpos + "x" + ypos); } else { callbackContext.error("Last event's coords were: " + xpos + "x" + ypos); } } }); return true; } @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (action.equals("show")) { this.showKeyBoard(); callbackContext.success("done"); return true; } else if (action.equals("hide")) { this.hideKeyBoard(); callbackContext.success(); return true; } else if (action.equals("isShowing")) { callbackContext.success(Boolean.toString(this.isKeyBoardShowing())); return true; } else if (action.equals("sendKey")) { try { int keyCode = args.getInt(0); return this.sendKey(keyCode, callbackContext); } catch (JSONException jsonEx) { callbackContext.error(jsonEx.getMessage()); return false; } } else if (action.equals("sendTap")) { try { int posx = args.getInt(0); int posy = args.getInt(1); return this.sendTap(posx, posy, callbackContext); } catch (JSONException jsonEx) { callbackContext.error(jsonEx.getMessage()); return false; } } else { return false; } } }
package com.intellij.openapi.actionSystem.impl; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.impl.DataManagerImpl; import com.intellij.ide.ui.UISettings; import com.intellij.internal.statistic.collectors.fus.ui.persistence.ToolbarClicksCollector; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionButtonLook; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowAnchor; import com.intellij.openapi.wm.WindowManager; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.ui.ColorUtil; import com.intellij.ui.ComponentUtil; import com.intellij.ui.JBColor; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.ui.paint.LinePainter2D; import com.intellij.ui.scale.JBUIScale; import com.intellij.ui.switcher.QuickActionProvider; import com.intellij.util.ui.*; import com.intellij.util.ui.update.Activatable; import com.intellij.util.ui.update.UiNotifyConnector; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.jetbrains.concurrency.CancellablePromise; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.List; import java.util.*; import java.util.concurrent.TimeUnit; public class ActionToolbarImpl extends JPanel implements ActionToolbar, QuickActionProvider { private static final Logger LOG = Logger.getInstance(ActionToolbarImpl.class); private static final Set<ActionToolbarImpl> ourToolbars = new LinkedHashSet<>(); private static final String RIGHT_ALIGN_KEY = "RIGHT_ALIGN"; private static final String SECONDARY_SHORTCUT = "SecondaryActions.shortcut"; static { JBUIScale.addUserScaleChangeListener(__ -> { ((JBDimension)ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE).update(); ((JBDimension)ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE).update(); }); } public static void updateAllToolbarsImmediately() { for (ActionToolbarImpl toolbar : new ArrayList<>(ourToolbars)) { toolbar.updateActionsImmediately(); for (Component c : toolbar.getComponents()) { if (c instanceof ActionButton) { ((ActionButton)c).updateToolTipText(); ((ActionButton)c).updateIcon(); } } } } /** * This array contains Rectangles which define bounds of the corresponding * components in the toolbar. This list can be consider as a cache of the * Rectangle objects that are used in calculation of preferred sizes and * components layout. */ private final List<Rectangle> myComponentBounds = new ArrayList<>(); private JBDimension myMinimumButtonSize = JBUI.emptySize(); /** * @see ActionToolbar#getLayoutPolicy() */ @LayoutPolicy private int myLayoutPolicy; private int myOrientation; private final ActionGroup myActionGroup; @NotNull private final String myPlace; List<? extends AnAction> myVisibleActions; private final PresentationFactory myPresentationFactory = new PresentationFactory(); private final boolean myDecorateButtons; private final ToolbarUpdater myUpdater; /** * @see ActionToolbar#adjustTheSameSize(boolean) */ private boolean myAdjustTheSameSize; private final ActionButtonLook myMinimalButtonLook = ActionButtonLook.INPLACE_LOOK; private final DataManager myDataManager; private Rectangle myAutoPopupRec; private final DefaultActionGroup mySecondaryActions = new DefaultActionGroup(); private PopupStateModifier mySecondaryButtonPopupStateModifier; private boolean myForceMinimumSize; private boolean myForceShowFirstComponent; private boolean mySkipWindowAdjustments; private boolean myMinimalMode; public ActionButton getSecondaryActionsButton() { return mySecondaryActionsButton; } private ActionButton mySecondaryActionsButton; private int myFirstOutsideIndex = -1; private JBPopup myPopup; private JComponent myTargetComponent; private boolean myReservePlaceAutoPopupIcon = true; private boolean myShowSeparatorTitles; public ActionToolbarImpl(@NotNull String place, @NotNull ActionGroup actionGroup, boolean horizontal) { this(place, actionGroup, horizontal, false, false); } public ActionToolbarImpl(@NotNull String place, @NotNull ActionGroup actionGroup, boolean horizontal, boolean decorateButtons) { this(place, actionGroup, horizontal, decorateButtons, false); } public ActionToolbarImpl(@NotNull String place, @NotNull ActionGroup actionGroup, final boolean horizontal, final boolean decorateButtons, boolean updateActionsNow) { super(null); myPlace = place; myActionGroup = actionGroup; myVisibleActions = new ArrayList<>(); myDataManager = DataManager.getInstance(); myDecorateButtons = decorateButtons; myUpdater = new ToolbarUpdater(this) { @Override protected void updateActionsImpl(boolean transparentOnly, boolean forced) { if (!ApplicationManager.getApplication().isDisposed()) { ActionToolbarImpl.this.updateActionsImpl(transparentOnly, forced); } } }; setOrientation(horizontal ? SwingConstants.HORIZONTAL : SwingConstants.VERTICAL); mySecondaryActions.getTemplatePresentation().setIcon(AllIcons.General.GearPlain); mySecondaryActions.setPopup(true); myUpdater.updateActions(updateActionsNow, false); // If the panel doesn't handle mouse event then it will be passed to its parent. // It means that if the panel is in sliding mode then the focus goes to the editor // and panel will be automatically hidden. enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.CONTAINER_EVENT_MASK); setMiniMode(false); } @Override public void updateUI() { super.updateUI(); for (Component component : getComponents()) { tweakActionComponentUI(component); } } @NotNull public String getPlace() { return myPlace; } @Override public void addNotify() { super.addNotify(); ourToolbars.add(this); // should update action right on the showing, otherwise toolbar may not be displayed at all, // since by default all updates are postponed until frame gets focused. updateActionsImmediately(); } private boolean isInsideNavBar() { return ActionPlaces.NAVIGATION_BAR_TOOLBAR.equals(myPlace); } @Override public void removeNotify() { super.removeNotify(); ourToolbars.remove(this); if (myPopup != null) { myPopup.cancel(); myPopup = null; } CancellablePromise<List<AnAction>> lastUpdate = myLastUpdate; if (lastUpdate != null) { lastUpdate.cancel(); if (ApplicationManager.getApplication().isUnitTestMode()) { try { lastUpdate.blockingGet(1, TimeUnit.DAYS); } catch (Exception e) { throw new RuntimeException(e); } } } } @NotNull @Override public JComponent getComponent() { return this; } @Override public int getLayoutPolicy() { return myLayoutPolicy; } @Override public void setLayoutPolicy(@LayoutPolicy int layoutPolicy) { if (layoutPolicy != NOWRAP_LAYOUT_POLICY && layoutPolicy != WRAP_LAYOUT_POLICY && layoutPolicy != AUTO_LAYOUT_POLICY) { throw new IllegalArgumentException("wrong layoutPolicy: " + layoutPolicy); } myLayoutPolicy = layoutPolicy; } @Override protected Graphics getComponentGraphics(Graphics graphics) { return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics)); } @NotNull public ActionGroup getActionGroup() { return myActionGroup; } @Override protected void paintComponent(final Graphics g) { super.paintComponent(g); if (myLayoutPolicy == AUTO_LAYOUT_POLICY && myAutoPopupRec != null) { if (myOrientation == SwingConstants.HORIZONTAL) { final int dy = myAutoPopupRec.height / 2 - AllIcons.Ide.Link.getIconHeight() / 2; AllIcons.Ide.Link.paintIcon(this, g, (int)myAutoPopupRec.getMaxX() - AllIcons.Ide.Link.getIconWidth() - 1, myAutoPopupRec.y + dy); } else { final int dx = myAutoPopupRec.width / 2 - AllIcons.Ide.Link.getIconWidth() / 2; AllIcons.Ide.Link.paintIcon(this, g, myAutoPopupRec.x + dx, (int)myAutoPopupRec.getMaxY() - AllIcons.Ide.Link.getIconWidth() - 1); } } } public void setSecondaryButtonPopupStateModifier(@NotNull PopupStateModifier popupStateModifier) { mySecondaryButtonPopupStateModifier = popupStateModifier; } private void fillToolBar(@NotNull List<? extends AnAction> actions, boolean layoutSecondaries) { boolean isLastElementSeparator = false; List<AnAction> rightAligned = new ArrayList<>(); for (int i = 0; i < actions.size(); i++) { AnAction action = actions.get(i); if (action instanceof RightAlignedToolbarAction) { rightAligned.add(action); continue; } if (layoutSecondaries) { if (!myActionGroup.isPrimary(action)) { mySecondaryActions.add(action); continue; } } if (action instanceof Separator) { if (isLastElementSeparator) continue; if (i > 0 && i < actions.size() - 1) { add(SEPARATOR_CONSTRAINT, new MySeparator(myShowSeparatorTitles ? ((Separator) action).getText() : null)); isLastElementSeparator = true; continue; } } else if (action instanceof CustomComponentAction) { add(CUSTOM_COMPONENT_CONSTRAINT, getCustomComponent(action)); } else { add(ACTION_BUTTON_CONSTRAINT, createToolbarButton(action)); } isLastElementSeparator = false; } if (mySecondaryActions.getChildrenCount() > 0) { mySecondaryActionsButton = new ActionButton(mySecondaryActions, myPresentationFactory.getPresentation(mySecondaryActions), myPlace, getMinimumButtonSize()) { @Override @ButtonState public int getPopState() { return mySecondaryButtonPopupStateModifier != null && mySecondaryButtonPopupStateModifier.willModify() ? mySecondaryButtonPopupStateModifier.getModifiedPopupState() : super.getPopState(); } @Override protected String getShortcutText() { Object shortcut = myPresentation.getClientProperty(SECONDARY_SHORTCUT); return shortcut != null ? shortcut.toString() : super.getShortcutText(); } }; mySecondaryActionsButton.setNoIconsInPopup(true); add(SECONDARY_ACTION_CONSTRAINT, mySecondaryActionsButton); } for (AnAction action : rightAligned) { JComponent button = action instanceof CustomComponentAction ? getCustomComponent(action) : createToolbarButton(action); if (!isInsideNavBar()) { button.putClientProperty(RIGHT_ALIGN_KEY, Boolean.TRUE); } add(button); } } @NotNull private JComponent getCustomComponent(@NotNull AnAction action) { Presentation presentation = myPresentationFactory.getPresentation(action); JComponent customComponent = presentation.getClientProperty(CustomComponentAction.COMPONENT_KEY); if (customComponent == null) { customComponent = ((CustomComponentAction)action).createCustomComponent(presentation, myPlace); presentation.putClientProperty(CustomComponentAction.COMPONENT_KEY, customComponent); ComponentUtil.putClientProperty(customComponent, CustomComponentAction.ACTION_KEY, action); } tweakActionComponentUI(customComponent); AbstractButton clickable = UIUtil.findComponentOfType(customComponent, AbstractButton.class); if (clickable != null) { class ToolbarClicksCollectorListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) {ToolbarClicksCollector.record(action, myPlace, e, getDataContext());} } if (Arrays.stream(clickable.getMouseListeners()).noneMatch(ml -> ml instanceof ToolbarClicksCollectorListener)) { clickable.addMouseListener(new ToolbarClicksCollectorListener()); } } return customComponent; } private void tweakActionComponentUI(@NotNull Component actionComponent) { if (ActionPlaces.EDITOR_TOOLBAR.equals(myPlace)) { // tweak font & color for editor toolbar to match editor tabs style actionComponent.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL)); actionComponent.setForeground(ColorUtil.dimmer(JBColor.BLACK)); } } @NotNull private Dimension getMinimumButtonSize() { return isInsideNavBar() ? NAVBAR_MINIMUM_BUTTON_SIZE : DEFAULT_MINIMUM_BUTTON_SIZE; } @NotNull protected ActionButton createToolbarButton(@NotNull AnAction action, final ActionButtonLook look, @NotNull String place, @NotNull Presentation presentation, @NotNull Dimension minimumSize) { if (action.displayTextInToolbar()) { int mnemonic = KeyEvent.getExtendedKeyCodeForChar(action.getTemplatePresentation().getMnemonic()); ActionButtonWithText buttonWithText = new ActionButtonWithText(action, presentation, place, minimumSize); if (mnemonic != KeyEvent.VK_UNDEFINED) { buttonWithText.registerKeyboardAction(__ -> buttonWithText.click(), KeyStroke.getKeyStroke(mnemonic, InputEvent.ALT_DOWN_MASK), WHEN_IN_FOCUSED_WINDOW); } tweakActionComponentUI(buttonWithText); return buttonWithText; } ActionButton actionButton = new ActionButton(action, presentation, place, minimumSize) { @Override protected DataContext getDataContext() { return getToolbarDataContext(); } @NotNull @Override protected Icon getFallbackIcon(boolean enabled) { return enabled ? AllIcons.Toolbar.Unknown : IconLoader.getDisabledIcon(AllIcons.Toolbar.Unknown); } }; actionButton.setLook(look); return actionButton; } @NotNull private ActionButton createToolbarButton(@NotNull AnAction action) { return createToolbarButton( action, myMinimalMode ? myMinimalButtonLook : myDecorateButtons ? new ActionButtonLook() { @Override public void paintBorder(Graphics g, JComponent c, int state) { g.setColor(JBColor.border()); g.drawLine(c.getWidth()-1, 0, c.getWidth()-1, c.getHeight()); } @Override public void paintBackground(Graphics g, JComponent component, int state) { if (state == ActionButtonComponent.PUSHED) { g.setColor(component.getBackground().darker()); ((Graphics2D)g).fill(g.getClip()); } } } : null, myPlace, myPresentationFactory.getPresentation(action), myMinimumButtonSize.size()); } @Override public void doLayout() { if (!isValid()) { calculateBounds(getSize(), myComponentBounds); } final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= myComponentBounds.size()); for (int i = componentCount - 1; i >= 0; i final Component component = getComponent(i); component.setBounds(myComponentBounds.get(i)); } } @Override public void validate() { if (!isValid()) { calculateBounds(getSize(), myComponentBounds); super.validate(); } } private Dimension getChildPreferredSize(int index) { Component component = getComponent(index); return component.isVisible() ? component.getPreferredSize() : new Dimension(); } /** * @return maximum button width */ private int getMaxButtonWidth() { int width = 0; for (int i = 0; i < getComponentCount(); i++) { final Dimension dimension = getChildPreferredSize(i); width = Math.max(width, dimension.width); } return width; } /** * @return maximum button height */ @Override public int getMaxButtonHeight() { int height = 0; for (int i = 0; i < getComponentCount(); i++) { final Dimension dimension = getChildPreferredSize(i); height = Math.max(height, dimension.height); } return height; } private void calculateBoundsNowrapImpl(@NotNull List<? extends Rectangle> bounds) { final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= bounds.size()); final int width = getWidth(); final int height = getHeight(); final Insets insets = getInsets(); if (myAdjustTheSameSize) { final int maxWidth = getMaxButtonWidth(); final int maxHeight = getMaxButtonHeight(); int offset = 0; if (myOrientation == SwingConstants.HORIZONTAL) { for (int i = 0; i < componentCount; i++) { final Rectangle r = bounds.get(i); r.setBounds(insets.left + offset, insets.top + (height - maxHeight) / 2, maxWidth, maxHeight); offset += maxWidth; } } else { for (int i = 0; i < componentCount; i++) { final Rectangle r = bounds.get(i); r.setBounds(insets.left + (width - maxWidth) / 2, insets.top + offset, maxWidth, maxHeight); offset += maxHeight; } } } else { if (myOrientation == SwingConstants.HORIZONTAL) { final int maxHeight = getMaxButtonHeight(); int offset = 0; for (int i = 0; i < componentCount; i++) { final Dimension d = getChildPreferredSize(i); final Rectangle r = bounds.get(i); r.setBounds(insets.left + offset, insets.top + (maxHeight - d.height) / 2, d.width, d.height); offset += d.width; } } else { final int maxWidth = getMaxButtonWidth(); int offset = 0; for (int i = 0; i < componentCount; i++) { final Dimension d = getChildPreferredSize(i); final Rectangle r = bounds.get(i); r.setBounds(insets.left + (maxWidth - d.width) / 2, insets.top + offset, d.width, d.height); offset += d.height; } } } } private void calculateBoundsAutoImp(@NotNull Dimension sizeToFit, @NotNull List<? extends Rectangle> bounds) { final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= bounds.size()); final boolean actualLayout = bounds == myComponentBounds; if (actualLayout) { myAutoPopupRec = null; } int autoButtonSize = AllIcons.Ide.Link.getIconWidth(); boolean full = false; final Insets insets = getInsets(); int widthToFit = sizeToFit.width - insets.left - insets.right; int heightToFit = sizeToFit.height - insets.top - insets.bottom; if (myOrientation == SwingConstants.HORIZONTAL) { int eachX = 0; int maxHeight = heightToFit; for (int i = 0; i < componentCount; i++) { final Component eachComp = getComponent(i); final boolean isLast = i == componentCount - 1; final Rectangle eachBound = new Rectangle(getChildPreferredSize(i)); maxHeight = Math.max(eachBound.height, maxHeight); if (!full) { boolean inside = isLast ? eachX + eachBound.width <= widthToFit : eachX + eachBound.width + autoButtonSize <= widthToFit; if (inside) { if (eachComp == mySecondaryActionsButton) { assert isLast; if (sizeToFit.width != Integer.MAX_VALUE) { eachBound.x = sizeToFit.width - insets.right - eachBound.width; eachX = (int)eachBound.getMaxX() - insets.left; } else { eachBound.x = insets.left + eachX; } } else { eachBound.x = insets.left + eachX; eachX += eachBound.width; } eachBound.y = insets.top; } else { full = true; } } if (full) { if (myAutoPopupRec == null) { myAutoPopupRec = new Rectangle(insets.left + eachX, insets.top, widthToFit - eachX, heightToFit); myFirstOutsideIndex = i; } eachBound.x = Integer.MAX_VALUE; eachBound.y = Integer.MAX_VALUE; } bounds.get(i).setBounds(eachBound); } for (final Rectangle r : bounds) { if (r.height < maxHeight) { r.y += (maxHeight - r.height) / 2; } } } else { int eachY = 0; for (int i = 0; i < componentCount; i++) { final Rectangle eachBound = new Rectangle(getChildPreferredSize(i)); if (!full) { boolean outside; if (i < componentCount - 1) { outside = eachY + eachBound.height + autoButtonSize < heightToFit; } else { outside = eachY + eachBound.height < heightToFit; } if (outside) { eachBound.x = insets.left; eachBound.y = insets.top + eachY; eachY += eachBound.height; } else { full = true; } } if (full) { if (myAutoPopupRec == null) { myAutoPopupRec = new Rectangle(insets.left, insets.top + eachY, widthToFit, heightToFit - eachY); myFirstOutsideIndex = i; } eachBound.x = Integer.MAX_VALUE; eachBound.y = Integer.MAX_VALUE; } bounds.get(i).setBounds(eachBound); } } } private void calculateBoundsWrapImpl(@NotNull Dimension sizeToFit, @NotNull List<? extends Rectangle> bounds) { // We have to graceful handle case when toolbar was not laid out yet. // In this case we calculate bounds as it is a NOWRAP toolbar. if (getWidth() == 0 || getHeight() == 0) { try { setLayoutPolicy(NOWRAP_LAYOUT_POLICY); calculateBoundsNowrapImpl(bounds); } finally { setLayoutPolicy(WRAP_LAYOUT_POLICY); } return; } final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= bounds.size()); final Insets insets = getInsets(); int widthToFit = sizeToFit.width - insets.left - insets.right; int heightToFit = sizeToFit.height - insets.top - insets.bottom; if (myAdjustTheSameSize) { final int maxWidth = getMaxButtonWidth(); final int maxHeight = getMaxButtonHeight(); int xOffset = 0; int yOffset = 0; if (myOrientation == SwingConstants.HORIZONTAL) { // Lay components out int maxRowWidth = getMaxRowWidth(widthToFit, maxWidth); for (int i = 0; i < componentCount; i++) { if (xOffset + maxWidth > maxRowWidth) { // place component at new row xOffset = 0; yOffset += maxHeight; } final Rectangle each = bounds.get(i); each.setBounds(insets.left + xOffset, insets.top + yOffset, maxWidth, maxHeight); xOffset += maxWidth; } } else { // Lay components out // Calculate max size of a row. It's not possible to make more then 3 column toolbar final int maxRowHeight = Math.max(heightToFit, componentCount * myMinimumButtonSize.height() / 3); for (int i = 0; i < componentCount; i++) { if (yOffset + maxHeight > maxRowHeight) { // place component at new row yOffset = 0; xOffset += maxWidth; } final Rectangle each = bounds.get(i); each.setBounds(insets.left + xOffset, insets.top + yOffset, maxWidth, maxHeight); yOffset += maxHeight; } } } else { if (myOrientation == SwingConstants.HORIZONTAL) { // Calculate row height int rowHeight = 0; final Dimension[] dims = new Dimension[componentCount]; // we will use this dimensions later for (int i = 0; i < componentCount; i++) { dims[i] = getChildPreferredSize(i); final int height = dims[i].height; rowHeight = Math.max(rowHeight, height); } // Lay components out int xOffset = 0; int yOffset = 0; // Calculate max size of a row. It's not possible to make more then 3 row toolbar int maxRowWidth = getMaxRowWidth(widthToFit, myMinimumButtonSize.width()); for (int i = 0; i < componentCount; i++) { final Dimension d = dims[i]; if (xOffset + d.width > maxRowWidth) { // place component at new row xOffset = 0; yOffset += rowHeight; } final Rectangle each = bounds.get(i); each.setBounds(insets.left + xOffset, insets.top + yOffset + (rowHeight - d.height) / 2, d.width, d.height); xOffset += d.width; } } else { // Calculate row width int rowWidth = 0; final Dimension[] dims = new Dimension[componentCount]; // we will use this dimensions later for (int i = 0; i < componentCount; i++) { dims[i] = getChildPreferredSize(i); final int width = dims[i].width; rowWidth = Math.max(rowWidth, width); } // Lay components out int xOffset = 0; int yOffset = 0; // Calculate max size of a row. It's not possible to make more then 3 column toolbar final int maxRowHeight = Math.max(heightToFit, componentCount * myMinimumButtonSize.height() / 3); for (int i = 0; i < componentCount; i++) { final Dimension d = dims[i]; if (yOffset + d.height > maxRowHeight) { // place component at new row yOffset = 0; xOffset += rowWidth; } final Rectangle each = bounds.get(i); each.setBounds(insets.left + xOffset + (rowWidth - d.width) / 2, insets.top + yOffset, d.width, d.height); yOffset += d.height; } } } } private int getMaxRowWidth(int widthToFit, int maxWidth) { int componentCount = getComponentCount(); // Calculate max size of a row. It's not possible to make more than 3 row toolbar int maxRowWidth = Math.max(widthToFit, componentCount * maxWidth / 3); for (int i = 0; i < componentCount; i++) { final Component component = getComponent(i); if (component instanceof JComponent && ((JComponent)component).getClientProperty(RIGHT_ALIGN_KEY) == Boolean.TRUE) { maxRowWidth -= getChildPreferredSize(i).width; } } return maxRowWidth; } /** * Calculates bounds of all the components in the toolbar */ private void calculateBounds(@NotNull Dimension size2Fit, @NotNull List<Rectangle> bounds) { bounds.clear(); for (int i = 0; i < getComponentCount(); i++) { bounds.add(new Rectangle()); } if (myLayoutPolicy == NOWRAP_LAYOUT_POLICY) { calculateBoundsNowrapImpl(bounds); } else if (myLayoutPolicy == WRAP_LAYOUT_POLICY) { calculateBoundsWrapImpl(size2Fit, bounds); } else if (myLayoutPolicy == AUTO_LAYOUT_POLICY) { calculateBoundsAutoImp(size2Fit, bounds); } else { throw new IllegalStateException("unknown layoutPolicy: " + myLayoutPolicy); } if (getComponentCount() > 0 && size2Fit.width < Integer.MAX_VALUE) { int maxHeight = 0; for (int i = 0; i < bounds.size() - 2; i++) { maxHeight = Math.max(maxHeight, bounds.get(i).height); } int rightOffset = 0; Insets insets = getInsets(); for (int i = getComponentCount() - 1, j = 1; i > 0; i final Component component = getComponent(i); if (component instanceof JComponent && ((JComponent)component).getClientProperty(RIGHT_ALIGN_KEY) == Boolean.TRUE) { rightOffset += bounds.get(i).width; Rectangle r = bounds.get(bounds.size() - j); r.x = size2Fit.width - rightOffset; r.y = insets.top + (getHeight() - insets.top - insets.bottom - bounds.get(i).height) / 2; } } } } @Override @NotNull public Dimension getPreferredSize() { return updatePreferredSize(super.getPreferredSize()); } protected Dimension updatePreferredSize(Dimension preferredSize) { final ArrayList<Rectangle> bounds = new ArrayList<>(); calculateBounds(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE), bounds);//it doesn't take into account wrapping if (bounds.isEmpty()) return JBUI.emptySize(); int forcedHeight = 0; if (getWidth() > 0 && getLayoutPolicy() == ActionToolbar.WRAP_LAYOUT_POLICY && myOrientation == SwingConstants.HORIZONTAL) { final ArrayList<Rectangle> limitedBounds = new ArrayList<>(); calculateBounds(new Dimension(getWidth(), Integer.MAX_VALUE), limitedBounds); Rectangle union = null; for (Rectangle bound : limitedBounds) { union = union == null ? bound : union.union(bound); } forcedHeight = union != null ? union.height : 0; } int xLeft = Integer.MAX_VALUE; int yTop = Integer.MAX_VALUE; int xRight = Integer.MIN_VALUE; int yBottom = Integer.MIN_VALUE; for (int i = bounds.size() - 1; i >= 0; i final Rectangle each = bounds.get(i); if (each.x == Integer.MAX_VALUE) continue; xLeft = Math.min(xLeft, each.x); yTop = Math.min(yTop, each.y); xRight = Math.max(xRight, each.x + each.width); yBottom = Math.max(yBottom, each.y + each.height); } final Dimension dimension = new Dimension(xRight - xLeft, Math.max(yBottom - yTop, forcedHeight)); if (myLayoutPolicy == AUTO_LAYOUT_POLICY && myReservePlaceAutoPopupIcon && !isInsideNavBar()) { if (myOrientation == SwingConstants.HORIZONTAL) { dimension.width += AllIcons.Ide.Link.getIconWidth(); } else { dimension.height += AllIcons.Ide.Link.getIconHeight(); } } JBInsets.addTo(dimension, getInsets()); return dimension; } /** * Forces the minimum size of the toolbar to show all buttons, When set to {@code true}. By default ({@code false}) the * toolbar will shrink further and show the auto popup chevron button. */ public void setForceMinimumSize(boolean force) { myForceMinimumSize = force; } /** * By default minimum size is to show chevron only. * If this option is {@code true} toolbar shows at least one (the first) component plus chevron (if need) */ public void setForceShowFirstComponent(boolean showFirstComponent) { myForceShowFirstComponent = showFirstComponent; } /** * This option makes sense when you use a toolbar inside JBPopup * When some 'actions' are hidden under the chevron the popup with extra components would be shown/hidden * with size adjustments for the main popup (this is default behavior). * If this option is {@code true} size adjustments would be omitted */ public void setSkipWindowAdjustments(boolean skipWindowAdjustments) { mySkipWindowAdjustments = skipWindowAdjustments; } @Override public Dimension getMinimumSize() { return updateMinimumSize(super.getMinimumSize()); } protected Dimension updateMinimumSize(Dimension minimumSize) { if (myForceMinimumSize) { return updatePreferredSize(minimumSize); } if (myLayoutPolicy == AUTO_LAYOUT_POLICY) { final Insets i = getInsets(); if (myForceShowFirstComponent && getComponentCount() > 0 && getComponent(0).isShowing()) { Component c = getComponent(0); Dimension firstSize = c.getPreferredSize(); if (myOrientation == SwingConstants.HORIZONTAL) { return new Dimension(firstSize.width + AllIcons.Ide.Link.getIconWidth() + i.left + i.right, Math.max(firstSize.height, myMinimumButtonSize.height()) + i.top + i.bottom); } else { return new Dimension(Math.max(firstSize.width, AllIcons.Ide.Link.getIconWidth()) + i.left + i.right, firstSize.height + myMinimumButtonSize.height() + i.top + i.bottom); } } return new Dimension(AllIcons.Ide.Link.getIconWidth() + i.left + i.right, myMinimumButtonSize.height() + i.top + i.bottom); } else { return minimumSize; } } private static class ToolbarReference extends WeakReference<ActionToolbarImpl> { private static final ReferenceQueue<ActionToolbarImpl> ourQueue = new ReferenceQueue<>(); private volatile Disposable myDisposable; ToolbarReference(@NotNull ActionToolbarImpl toolbar) { super(toolbar, ourQueue); processQueue(); } private static void processQueue() { while (true) { ToolbarReference ref = (ToolbarReference)ourQueue.poll(); if (ref == null) break; ref.disposeReference(); } } private void disposeReference() { Disposable disposable = myDisposable; if (disposable != null) { myDisposable = null; Disposer.dispose(disposable); } } } @NotNull protected Color getSeparatorColor() { return JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground(); } private final class MySeparator extends JComponent { private final String myText; private MySeparator(String text) { myText = text; setFont(JBUI.Fonts.toolbarSmallComboBoxFont()); } @Override public Dimension getPreferredSize() { int gap = JBUIScale.scale(2); int center = JBUIScale.scale(3); int width = gap * 2 + center; int height = JBUIScale.scale(24); if (myOrientation == SwingConstants.HORIZONTAL) { if (myText != null) { FontMetrics fontMetrics = getFontMetrics(getFont()); int textWidth = getTextWidth(fontMetrics, myText, getGraphics()); return new JBDimension(width + gap * 2 + textWidth, Math.max(fontMetrics.getHeight(), height), true); } else { return new JBDimension(width, height, true); } } else { //noinspection SuspiciousNameCombination return new JBDimension(height, width, true); } } @Override protected void paintComponent(final Graphics g) { if (getParent() == null) return; int gap = JBUIScale.scale(2); int center = JBUIScale.scale(3); int offset; if (myOrientation == SwingConstants.HORIZONTAL) { offset = ActionToolbarImpl.this.getHeight() - getMaxButtonHeight() - 1; } else { offset = ActionToolbarImpl.this.getWidth() - getMaxButtonWidth() - 1; } g.setColor(getSeparatorColor()); if (myOrientation == SwingConstants.HORIZONTAL) { int y2 = ActionToolbarImpl.this.getHeight() - gap * 2 - offset; LinePainter2D.paint((Graphics2D)g, center, gap, center, y2); if (myText != null) { FontMetrics fontMetrics = getFontMetrics(getFont()); int top = (getHeight() - fontMetrics.getHeight()) / 2; UISettings.setupAntialiasing(g); g.setColor(JBColor.foreground()); g.drawString(myText, gap * 2 + center + gap, top + fontMetrics.getAscent()); } } else { LinePainter2D.paint((Graphics2D)g, gap, center, ActionToolbarImpl.this.getWidth() - gap * 2 - offset, center); } } private int getTextWidth(@NotNull FontMetrics fontMetrics, @NotNull String text, @Nullable Graphics graphics) { if (graphics == null) { return fontMetrics.stringWidth(text); } else { Graphics g = graphics.create(); try { UISettings.setupAntialiasing(g); return fontMetrics.getStringBounds(text, g).getBounds().width; } finally { g.dispose(); } } } } @Override public void adjustTheSameSize(final boolean value) { if (myAdjustTheSameSize == value) { return; } myAdjustTheSameSize = value; revalidate(); } @Override public void setMinimumButtonSize(@NotNull final Dimension size) { myMinimumButtonSize = JBDimension.create(size, true); for (int i = getComponentCount() - 1; i >= 0; i final Component component = getComponent(i); if (component instanceof ActionButton) { final ActionButton button = (ActionButton)component; button.setMinimumButtonSize(size); } } revalidate(); } @Override public void setOrientation(@MagicConstant(intValues = {SwingConstants.HORIZONTAL, SwingConstants.VERTICAL}) int orientation) { if (SwingConstants.HORIZONTAL != orientation && SwingConstants.VERTICAL != orientation) { throw new IllegalArgumentException("wrong orientation: " + orientation); } myOrientation = orientation; } @MagicConstant(intValues = {SwingConstants.HORIZONTAL, SwingConstants.VERTICAL}) public int getOrientation() { return myOrientation; } @Override public void updateActionsImmediately() { ApplicationManager.getApplication().assertIsDispatchThread(); myUpdater.updateActions(true, false); } private boolean myAlreadyUpdated; private void updateActionsImpl(boolean transparentOnly, boolean forced) { DataContext dataContext = getDataContext(); boolean async = myAlreadyUpdated && Registry.is("actionSystem.update.actions.asynchronously") && ourToolbars.contains(this) && isShowing(); ActionUpdater updater = new ActionUpdater(LaterInvocator.isInModalContext(), myPresentationFactory, async ? new AsyncDataContext(dataContext) : dataContext, myPlace, false, true, transparentOnly); if (async) { if (myLastUpdate != null) myLastUpdate.cancel(); myLastUpdate = updater.expandActionGroupAsync(myActionGroup, false); myLastUpdate.onSuccess(actions -> actionsUpdated(forced, actions)).onProcessed(__ -> myLastUpdate = null); } else { actionsUpdated(forced, updater.expandActionGroupWithTimeout(myActionGroup, false)); myAlreadyUpdated = true; } } private CancellablePromise<List<AnAction>> myLastUpdate; private void actionsUpdated(boolean forced, @NotNull List<? extends AnAction> newVisibleActions) { if (forced || !newVisibleActions.equals(myVisibleActions)) { boolean shouldRebuildUI = newVisibleActions.isEmpty() || myVisibleActions.isEmpty(); myVisibleActions = newVisibleActions; Dimension oldSize = getPreferredSize(); removeAll(); mySecondaryActions.removeAll(); mySecondaryActionsButton = null; fillToolBar(myVisibleActions, getLayoutPolicy() == AUTO_LAYOUT_POLICY && myOrientation == SwingConstants.HORIZONTAL); Dimension newSize = getPreferredSize(); if (!mySkipWindowAdjustments) { ((WindowManagerEx)WindowManager.getInstance()).adjustContainerWindow(this, oldSize, newSize); } if (shouldRebuildUI) { revalidate(); } else { Container parent = getParent(); if (parent != null) { parent.invalidate(); parent.validate(); } } repaint(); } } @Override public boolean hasVisibleActions() { return !myVisibleActions.isEmpty(); } @Override public void setTargetComponent(final JComponent component) { myTargetComponent = component; if (myTargetComponent != null) { updateWhenFirstShown(myTargetComponent, new ToolbarReference(this)); } } private static void updateWhenFirstShown(@NotNull JComponent targetComponent, @NotNull ToolbarReference ref) { Activatable activatable = new Activatable() { @Override public void showNotify() { ActionToolbarImpl toolbar = ref.get(); if (toolbar != null) { toolbar.myUpdater.updateActions(false, false); } } }; ref.myDisposable = new UiNotifyConnector(targetComponent, activatable) { @Override protected void showNotify() { super.showNotify(); ref.disposeReference(); } }; } @NotNull @Override public DataContext getToolbarDataContext() { return getDataContext(); } @Override public void setShowSeparatorTitles(boolean showSeparatorTitles) { myShowSeparatorTitles = showSeparatorTitles; } @NotNull protected DataContext getDataContext() { return myTargetComponent != null ? myDataManager.getDataContext(myTargetComponent) : ((DataManagerImpl)myDataManager).getDataContextTest(this); } @Override protected void processMouseMotionEvent(final MouseEvent e) { super.processMouseMotionEvent(e); if (getLayoutPolicy() != AUTO_LAYOUT_POLICY) { return; } if (myAutoPopupRec != null && myAutoPopupRec.contains(e.getPoint())) { IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(() -> showAutoPopup()); } } private void showAutoPopup() { if (isPopupShowing()) return; final ActionGroup group; if (myOrientation == SwingConstants.HORIZONTAL) { group = myActionGroup; } else { final DefaultActionGroup outside = new DefaultActionGroup(); for (int i = myFirstOutsideIndex; i < myVisibleActions.size(); i++) { outside.add(myVisibleActions.get(i)); } group = outside; } PopupToolbar popupToolbar = new PopupToolbar(myPlace, group, true, this) { @Override protected void onOtherActionPerformed() { hidePopup(); } @NotNull @Override protected DataContext getDataContext() { return ActionToolbarImpl.this.getDataContext(); } }; popupToolbar.setLayoutPolicy(NOWRAP_LAYOUT_POLICY); popupToolbar.updateActionsImmediately(); Point location; if (myOrientation == SwingConstants.HORIZONTAL) { location = getLocationOnScreen(); ToolWindow toolWindow = DataManager.getInstance().getDataContext(this).getData(PlatformDataKeys.TOOL_WINDOW); if (toolWindow != null && toolWindow.getAnchor() == ToolWindowAnchor.RIGHT) { int rightXOnScreen = location.x + getWidth(); int toolbarPreferredWidth = popupToolbar.getPreferredSize().width; location.x = rightXOnScreen - toolbarPreferredWidth; } } else { location = getLocationOnScreen(); location.y = location.y + getHeight() - popupToolbar.getPreferredSize().height; } ActionManagerEx actionManager = ActionManagerEx.getInstanceEx(); final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(popupToolbar, null); builder.setResizable(false) .setMovable(true) // fit the screen automatically .setRequestFocus(true) .setMayBeParent(true) .setTitle(null) .setCancelOnClickOutside(true) .setCancelOnOtherWindowOpen(true) .setCancelCallback(() -> { final boolean toClose = actionManager.isActionPopupStackEmpty(); if (toClose) { myUpdater.updateActions(false, true); } return toClose; }) .setCancelOnMouseOutCallback(event -> { return myAutoPopupRec != null && actionManager.isActionPopupStackEmpty() && !new RelativeRectangle(this, myAutoPopupRec).contains(new RelativePoint(event)); }); builder.addListener(new JBPopupListener() { @Override public void onClosed(@NotNull LightweightWindowEvent event) { processClosed(); } }); myPopup = builder.createPopup(); Disposer.register(myPopup, popupToolbar); myPopup.showInScreenCoordinates(this, location); Window window = SwingUtilities.getWindowAncestor(this); if (window == null) { return; } ComponentAdapter componentAdapter = new ComponentAdapter() { @Override public void componentResized(final ComponentEvent e) { hidePopup(); } @Override public void componentMoved(final ComponentEvent e) { hidePopup(); } @Override public void componentShown(final ComponentEvent e) { hidePopup(); } @Override public void componentHidden(final ComponentEvent e) { hidePopup(); } }; window.addComponentListener(componentAdapter); Disposer.register(popupToolbar, () -> window.removeComponentListener(componentAdapter)); } private boolean isPopupShowing() { return myPopup != null && !myPopup.isDisposed(); } private void hidePopup() { if (myPopup != null) { myPopup.cancel(); processClosed(); } } private void processClosed() { if (myPopup == null) return; if (myPopup.isVisible()) { // setCancelCallback(..) can override cancel() return; } // cancel() already called Disposer.dispose() myPopup = null; myUpdater.updateActions(false, false); } abstract static class PopupToolbar extends ActionToolbarImpl implements AnActionListener, Disposable { private final JComponent myParent; PopupToolbar(@NotNull String place, @NotNull ActionGroup actionGroup, final boolean horizontal, @NotNull JComponent parent) { super(place, actionGroup, horizontal, false, true); ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(AnActionListener.TOPIC, this); myParent = parent; setBorder(myParent.getBorder()); } @Override public Container getParent() { Container parent = super.getParent(); return parent != null ? parent : myParent; } @Override public void dispose() { } @Override public void afterActionPerformed(@NotNull final AnAction action, @NotNull final DataContext dataContext, @NotNull AnActionEvent event) { if (!myVisibleActions.contains(action)) { onOtherActionPerformed(); } } protected abstract void onOtherActionPerformed(); } @Override public void setReservePlaceAutoPopupIcon(final boolean reserve) { myReservePlaceAutoPopupIcon = reserve; } @Override public void setSecondaryActionsTooltip(@NotNull String secondaryActionsTooltip) { mySecondaryActions.getTemplatePresentation().setText(secondaryActionsTooltip); } public void setSecondaryActionsShortcut(@NotNull String secondaryActionsShortcut) { mySecondaryActions.getTemplatePresentation().putClientProperty(SECONDARY_SHORTCUT, secondaryActionsShortcut); } @Override public void setSecondaryActionsIcon(Icon icon) { setSecondaryActionsIcon(icon, false); } @Override public void setSecondaryActionsIcon(Icon icon, boolean hideDropdownIcon) { Presentation presentation = mySecondaryActions.getTemplatePresentation(); presentation.setIcon(icon); presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, hideDropdownIcon ? Boolean.TRUE : null); } @NotNull @Override public List<AnAction> getActions(boolean originalProvider) { return getActions(); } @NotNull @Override public List<AnAction> getActions() { ArrayList<AnAction> result = new ArrayList<>(); ArrayList<AnAction> secondary = new ArrayList<>(); AnAction[] kids = myActionGroup.getChildren(null); for (AnAction each : kids) { if (myActionGroup.isPrimary(each)) { result.add(each); } else { secondary.add(each); } } result.add(new Separator()); result.addAll(secondary); return result; } @Override public void setMiniMode(boolean minimalMode) { //if (myMinimalMode == minimalMode) return; myMinimalMode = minimalMode; if (myMinimalMode) { setMinimumButtonSize(JBUI.emptySize()); setLayoutPolicy(NOWRAP_LAYOUT_POLICY); setBorder(JBUI.Borders.empty()); setOpaque(false); } else { setBorder(JBUI.Borders.empty(2)); setMinimumButtonSize(myDecorateButtons ? JBUI.size(30, 20) : DEFAULT_MINIMUM_BUTTON_SIZE); setOpaque(true); setLayoutPolicy(AUTO_LAYOUT_POLICY); } myUpdater.updateActions(false, true); } @TestOnly public Presentation getPresentation(AnAction action) { return myPresentationFactory.getPresentation(action); } public void clearPresentationCache() { myPresentationFactory.reset(); } public interface PopupStateModifier { @ActionButtonComponent.ButtonState int getModifiedPopupState(); boolean willModify(); } }
package com.intellij.openapi.application; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.UUID; import java.util.prefs.Preferences; /** * UUID identifying pair user@computer */ public final class PermanentInstallationID { private static final Logger LOG = Logger.getInstance("#PermanentInstallationID"); private static final String OLD_USER_ON_MACHINE_ID_KEY = "JetBrains.UserIdOnMachine"; @NonNls private static final String INSTALLATION_ID_KEY = "user_id_on_machine"; private static final String INSTALLATION_ID = calculateInstallationId(); @NotNull public static String get() { return INSTALLATION_ID; } private static String calculateInstallationId() { String installationId = null; try { final ApplicationInfoEx appInfo = ApplicationInfoImpl.getShadowInstance(); final Preferences oldPrefs = Preferences.userRoot(); final String oldValue = appInfo.isVendorJetBrains()? oldPrefs.get(OLD_USER_ON_MACHINE_ID_KEY, null) : null; // compatibility with previous versions final String companyName = appInfo.getShortCompanyName(); final Preferences prefs = Preferences.userRoot().node(StringUtil.isEmptyOrSpaces(companyName)? "jetbrains" : StringUtil.toLowerCase(companyName)); installationId = prefs.get(INSTALLATION_ID_KEY, null); if (StringUtil.isEmptyOrSpaces(installationId)) { installationId = !StringUtil.isEmptyOrSpaces(oldValue) ? oldValue : UUID.randomUUID().toString(); prefs.put(INSTALLATION_ID_KEY, installationId); } if (!appInfo.isVendorJetBrains()) { return installationId; } // for Windows attempt to use PermanentUserId, so that DotNet products and IDEA would use the same ID. if (SystemInfo.isWindows) { installationId = syncWithSharedFile("PermanentUserId", installationId, prefs, INSTALLATION_ID_KEY); } // make sure values in older location and in the new location are the same if (!installationId.equals(oldValue)) { oldPrefs.put(OLD_USER_ON_MACHINE_ID_KEY, installationId); } } catch (Throwable ex) { // should not happen LOG.info("Unexpected error initializing Installation ID", ex); } return installationId == null? UUID.randomUUID().toString() : installationId; } @NotNull public static String syncWithSharedFile(@NotNull String fileName, @NotNull String installationId, @NotNull Preferences prefs, @NotNull String prefsKey) { try { final String appdata = System.getenv("APPDATA"); if (appdata != null) { final File dir = new File(appdata, "JetBrains"); if (dir.exists() || dir.mkdirs()) { final File permanentIdFile = new File(dir, fileName); String fromFile = ""; if (permanentIdFile.exists()) { fromFile = loadFromFile(permanentIdFile).trim(); } if (!fromFile.isEmpty()) { if (!fromFile.equals(installationId)) { installationId = fromFile; prefs.put(prefsKey, installationId); } } else { writeToFile(permanentIdFile, installationId); } } } } catch (Throwable ex) { LOG.info("Error synchronizing Installation ID", ex); } return installationId; } @NotNull private static String loadFromFile(@NotNull File file) throws IOException { try (FileInputStream is = new FileInputStream(file)) { final byte[] bytes = FileUtilRt.loadBytes(is); final int offset = CharsetToolkit.hasUTF8Bom(bytes) ? CharsetToolkit.UTF8_BOM.length : 0; return new String(bytes, offset, bytes.length - offset, StandardCharsets.UTF_8); } } private static void writeToFile(@NotNull File file, @NotNull String text) throws IOException { try (DataOutputStream stream = new DataOutputStream(new FileOutputStream(file))) { stream.write(text.getBytes(StandardCharsets.UTF_8)); } } }
package org.lockss.plugin.highwire.aps; import java.io.InputStream; import java.util.Iterator; import java.util.Stack; import java.util.regex.Pattern; import org.lockss.config.*; import org.lockss.daemon.*; import org.lockss.extractor.*; import org.lockss.plugin.*; import org.lockss.plugin.simulated.*; import org.lockss.test.*; import org.lockss.util.CIProperties; import org.lockss.util.Constants; import org.lockss.util.ListUtil; public class TestAPSDrupalArticleIteratorFactory extends ArticleIteratorTestCase { private SimulatedArchivalUnit sau; // Simulated AU to generate content private final String PLUGIN_NAME = "org.lockss.plugin.highwire.aps.APSDrupalPlugin"; static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey(); static final String VOLUME_NAME_KEY = ConfigParamDescr.VOLUME_NAME.getKey(); private final String BASE_URL = "http://ajpendo.physiology.org/"; private final Configuration AU_CONFIG = ConfigurationUtil.fromArgs( BASE_URL_KEY, BASE_URL, VOLUME_NAME_KEY, "1"); private String BASE_AU_URL = BASE_URL + "content/1/"; private static final int DEFAULT_FILESIZE = 3000; private final String ARTICLE_FAIL_MSG = "Article files not created properly"; protected String cuRole = null; ArticleMetadataExtractor.Emitter emitter; protected boolean emitDefaultIfNone = false; FileMetadataExtractor me = null; MetadataTarget target; @Override public void setUp() throws Exception { super.setUp(); String tempDirPath = setUpDiskSpace(); au = createAu(); sau = PluginTestUtil.createAndStartSimAu(simAuConfig(tempDirPath)); } @Override public void tearDown() throws Exception { sau.deleteContentTree(); super.tearDown(); } protected ArchivalUnit createAu() throws ArchivalUnit.ConfigurationException { return PluginTestUtil.createAndStartAu(PLUGIN_NAME, AU_CONFIG); } Configuration simAuConfig(String rootPath) { Configuration conf = ConfigManager.newConfiguration(); conf.put("root", rootPath); conf.put(BASE_URL_KEY, BASE_URL); conf.put(VOLUME_NAME_KEY, "1"); conf.put("depth", "1"); conf.put("branch", "1"); conf.put("numFiles", "7"); conf.put("fileTypes", "" + (SimulatedContentGenerator.FILE_TYPE_PDF | SimulatedContentGenerator.FILE_TYPE_HTML)); conf.put("binFileSize", "" + DEFAULT_FILESIZE); return conf; } public void testRoots() throws Exception { SubTreeArticleIterator artIter = createSubTreeIter(); assertEquals(ListUtil.list(BASE_AU_URL), getRootUrls(artIter)); } // We are set up to match any of "<base_url>content/<vol>/<iss>/<pg>.full(.pdf)" public void testUrls() throws Exception { SubTreeArticleIterator artIter = createSubTreeIter(); Pattern pat = getPattern(artIter); assertMatchesRE(pat, "http://ajpendo.physiology.org/content/1/1/1"); // but not to ... assertNotMatchesRE(pat, "http://ajpendo.physiology.org/content/1/1"); assertNotMatchesRE(pat, "http://ajpendo.physiology.org/content/ajpendo/1/1"); assertNotMatchesRE(pat, "http://ajpendo.physiology.org/content/ajpendo/1/1/1"); assertNotMatchesRE(pat, "http://ajpendo.physiology.org/content/1/1/1.full"); assertNotMatchesRE(pat, "http://ajpendo.physiology.org/content/1/1/1.full.pdf"); assertNotMatchesRE(pat, "http://ajpendo.physiology.org/content/1/1/1.full.pdf+html"); assertNotMatchesRE(pat, "http://ajpendo.physiology.org/content/1/1/1.abstract"); assertNotMatchesRE(pat, "http://ajpendo.physiology.org/content/1/1/1.long"); assertNotMatchesRE(pat, "http://ajpendo.physiology.org/email?gca=bjophthalmol;96/1/1&current-view-path=/content/96/1/1.extract"); // wrong base url assertNotMatchesRE(pat, "http://ametsoc.org/bitstream/handle/foobar"); } // simAU was created with only one depth // 1 filetype (html) and 2 files of each type // So the total number of files of all types is 2 // simAU file structures looks like this branch01/01file.html public void testCreateArticleFiles() throws Exception { PluginTestUtil.crawlSimAu(sau); /* * Go through the simulated content you just crawled and modify the results to emulate * what you would find in a "real" crawl with APSDrupal: * <base_url>content/<vol>/<iss>/pg.full */ String pat0 = "(?!branch)00([2-6])file[.]html"; // turn xxfile.html into body String rep0 = "/content/1/1/C$1"; String rep0e = "/content/ajpendo/1/1/C$1"; PluginTestUtil.copyAu(sau, au, ".*[.]html$", pat0, rep0); PluginTestUtil.copyAu(sau, au, ".*[.]html$", pat0, rep0e); String pat1 = "branch(\\d+)/\\d+([1356])file[.]html"; String rep1 = "/content/1/$1/C$2.full.pdf+html"; PluginTestUtil.copyAu(sau, au, ".*[.]html$", pat1, rep1); String pat2 = "branch(\\d+)/\\d+([237])file[.]pdf"; String rep2 = "/content/1/$1/C$2.full.pdf"; String rep2e = "/content/ajpendo/1/$1/C$2.full.pdf"; PluginTestUtil.copyAu(sau, au, ".*[.]pdf$", pat2, rep2); PluginTestUtil.copyAu(sau, au, ".*[.]pdf$", pat2, rep2e); Iterator<ArticleFiles> it = au.getArticleIterator(MetadataTarget.Any()); int count = 0; int countFullText= 0; int countMetadata = 0; int countPdf = 0; int countPdfLanding = 0; while (it.hasNext()) { ArticleFiles af = it.next(); count ++; //log.info(af.toString()); CachedUrl cu = af.getFullTextCu(); if ( cu != null) { ++countFullText; } cu = af.getRoleCu(ArticleFiles.ROLE_ARTICLE_METADATA); if (cu != null) { ++countMetadata; } cu = af.getRoleCu(ArticleFiles.ROLE_FULL_TEXT_PDF); if (cu != null) { ++countPdf; } cu = af.getRoleCu(ArticleFiles.ROLE_FULL_TEXT_PDF_LANDING_PAGE); if (cu != null) { ++countPdfLanding; } } // potential article count is 7 (1 branch * 7 files each branch) // less the pdf only and pdf landing only int expCount = 5; log.debug3("Article count is " + count); assertEquals(expCount, count); // you will get full text for ALL articles assertEquals(expCount, countFullText); // you will get metadata for all but 2 assertEquals(expCount, countMetadata); // no metadata for pdf only // you will get pdf for 2 (3 - 1 non-base article) assertEquals(2, countPdf); // you will get landing for 3 (4 - 1 non-base article) assertEquals(3, countPdfLanding); } public void testCreateArticleFiles2() throws Exception { PluginTestUtil.crawlSimAu(sau); String[] urls = { BASE_URL + "content/1/1/C1.full", BASE_URL + "content/1/1/C1.full.pdf", BASE_URL + "content/1/1/C1.full.pdf+html", BASE_URL + "content/1/1/C1", BASE_URL + "content/1/1/C1.article-info", BASE_URL + "content/1/1/C1.figures-only", BASE_URL + "content/1/1/C10.full.pdf", BASE_URL + "content/1/1/C10.full.pdf+html", BASE_URL + "content/1/1/C10", BASE_URL + "content/1/1/C10.article-info", BASE_URL + "content/1/1/C100.full.pdf+html", BASE_URL + "content/1/1/C100", BASE_URL + "content/1/1/C3", BASE_URL + "content/1/1/C3.article-info", BASE_URL + "content/1/1/C4.full.pdf", BASE_URL + "content/1/1/C4", BASE_URL + "content/1/1/C18.article-info", BASE_URL + "content/1/1/C19.figures-only", BASE_URL, BASE_URL + "content" }; CachedUrl cuPdf = null; CachedUrl cuHtml = null; for (CachedUrl cu : AuUtil.getCuIterable(sau)) { if (cuPdf == null && cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_PDF)) { cuPdf = cu; } else if (cuHtml == null && cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_HTML)) { cuHtml = cu; } if (cuPdf != null && cuHtml != null) { break; } } for (String url : urls) { InputStream input = null; CIProperties props = null; if (url.contains("pdf+html")) { input = cuHtml.getUnfilteredInputStream(); props = cuHtml.getProperties(); } else if (url.contains("pdf")) { input = cuPdf.getUnfilteredInputStream(); props = cuPdf.getProperties(); } else { input = cuHtml.getUnfilteredInputStream(); props = cuHtml.getProperties(); } UrlData ud = new UrlData(input, props, url); UrlCacher uc = au.makeUrlCacher(ud); uc.storeContent(); } Stack<String[]> expStack = new Stack<String[]>(); String [] af1 = { BASE_URL + "content/1/1/C1.full", BASE_URL + "content/1/1/C1.full.pdf+html", BASE_URL + "content/1/1/C1.full.pdf", BASE_URL + "content/1/1/C1.full.pdf+html"}; String [] af2 = { BASE_URL + "content/1/1/C10", BASE_URL + "content/1/1/C10.full.pdf+html", BASE_URL + "content/1/1/C10.full.pdf", BASE_URL + "content/1/1/C10.full.pdf+html"}; String [] af3 = { BASE_URL + "content/1/1/C100", BASE_URL + "content/1/1/C100.full.pdf+html", null, BASE_URL + "content/1/1/C100.full.pdf+html"}; String [] af4 = { BASE_URL + "content/1/1/C3", null, null, BASE_URL + "content/1/1/C3"}; String [] af5 = { BASE_URL + "content/1/1/C4", null, BASE_URL + "content/1/1/C4.full.pdf", BASE_URL + "content/1/1/C4"}; String [] af6 = { null, null, null, null}; expStack.push(af6); expStack.push(af5); expStack.push(af4); expStack.push(af3); expStack.push(af2); expStack.push(af1); String[] exp; for ( SubTreeArticleIterator artIter = createSubTreeIter(); artIter.hasNext(); ) { // the article iterator return aspects with html first, then pdf, then nothing ArticleFiles af = artIter.next(); String[] act = { af.getFullTextUrl(), af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF_LANDING_PAGE), af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF), af.getRoleUrl(ArticleFiles.ROLE_ARTICLE_METADATA) }; System.err.println(" "); exp = expStack.pop(); if(act.length == exp.length){ for(int i = 0;i< act.length; i++){ System.err.println(" Expected: " + exp[i] + "\n Actual: " + act[i]); assertEquals(ARTICLE_FAIL_MSG + " Expected: " + exp[i] + "\n Actual: " + act[i], exp[i],act[i]); } } else fail(ARTICLE_FAIL_MSG + " length of expected and actual ArticleFiles content not the same:" + exp.length + "!=" + act.length); } exp = expStack.pop(); assertEquals("Did not find null end marker", exp, af6); } }
package com.opengamma.financial.security.option; /** * The FX barrier option sampling frequency. */ public enum SamplingFrequency { /** * Daily close. */ DAILY_CLOSE, /** * Friday. */ FRIDAY, /** * Weekly close. */ WEEKLY_CLOSE, /** * Continuous (for continuous monitoring) */ CONTINUOUS }
package org.testeditor.fixture.swt; import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.widgetOfType; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.lang.reflect.Method; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Widget; import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot; import org.eclipse.swtbot.eclipse.finder.waits.Conditions; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEclipseEditor; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.finders.ContextMenuHelper; import org.eclipse.swtbot.swt.finder.utils.SWTBotPreferences; import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton; import org.eclipse.swtbot.swt.finder.widgets.SWTBotCheckBox; import org.eclipse.swtbot.swt.finder.widgets.SWTBotCombo; import org.eclipse.swtbot.swt.finder.widgets.SWTBotList; import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu; import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell; import org.eclipse.swtbot.swt.finder.widgets.SWTBotText; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem; import org.eclipse.swtbot.swt.finder.widgets.TimeoutException; import org.testeditor.fixture.core.interaction.FixtureMethod; /** * Fixture to control SWT elements in an RCP Application. * */ public class SWTFixture { private Logger logger = LogManager.getLogger(SWTFixture.class); private SWTWorkbenchBot bot = new SWTWorkbenchBot(); public SWTFixture() { System.setProperty("org.eclipse.swtbot.search.timeout", "10000"); System.setProperty("org.eclipse.swtbot.playback.poll.delay", "10000"); } /** * Method for debugging the AUT. A first implementation of an widget * scanner. all widget s on current SWT-App will be printed with their id's * in the swtbot.log with the trace-level. This Method is in work and can be * extended and modified step by step. * */ @FixtureMethod public void reportWidgets() { logger.info("analyzeWidgets start"); logger.info(" getDisplay().syncExec(new Runnable() { @Override public void run() { List<? extends Widget> widgets = bot.widgets(widgetOfType(Widget.class)); StringBuilder sb = new StringBuilder(); for (Widget widget : widgets) { if (widget instanceof Table) { sb.append("\n >>> Table gefunden mit " + ((Table) widget).getItems().length + " Zeilen !"); } sb.append("widgetId: " + widget.getData("org.eclipse.swtbot.widget.key")); sb.append(" widgetClass: " + widget.getClass().getSimpleName()); try { Method[] methods = widget.getClass().getMethods(); boolean foundGetText = false; for (Method method : methods) { if (method.getName().equals("getText")) { foundGetText = true; } } if (foundGetText) { Method method = widget.getClass().getMethod("getText", new Class[] {}); sb.append("\n >>> text value: " + method.invoke(widget, new Object[] {})); } } catch (Exception e) { logger.error("No text", e); } sb.append(" widget: " + widget).append("\n"); } logger.info(sb.toString()); } }); logger.info("analyzeWidgets end"); logger.info(" } /** * * @return a SWT Display object. */ protected Display getDisplay() { return Display.getDefault(); } /** * Wait Step to inteerupt the test execution for a defined time. * * @param seconds * to wait until continue test. * @throws InterruptedException * on test abort. */ @FixtureMethod public void wait(int seconds) throws InterruptedException { logger.info("Waiting for {} seconds.", seconds); Thread.sleep(seconds * 1000); } /** * Waits for a dialog with a given title to show up. * * @param title * the title of the dialog */ @FixtureMethod public void waitForDialogClosing(String title) { long swtBotDefaultInMilliSeconds = SWTBotPreferences.TIMEOUT; waitForDialogClosingWithTimeout(title, swtBotDefaultInMilliSeconds / 1000); } /** * Waits for a dialog with a given title to show up. * * @param title * the title of the dialog * @param timeout * the time to wait */ @FixtureMethod public void waitForDialogClosingWithTimeout(String title, long timeout) { logger.info("Waiting for dialog with title='{}' to open, timeout='{}' seconds.", title, timeout); try { try { bot.waitUntil(Conditions.shellIsActive(title), 3000); SWTBotShell shell = bot.shell(title); bot.waitUntil(Conditions.shellCloses(shell), timeout * 1000); } catch (TimeoutException e) { logger.info("Dialog with title {} was not found. Test continuous.", title); } } catch (WidgetNotFoundException e) { logger.info("Widget not found. No reason to wait."); } logger.info("Finished waiting."); } /** * Checks that a view in the RCP is active. * * @param locator * to locator of the view to be looked up. * @param locatorStrategy * the strategy that shall be applied * @return true if the vie is visible */ @FixtureMethod public boolean isViewVisible(String locator, ViewLocatorStrategy locatorStrategy) { SWTBotView view = getView(locator, locatorStrategy); return view.isActive(); } private SWTBotView getView(String locator, ViewLocatorStrategy locatorStrategy) { switch (locatorStrategy) { case ID: logger.debug("Searching for view with id='{}'.", locator); return bot.viewById(locator); case PARTNAME: logger.debug("Searching for view with partName='{}'.", locator); return bot.viewByPartName(locator); case TITLE: logger.debug("Searching for view with title='{}'.", locator); return bot.viewByTitle(locator); default: throw new IllegalArgumentException("Unknown locator strategy: " + locatorStrategy); } } /** * Selects an element in a tree. It takes a path string end tries to expand * the tree along the path. The node of the path is selectd. * * @param locator * of the tree. * @param itemName * path to the item to be selectd. Example: * "Root/SubNode/FinalNode" */ @FixtureMethod public void selectElementInTreeView(String itemName, String locator, SWTLocatorStrategy locatorStrategy) { logger.trace("search for view with title: {} to get the default tree", locator); SWTBotTree tree = getTree(locator, locatorStrategy); logger.trace("Open item with path: {}", itemName); try { SWTBotTreeItem expandNode = tree.expandNode(itemName.split("/")); expandNode.select(); } catch (WidgetNotFoundException e) { logger.error("Widget not found", e); printTreeItems(tree, locator); throw e; } } private SWTBotTree getTree(String locator, SWTLocatorStrategy locatorStrategy) { switch (locatorStrategy) { case ID: return bot.viewById(locator).bot().tree(); case LABEL: return bot.viewByTitle(locator).bot().tree(); case SINGLE: return bot.tree(); } throw new IllegalArgumentException("Unkown locatorStrategy: " + locatorStrategy); } private void printTreeItems(SWTBotTree tree, String locator) { logger.info("Printing all items of tree with locator='{}'.", locator); printTreeItems(tree.getAllItems(), 0); } private void printTreeItems(SWTBotTreeItem[] items, int level) { String spaces = StringUtils.repeat(" ", 4 * level); for (SWTBotTreeItem item : items) { logger.info("{}|-- {}", spaces, item.getText()); if (!item.isExpanded()) { item.expand(); } printTreeItems(item.getItems(), level + 1); } } @FixtureMethod public void selectElementInList(String itemName, String locator, SWTLocatorStrategy locatorStrategy) { logger.trace("search for list with {}", locator); SWTBotList list = getList(locator, locatorStrategy); list.select(itemName); } private SWTBotList getList(String locator, SWTLocatorStrategy locatorStrategy) { switch (locatorStrategy) { case ID: return bot.listWithId(locator); case LABEL: return bot.listWithLabel(locator); case SINGLE: return bot.list(); } throw new IllegalArgumentException("Unkown locatorStrategy: " + locatorStrategy); } @FixtureMethod public void selectElementInCombobox(String value, String locator, SWTLocatorStrategy locatorStrategy) { logger.trace("search for dropdown with {}", locator); SWTBotCombo comboBox = getComboBox(locator, locatorStrategy); comboBox.setText(value); } private SWTBotCombo getComboBox(String locator, SWTLocatorStrategy locatorStrategy) { switch (locatorStrategy) { case ID: return bot.comboBoxWithId(locator); case LABEL: return bot.comboBoxWithLabel(locator); case SINGLE: return bot.comboBox(); } throw new IllegalArgumentException("Unkown locatorStrategy: " + locatorStrategy); } /** * Opens the context Menu of a widget and executes the menuitem described as * a path. * * @param viewName * id of the view / widget with the context menu * @param menuItem * poath to the menuitem Example: "New/Project" * @throws Exception * on failure to break the test. */ @FixtureMethod public void executeContextMenuEntry(String menuItem, String viewName, SWTLocatorStrategy locatorStrategy) throws Exception { logger.trace("Search for view with title: {}", viewName); SWTBotTree tree = getTree(viewName, locatorStrategy); assertNotNull(tree); MenuItem item = ContextMenuHelper.contextMenu(tree, menuItem.split("/")); assertNotNull(item); logger.trace("Click on menu item: {}", menuItem); new SWTBotMenu(item).click(); } /** * Looking for a widget in that is typeable and is identifiable by the * locator. * * @param locator * of the widget. * @param value * set to the widget. * @param locatorStrategy * strategy to lookup the widget. */ @FixtureMethod public void typeInto(String value, String locator, SWTLocatorStrategy locatorStrategy) { logger.trace("search for text with title: {}", locator); SWTBotText text = getText(locator, locatorStrategy); text.setText(value); } private SWTBotText getText(String locator, SWTLocatorStrategy locatorStrategy) { switch (locatorStrategy) { case ID: return bot.textWithId(locator); case LABEL: return bot.textWithLabel(locator); case SINGLE: return bot.text(); } throw new IllegalArgumentException("Unkown locatorStrategy: " + locatorStrategy); } /** * Clicks on a button. * * @param locator * to identify the button. */ @FixtureMethod public void clickOn(String locator, SWTLocatorStrategy locatorStrategy) { logger.trace("search for button with: {}", locator); try { SWTBotButton button = getButton(locator, locatorStrategy); button.click(); } catch (WidgetNotFoundException e) { logger.info(e.getLocalizedMessage(), e); this.reportWidgets(); fail(); } } private SWTBotButton getButton(String locator, SWTLocatorStrategy locatorStrategy) { switch (locatorStrategy) { case ID: return bot.buttonWithId(locator); case LABEL: return bot.button(locator); case SINGLE: return bot.button(); } throw new IllegalArgumentException("Unkown locatorStrategy: " + locatorStrategy); } /** * Checks an SWT checkbox. * * @param locator * to identify the checkbox * @param locatorStrategy * the strategy to use */ @FixtureMethod public void check(String locator, SWTLocatorStrategy locatorStrategy) { SWTBotCheckBox checkBox = getCheckBox(locator, locatorStrategy); checkBox.select(); } /** * Unchecks an SWT checkbox. * * @param locator * to identify the checkbox * @param locatorStrategy * the strategy to use */ @FixtureMethod public void uncheck(String locator, SWTLocatorStrategy locatorStrategy) { SWTBotCheckBox checkBox = getCheckBox(locator, locatorStrategy); checkBox.deselect(); } // TODO would be nicer to use the generic withId(...) but we need Harmcrest // on the classpath for that public SWTBotCheckBox getCheckBox(String locator, SWTLocatorStrategy locatorStrategy) { switch (locatorStrategy) { case ID: return bot.checkBoxWithId(locator); case LABEL: return bot.checkBoxWithLabel(locator); case SINGLE: return bot.checkBox(locator); } throw new IllegalArgumentException("Unkown locatorStrategy: " + locatorStrategy); } @FixtureMethod public String containsActiveTextEditorContent(String searchString) { SWTBotEditor activeEditor = bot.activeEditor(); logger.info("Check if the current active editor {} contains {}", activeEditor.getTitle(), searchString); return Boolean.toString(activeEditor.toTextEditor().getText().contains(searchString)); } @FixtureMethod public void removeLineFromEditor(int lineNumber) { SWTBotEditor activeEditor = bot.activeEditor(); logger.info("Removing line {} from editor {}.", lineNumber, activeEditor.getTitle()); SWTBotEclipseEditor textEditor = activeEditor.toTextEditor(); textEditor.selectLine(lineNumber - 1); textEditor.typeText(" "); } @FixtureMethod public void saveActiveEditor() { SWTBotEditor activeEditor = bot.activeEditor(); logger.info("Save editor {}", activeEditor.getTitle()); activeEditor.toTextEditor().save(); } }
package polyglot.ext.jl5.ast; import java.util.LinkedHashSet; import java.util.Set; import polyglot.ast.Node; import polyglot.ext.jl5.types.IntersectionType; import polyglot.ext.jl5.types.JL5Context; import polyglot.ext.jl5.types.JL5ParsedClassType; import polyglot.ext.jl5.types.JL5SubstClassType; import polyglot.ext.jl5.types.JL5TypeSystem; import polyglot.ext.jl5.types.RawClass; import polyglot.ext.jl5.types.TypeVariable; import polyglot.ext.jl5.types.WildCardType; import polyglot.frontend.MissingDependencyException; import polyglot.frontend.Scheduler; import polyglot.frontend.goals.Goal; import polyglot.types.ArrayType; import polyglot.types.ClassType; import polyglot.types.ReferenceType; import polyglot.types.SemanticException; import polyglot.types.Type; import polyglot.util.Position; import polyglot.util.SerialVersionUID; import polyglot.visit.TypeChecker; public class JL5CanonicalTypeNode_c extends polyglot.ast.CanonicalTypeNode_c { private static final long serialVersionUID = SerialVersionUID.generate(); public JL5CanonicalTypeNode_c(Position pos, Type type) { super(pos, makeRawIfNeeded(type, pos)); } private static Type makeRawIfNeeded(Type type, Position pos) { if (type.isClass()) { JL5TypeSystem ts = (JL5TypeSystem) type.typeSystem(); if (type instanceof JL5ParsedClassType && !((JL5ParsedClassType) type).typeVariables().isEmpty()) { // needs to be a raw type return ts.rawClass((JL5ParsedClassType) type, pos); } if (type.toClass().isInnerClass()) { ClassType t = type.toClass(); ClassType outer = type.toClass().outer(); while (t.isInnerClass() && outer != null) { if (outer instanceof RawClass) { // an inner class of a raw class should be a raw class. return ts.erasureType(type); } t = outer; outer = outer.outer(); } } } return type; } @Override public Node typeCheck(TypeChecker tc) throws SemanticException { Type t = this.type(); if (t instanceof JL5SubstClassType) { JL5SubstClassType st = (JL5SubstClassType) t; JL5TypeSystem ts = (JL5TypeSystem) tc.typeSystem(); // Check for rare types: e.g., Outer<String>.Inner, where Inner has uninstantiated type variables // See JLS 3rd ed. 4.8 if (st.isInnerClass() && !st.base().typeVariables().isEmpty()) { // st is an inner class, with type variables. Make sure that // these type variables are acutally instantiated for (TypeVariable tv : st.base().typeVariables()) { if (!st.subst().substitutions().keySet().contains(tv)) { throw new SemanticException("\"Rare\" types are not allowed: cannot " + "use raw class " + st.name() + " when the outer class " + st.outer() + " has instantiated type variables.", position); } } } if (!st.base().typeVariables().isEmpty()) { // check that arguments obey their bounds. //first we must perform capture conversion. see beginning of JLS 4.5 JL5SubstClassType capCT = (JL5SubstClassType) ts.applyCaptureConversion(st, this.position); for (int i = 0; i < capCT.actuals().size(); i++) { TypeVariable ai = capCT.base().typeVariables().get(i); Type xi = capCT.actuals().get(i); if (!ai.upperBound().isCanonical()) { // need to disambiguate Scheduler scheduler = tc.job().extensionInfo().scheduler(); Goal g = scheduler.SupertypesResolved(st.base()); throw new MissingDependencyException(g); } //require that arguments obey their bounds if (!ts.isSubtype(xi, capCT.subst().substType(ai.upperBound()))) { throw new SemanticException("Type argument " + st.actuals().get(i) + " is not a subtype of its declared bound " + ai.upperBound(), position()); } } } } // check for uses of type variables in static contexts if (tc.context().inStaticContext() && !((JL5Context) tc.context()).inCTORCall()) { for (TypeVariable tv : findInstanceTypeVariables(t)) { throw new SemanticException("Type variable " + tv + " cannot be used in a static context", this.position); } } ClassType currentClass = tc.context().currentClass(); JL5Context jc = (JL5Context) tc.context(); if (jc.inExtendsClause()) { currentClass = jc.extendsClauseDeclaringClass(); } if (currentClass != null) { if (currentClass.isNested() && !currentClass.isInnerClass()) { // the current class is static. for (TypeVariable tv : findInstanceTypeVariables(t)) { if (!tv.declaringClass().equals(currentClass)) { throw new SemanticException("Type variable " + tv + " of class " + tv.declaringClass() + " cannot be used in a nested class", this.position); } } } } return super.typeCheck(tc); } private Set<TypeVariable> findInstanceTypeVariables(Type t) { Set<TypeVariable> s = new LinkedHashSet<TypeVariable>(); findInstanceTypeVariables(t, s); return s; } private void findInstanceTypeVariables(Type t, Set<TypeVariable> tvs) { if (t instanceof TypeVariable) { TypeVariable tv = (TypeVariable) t; if (tv.declaredIn() == TypeVariable.TVarDecl.CLASS_TYPE_VARIABLE) { tvs.add(tv); } } if (t instanceof ArrayType) { ArrayType at = (ArrayType) t; findInstanceTypeVariables(at.base(), tvs); } if (t instanceof WildCardType) { WildCardType at = (WildCardType) t; findInstanceTypeVariables(at.upperBound(), tvs); } if (t instanceof JL5SubstClassType) { JL5SubstClassType ct = (JL5SubstClassType) t; for (ReferenceType at : ct.actuals()) { findInstanceTypeVariables(at, tvs); } } if (t instanceof IntersectionType) { IntersectionType it = (IntersectionType) t; for (Type at : it.bounds()) { findInstanceTypeVariables(at, tvs); } } if (t.isClass() && t.toClass().isNested()) { findInstanceTypeVariables(t.toClass().outer(), tvs); } } }
package polyglot.types; import polyglot.frontend.*; import polyglot.frontend.goals.*; import polyglot.types.*; import polyglot.util.InternalCompilerError; import java.util.Iterator; /** * A LazyClassInitializer is responsible for initializing members of a class * after it has been created. Members are initialized lazily to correctly handle * cyclic dependencies between classes. */ public class DeserializedClassInitializer implements LazyClassInitializer { protected TypeSystem ts; protected ParsedClassType ct; protected boolean init; public DeserializedClassInitializer(TypeSystem ts) { this.ts = ts; } public void setClass(ParsedClassType ct) { this.ct = ct; } public boolean fromClassFile() { return false; } public void initTypeObject() { if (this.init) return; if (ct.isMember() && ct.outer() instanceof ParsedClassType) { ParsedClassType outer = (ParsedClassType) ct.outer(); outer.addMemberClass(ct); } for (Iterator i = ct.memberClasses().iterator(); i.hasNext(); ) { ParsedClassType ct = (ParsedClassType) i.next(); ct.initializer().initTypeObject(); } this.init = true; } public boolean isTypeObjectInitialized() { return this.init; } public void initSuperclass() { } public void initInterfaces() { } public void initMemberClasses() { } public void initConstructors() { } public void initMethods() { } public void initFields() { } public void canonicalConstructors() { } public void canonicalMethods() { } public void canonicalFields() { } }
package org.kie.guvnor.jcr2vfsmigration.migrater.asset; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import org.drools.guvnor.client.common.AssetFormats; import org.drools.guvnor.client.rpc.Asset; import org.drools.guvnor.client.rpc.Module; import org.drools.guvnor.server.RepositoryAssetService; import org.drools.guvnor.server.contenthandler.drools.FactModelContentHandler; import org.drools.repository.AssetItem; import org.kie.commons.io.IOService; import org.kie.commons.java.nio.base.options.CommentedOption; import org.kie.commons.java.nio.file.NoSuchFileException; import org.kie.guvnor.factmodel.service.FactModelService; import org.kie.guvnor.jcr2vfsmigration.migrater.util.MigrationPathManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.uberfire.backend.server.util.Paths; import org.uberfire.backend.vfs.Path; import com.google.gwt.user.client.rpc.SerializationException; @ApplicationScoped public class FactModelsMigrater { protected static final Logger logger = LoggerFactory.getLogger(FactModelsMigrater.class); @Inject protected RepositoryAssetService jcrRepositoryAssetService; @Inject protected FactModelService vfsFactModelService; @Inject protected MigrationPathManager migrationPathManager; @Inject @Named("ioStrategy") private IOService ioService; @Inject private Paths paths; public void migrate(Module jcrModule, AssetItem jcrAssetItem) { if (!AssetFormats.DRL_MODEL.equals(jcrAssetItem.getFormat())) { throw new IllegalArgumentException("The jcrAsset (" + jcrAssetItem.getName() + ") has the wrong format (" + jcrAssetItem.getFormat() + ")."); } Path path = migrationPathManager.generatePathForAsset(jcrModule, jcrAssetItem); final org.kie.commons.java.nio.file.Path nioPath = paths.convert( path ); Map<String, Object> attrs; try { attrs = ioService.readAttributes( nioPath ); } catch ( final NoSuchFileException ex ) { attrs = new HashMap<String, Object>(); } FactModelContentHandler h = new FactModelContentHandler(); StringBuilder stringBuilder = new StringBuilder(); try { Asset jcrAsset = jcrRepositoryAssetService.loadRuleAsset(jcrAssetItem.getUUID()); h.assembleSource(jcrAsset.getContent(), stringBuilder); ioService.write( nioPath, stringBuilder.toString(), attrs, new CommentedOption(jcrAssetItem.getLastContributor(), null, jcrAssetItem.getCheckinComment(), jcrAssetItem.getLastModified().getTime() )); } catch (SerializationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package org.ossmeter.platform.vcs.workingcopy.manager; import java.io.File; import java.util.Map; import org.apache.log4j.Logger; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.ossmeter.platform.logging.OssmeterLoggerFactory; import org.ossmeter.platform.util.ExtensionPointHelper; import org.ossmeter.repository.model.Project; import org.ossmeter.repository.model.VcsRepository; public class WorkingCopyFactory { private static final String WORKING_COPY_DIRECTORY = "workingCopies"; private static final String MODEL_DIRECTORY = "workingModels"; private static final Logger LOGGER = new OssmeterLoggerFactory().makeNewLoggerInstance("workingCopyManagerFactory"); private static class InstanceKeeper { public static WorkingCopyFactory instance = new WorkingCopyFactory(); } public static WorkingCopyFactory getInstance() { return InstanceKeeper.instance; } private WorkingCopyManager getWorkingCopyCreator(VcsRepository repository) throws WorkingCopyManagerUnavailable { for (IConfigurationElement confElement : ExtensionPointHelper.getConfigurationElementsForExtensionPoint("org.ossmeter.vcs.workingcopymanager")) { try { WorkingCopyManager c = (WorkingCopyManager) confElement.createExecutableExtension("manager"); if (c.appliesTo(repository)) { return c; } } catch (CoreException e) { // TODO: this logger throws null pointer exceptions // LOGGER.error("exception while searching for a working copy creator", e); e.printStackTrace(); } } throw new WorkingCopyManagerUnavailable(repository); } /** * Checks out a project at a certain revision. After this call for all repositories * associated with the current project a proper working copy will have been created. * * This method returns references to directories where the working copies reside. * The intention is to have clients never write in these directories such that the * working copies remain clean and such that the working copy managers may provide * efficient incremental updating without chance of merge conflicts. * * To store temporary data (models) associated with the working copies, this checkout * method also generates an empty folder for every repository of the project where * stuff can freely be written. * * @param project for which to check out all repositories * @param revision the revision of the project * @param workingCopyFolders a map where the keys are repository urls and the * values are working copy folders. Try to keep these folders clean. * @param scratchFolders a map where the keys are repository urls and the values * are folder for storing additional (model) data * @throws WorkingCopyManagerUnavailable if there is no registered means for creating a working copy for a certain VcsRepository. * @throws WorkingCopyCheckoutException when a working copy manager generates an exception while producing the working copy. */ public void checkout(Project project, String revision, Map<String,File> workingCopyFolders, Map<String,File> scratchFolders) throws WorkingCopyManagerUnavailable, WorkingCopyCheckoutException { File storage = new File(project.getStorage().getPath()); File wc = new File(storage, WORKING_COPY_DIRECTORY); File md = new File(storage, MODEL_DIRECTORY); if (!wc.exists()) { wc.mkdirs(); } for (VcsRepository repo : project.getVcsRepositories()) { WorkingCopyManager manager = getWorkingCopyCreator(repo); String sub = encode(repo.getUrl()); File checkout = new File(wc, sub); manager.checkout(checkout, repo, revision); workingCopyFolders.put(repo.getUrl(), checkout); File model = new File(md, sub); if (!model.exists()) { model.mkdirs(); } scratchFolders.put(repo.getUrl() , model); } } private String encode(String url) { StringBuilder b = new StringBuilder(); for (char ch : url.toCharArray()) { if (Character.isLetterOrDigit(ch)) { b.append(ch); } else { b.append(String.format("_%x_", (int) ch)); } } return b.toString(); } }
package io.getlime.security.powerauth.rest.api.base.encryption; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.BaseEncoding; import io.getlime.security.powerauth.crypto.lib.encryptor.NonPersonalizedEncryptor; import io.getlime.security.powerauth.crypto.lib.encryptor.model.NonPersonalizedEncryptedMessage; import io.getlime.security.powerauth.rest.api.model.base.PowerAuthApiRequest; import io.getlime.security.powerauth.rest.api.model.base.PowerAuthApiResponse; import io.getlime.security.powerauth.rest.api.model.entity.NonPersonalizedEncryptedPayloadModel; import java.io.IOException; /** * @author Petr Dvorak, petr@lime-company.eu */ public class PowerAuthNonPersonalizedEncryptor { private NonPersonalizedEncryptor encryptor; ObjectMapper mapper = new ObjectMapper(); public PowerAuthNonPersonalizedEncryptor(String applicationKeyBase64, String sessionKeyBytesBase64, String sessionIndexBase64, String ephemeralPublicKeyBase64) { byte[] applicationKey = BaseEncoding.base64().decode(applicationKeyBase64); byte[] sessionIndex = BaseEncoding.base64().decode(sessionIndexBase64); byte[] sessionKeyBytes = BaseEncoding.base64().decode(sessionKeyBytesBase64); byte[] ephemeralKeyBytes = BaseEncoding.base64().decode(ephemeralPublicKeyBase64); this.encryptor = new NonPersonalizedEncryptor(applicationKey, sessionKeyBytes, sessionIndex, ephemeralKeyBytes); } public PowerAuthApiResponse<NonPersonalizedEncryptedPayloadModel> encrypt(Object object) throws JsonProcessingException { if (object == null) { return null; } byte[] originalData = mapper.writeValueAsBytes(object); return this.encrypt(originalData); } public PowerAuthApiResponse<NonPersonalizedEncryptedPayloadModel> encrypt(byte[] originalData) { if (originalData == null) { return null; } NonPersonalizedEncryptedMessage message = encryptor.encrypt(originalData); if (message == null) { // this will happen only in case of an unlikely randomness error, or if keys are corrupted return null; } NonPersonalizedEncryptedPayloadModel responseObject = new NonPersonalizedEncryptedPayloadModel(); responseObject.setApplicationKey(BaseEncoding.base64().encode(message.getApplicationKey())); responseObject.setEphemeralPublicKey(BaseEncoding.base64().encode(message.getEphemeralPublicKey())); responseObject.setSessionIndex(BaseEncoding.base64().encode(message.getSessionIndex())); responseObject.setAdHocIndex(BaseEncoding.base64().encode(message.getAdHocIndex())); responseObject.setMacIndex(BaseEncoding.base64().encode(message.getMacIndex())); responseObject.setNonce(BaseEncoding.base64().encode(message.getNonce())); responseObject.setMac(BaseEncoding.base64().encode(message.getMac())); responseObject.setEncryptedData(BaseEncoding.base64().encode(message.getEncryptedData())); return new PowerAuthApiResponse<>( PowerAuthApiResponse.Status.OK, PowerAuthApiResponse.Encryption.NON_PERSONALIZED, responseObject ); } public byte[] decrypt(PowerAuthApiRequest<NonPersonalizedEncryptedPayloadModel> request) { if (request == null) { return null; } NonPersonalizedEncryptedPayloadModel requestObject = request.getRequestObject(); if (requestObject == null) { return null; } NonPersonalizedEncryptedMessage message = new NonPersonalizedEncryptedMessage(); message.setApplicationKey(BaseEncoding.base64().decode(requestObject.getApplicationKey())); message.setEphemeralPublicKey(BaseEncoding.base64().decode(requestObject.getEphemeralPublicKey())); message.setSessionIndex(BaseEncoding.base64().decode(requestObject.getSessionIndex())); message.setAdHocIndex(BaseEncoding.base64().decode(requestObject.getAdHocIndex())); message.setMacIndex(BaseEncoding.base64().decode(requestObject.getMacIndex())); message.setNonce(BaseEncoding.base64().decode(requestObject.getNonce())); message.setMac(BaseEncoding.base64().decode(requestObject.getMac())); message.setEncryptedData(BaseEncoding.base64().decode(requestObject.getEncryptedData())); return encryptor.decrypt(message); } public <T> T decrypt(PowerAuthApiRequest<NonPersonalizedEncryptedPayloadModel> request, Class<T> resultClass) throws IOException { byte[] result = this.decrypt(request); if (result == null) { return null; } return mapper.readValue(result, resultClass); } }
package org.xwiki.ircbot.internal; import java.util.Collections; import org.jmock.Expectations; import org.junit.Before; import org.junit.Test; import org.xwiki.bridge.DocumentAccessBridge; import org.xwiki.context.Execution; import org.xwiki.context.ExecutionContext; import org.xwiki.ircbot.IRCBot; import org.xwiki.ircbot.wiki.WikiIRCModel; import org.xwiki.model.ModelContext; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.model.reference.WikiReference; import org.xwiki.observation.EventListener; import org.xwiki.observation.ObservationManager; import org.xwiki.observation.internal.DefaultObservationManager; import org.xwiki.test.AbstractMockingComponentTestCase; import org.xwiki.test.annotation.ComponentList; import org.xwiki.test.annotation.MockingRequirement; import com.xpn.xwiki.internal.event.XARImportedEvent; import com.xpn.xwiki.internal.event.XARImportingEvent; import junit.framework.Assert; /** * Unit tests for {@link org.xwiki.ircbot.internal.XARImportEventListener}. * * @version $Id$ * @since 4.2M3 */ @ComponentList({ // Used to test our Event Listener in integration with the Observation Manager (see below) DefaultObservationManager.class }) @MockingRequirement(XARImportEventListener.class) public class XARImportEventListenerTest extends AbstractMockingComponentTestCase { private EventListener listener; private ObservationManager observationManager; @Before public void configure() throws Exception { this.listener = getComponentManager().getInstance(EventListener.class, "ircxarimport"); // In order for the test to be more complete we send the XAR events through the Observation Manager which // dispatches them to our Event Listener under test. This proves that our Listener is correctly registered as // an Event Listener. this.observationManager = getComponentManager().getInstance(ObservationManager.class); } @Test public void onEventWhenBotNotStarted() throws Exception { final IRCBot bot = getComponentManager().getInstance(IRCBot.class); getMockery().checking(new Expectations() {{ oneOf(bot).isConnected(); will(returnValue(false)); // The test is here, we verify that sendMessage is never called, i.e. that no message is sent to the IRC // channel. Note that this statement is not needed, it's just here to make the test more explicit. never(bot).sendMessage(with(any(String.class)), with(any(String.class))); }}); this.observationManager.notify(new XARImportingEvent(), null, null); } @Test public void onEventWhenXARImportStarted() throws Exception { final IRCBot bot = getComponentManager().getInstance(IRCBot.class); final EntityReferenceSerializer<String> serializer = getComponentManager().getInstance(EntityReferenceSerializer.TYPE_STRING); final DocumentReference userReference = new DocumentReference("userwiki", "userspace", "userpage"); final DocumentAccessBridge dab = getComponentManager().getInstance(DocumentAccessBridge.class); final ModelContext modelContext = getComponentManager().getInstance(ModelContext.class); // We simulate an EC without any XAR started information final Execution execution = getComponentManager().getInstance(Execution.class); final ExecutionContext ec = new ExecutionContext(); getMockery().checking(new Expectations() {{ oneOf(bot).isConnected(); will(returnValue(true)); oneOf(bot).getChannelsNames(); will(returnValue(Collections.singleton("channel"))); oneOf(execution).getContext(); will(returnValue(ec)); oneOf(serializer).serialize(userReference); will(returnValue("userwiki:userspace.userpage")); oneOf(dab).getCurrentUserReference(); will(returnValue(userReference)); oneOf(modelContext).getCurrentEntityReference(); will(returnValue(new WikiReference("somewiki"))); // The test is here! oneOf(bot).sendMessage("channel", "A XAR import has been started by userwiki:userspace.userpage in wiki somewiki"); }}); this.observationManager.notify(new XARImportingEvent(), null, null); // Also verify that the XAR import counter has been set to 0 in the EC Assert.assertEquals(0L, ec.getProperty(XARImportEventListener.XAR_IMPORT_COUNTER_KEY)); } @Test public void onEventWhenXARImportFinished() throws Exception { final IRCBot bot = getComponentManager().getInstance(IRCBot.class); final EntityReferenceSerializer<String> serializer = getComponentManager().getInstance(EntityReferenceSerializer.TYPE_STRING); final DocumentReference userReference = new DocumentReference("userwiki", "userspace", "userpage"); final DocumentAccessBridge dab = getComponentManager().getInstance(DocumentAccessBridge.class); final ModelContext modelContext = getComponentManager().getInstance(ModelContext.class); // We simulate an EC with some XAR started information (100 documents imported) final Execution execution = getComponentManager().getInstance(Execution.class); final ExecutionContext ec = new ExecutionContext(); ec.setProperty(XARImportEventListener.XAR_IMPORT_COUNTER_KEY, 100L); getMockery().checking(new Expectations() {{ oneOf(bot).isConnected(); will(returnValue(true)); oneOf(bot).getChannelsNames(); will(returnValue(Collections.singleton("channel"))); oneOf(execution).getContext(); will(returnValue(ec)); oneOf(serializer).serialize(userReference); will(returnValue("userwiki:userspace.userpage")); oneOf(dab).getCurrentUserReference(); will(returnValue(userReference)); oneOf(modelContext).getCurrentEntityReference(); will(returnValue(new WikiReference("somewiki"))); // The test is here! oneOf(bot).sendMessage("channel", "The XAR import started by userwiki:userspace.userpage " + "in wiki somewiki is now finished, 100 documents have been imported"); }}); this.observationManager.notify(new XARImportedEvent(), null, null); // Also verify that the XAR import counter has been removed Assert.assertNull(ec.getProperty(XARImportEventListener.XAR_IMPORT_COUNTER_KEY)); } }
package __TOP_LEVEL_PACKAGE__.__SEGMENT_PACKAGE__; import com.github.gwtbootstrap.client.ui.SimplePager.ImageButtonsConstants; public interface SimplePagerConstants extends ImageButtonsConstants { }
package org.deviceconnect.android.deviceplugin.alljoyn.profile; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import org.alljoyn.bus.BusException; import org.alljoyn.bus.Variant; import org.alljoyn.services.common.BusObjectDescription; import org.allseen.LSF.ControllerService.Lamp; import org.allseen.LSF.ControllerService.LampGroup; import org.allseen.LSF.LampDetails; import org.allseen.LSF.LampState; import org.allseen.LSF.ResponseCode; import org.deviceconnect.android.deviceplugin.alljoyn.AllJoynDeviceApplication; import org.deviceconnect.android.deviceplugin.alljoyn.AllJoynServiceEntity; import org.deviceconnect.android.deviceplugin.alljoyn.OneShotSessionHandler; import org.deviceconnect.android.deviceplugin.alljoyn.util.ColorUtil; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.profile.LightProfile; import org.deviceconnect.message.DConnectMessage; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * AllJoyn Light . * * @author NTT DOCOMO, INC. */ public class AllJoynLightProfile extends LightProfile { private final static int TRANSITION_PERIOD = 10; private enum LampServiceType { TYPE_SINGLE_LAMP, TYPE_LAMP_CONTROLLER, TYPE_UNKNOWN, } AllJoynDeviceApplication getApplication() { return (AllJoynDeviceApplication) getContext().getApplicationContext(); } @Override protected boolean onGetLight(Intent request, final Intent response, final String serviceId) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } final AllJoynDeviceApplication app = getApplication(); final AllJoynServiceEntity service = app.getDiscoveredAlljoynServices().get(serviceId); if (service == null) { MessageUtils.setNotFoundServiceError(response); return true; } switch (getLampServiceType(service)) { case TYPE_SINGLE_LAMP: { onGetLightForSingleLamp(request, response, service); return false; } case TYPE_LAMP_CONTROLLER: { onGetLightForLampController(request, response, service); return false; } case TYPE_UNKNOWN: default: { setUnsupportedError(response); return true; } } } private void onGetLightForSingleLamp(Intent request, final Intent response, final AllJoynServiceEntity service) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { LampState state = app.getInterface(busName, sessionId, LampState.class); List<Bundle> lights = new ArrayList<>(); if (state != null) { Bundle light = new Bundle(); try { light.putString(PARAM_LIGHT_ID, "self"); light.putString(PARAM_NAME, service.serviceName); light.putString(PARAM_CONFIG, ""); light.putBoolean(PARAM_ON, state.getOnOff()); lights.add(light); } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } } response.putExtra(PARAM_LIGHTS, lights.toArray(new Bundle[lights.size()])); setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } private void onGetLightForLampController(Intent request, final Intent response, final AllJoynServiceEntity service) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { Lamp lamp = app.getInterface(busName, sessionId, Lamp.class); List<Bundle> lights = new ArrayList<>(); if (lamp != null) { try { Lamp.GetAllLampIDs_return_value_uas lampIDsResponse = lamp.getAllLampIDs(); if (lampIDsResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to obtain lamp IDs."); getContext().sendBroadcast(response); return; } for (String lampId : lampIDsResponse.lampIDs) { Bundle light = new Bundle(); light.putString(PARAM_LIGHT_ID, lampId); Lamp.GetLampName_return_value_usss lampNameResponse = lamp.getLampName(lampId, service.defaultLanguage); if (lampNameResponse.responseCode != ResponseCode.OK.getValue()) { Log.w(AllJoynLightProfile.this.getClass().getSimpleName(), "Failed to obtain the lamp name. Skipping this lamp..."); continue; } Lamp.GetLampState_return_value_usa_sv lampStateResponse = lamp.getLampState(lampId); if (lampStateResponse.responseCode != ResponseCode.OK.getValue()) { Log.w(AllJoynLightProfile.this.getClass().getSimpleName(), "Failed to obtain the on/off state. Skipping this lamp..."); continue; } boolean isOn = lampStateResponse.lampState.get("OnOff") .getObject(boolean.class); light.putString(PARAM_NAME, lampNameResponse.lampName); light.putString(PARAM_CONFIG, ""); light.putBoolean(PARAM_ON, isOn); lights.add(light); } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } } response.putExtra(PARAM_LIGHTS, lights.toArray(new Bundle[lights.size()])); setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } @Override protected boolean onPostLight(Intent request, Intent response, String serviceId, String lightId, Float brightness, int[] color) { if (serviceId == null || lightId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } final AllJoynDeviceApplication app = getApplication(); final AllJoynServiceEntity service = app.getDiscoveredAlljoynServices().get(serviceId); if (service == null) { MessageUtils.setNotFoundServiceError(response); return true; } switch (getLampServiceType(service)) { case TYPE_SINGLE_LAMP: { onPostLightForSingleLamp(request, response, service, lightId, brightness, color); return false; } case TYPE_LAMP_CONTROLLER: { onPostLightForLampController(request, response, service, lightId, brightness, color); return false; } case TYPE_UNKNOWN: default: { setUnsupportedError(response); return true; } } } private void onPostLightForSingleLamp(Intent request, final Intent response, final AllJoynServiceEntity service, String lightId, final Float brightness, final int[] color) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { LampState state = app.getInterface(busName, sessionId, LampState.class); LampDetails details = app.getInterface(busName, sessionId, LampDetails.class); try { HashMap<String, Variant> newStates = new HashMap<>(); // NOTE: Arithmetic operations in primitive types may lead to arithmetic // overflow. To retain precision, BigDecimal objects are used. newStates.put("OnOff", new Variant(true, "b")); if (details.getColor() && color != null) { int[] hsb = ColorUtil.convertRGB_8_8_8_To_HSB_32_32_32(color); newStates.put("Hue", new Variant(hsb[0], "u")); newStates.put("Saturation", new Variant(hsb[1], "u")); } if (details.getDimmable() && brightness != null) { // [0, 1] -> [0, 0xffffffff] BigDecimal tmp = BigDecimal.valueOf(0xffffffffl); tmp = tmp.multiply(BigDecimal.valueOf(brightness)); long scaledVal = tmp.longValue(); int intScaledVal = ByteBuffer.allocate(8).putLong(scaledVal).getInt(4); newStates.put("Brightness", new Variant(intScaledVal, "u")); } int responseCode = state.transitionLampState(0, newStates, TRANSITION_PERIOD); if (responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to change lamp states."); getContext().sendBroadcast(response); return; } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } private void onPostLightForLampController(Intent request, final Intent response, AllJoynServiceEntity service, final String lightId, final Float brightness, final int[] color) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { Lamp lamp = app.getInterface(busName, sessionId, Lamp.class); try { Lamp.GetLampDetails_return_value_usa_sv lampDetailsResponse = lamp.getLampDetails(lightId); if (lampDetailsResponse == null || lampDetailsResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to obtain lamp details."); getContext().sendBroadcast(response); return; } HashMap<String, Variant> newStates = new HashMap<>(); // NOTE: Arithmetic operations in primitive types may lead to arithmetic // overflow. To retain precision, BigDecimal objects are used. newStates.put("OnOff", new Variant(true, "b")); if (lampDetailsResponse.lampDetails.containsKey("Color")) { if (lampDetailsResponse.lampDetails.get("Color").getObject(boolean.class) && color != null) { int[] hsb = ColorUtil.convertRGB_8_8_8_To_HSB_32_32_32(color); newStates.put("Hue", new Variant(hsb[0], "u")); newStates.put("Saturation", new Variant(hsb[1], "u")); } } else { Log.w(AllJoynLightProfile.this.getClass().getSimpleName(), "Color support is not described in the lamp details. " + "Assuming it is not supported..."); } if (lampDetailsResponse.lampDetails.containsKey("Dimmable")) { if (lampDetailsResponse.lampDetails.get("Dimmable").getObject(boolean.class) && brightness != null) { // [0, 1] -> [0, 0xffffffff] BigDecimal tmp = BigDecimal.valueOf(0xffffffffl); tmp = tmp.multiply(BigDecimal.valueOf(brightness)); long scaledVal = tmp.longValue(); int intScaledVal = ByteBuffer.allocate(8).putLong(scaledVal).getInt(4); newStates.put("Brightness", new Variant(intScaledVal, "u")); } } else { Log.w(AllJoynLightProfile.this.getClass().getSimpleName(), "Dim support is not described in the lamp details. " + "Assuming it is not supported..."); } Lamp.TransitionLampState_return_value_us transLampStateResponse = lamp.transitionLampState(lightId, newStates, TRANSITION_PERIOD); if (transLampStateResponse == null || transLampStateResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to change lamp states."); getContext().sendBroadcast(response); return; } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } @Override protected boolean onDeleteLight(Intent request, Intent response, String serviceId, String lightId) { if (serviceId == null || lightId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } final AllJoynDeviceApplication app = getApplication(); final AllJoynServiceEntity service = app.getDiscoveredAlljoynServices().get(serviceId); if (service == null) { MessageUtils.setNotFoundServiceError(response); return true; } switch (getLampServiceType(service)) { case TYPE_SINGLE_LAMP: { onDeleteLightForSingleLamp(request, response, service, lightId); return false; } case TYPE_LAMP_CONTROLLER: { onDeleteLightForLampController(request, response, service, lightId); return false; } case TYPE_UNKNOWN: default: { setUnsupportedError(response); return true; } } } private void onDeleteLightForSingleLamp(Intent request, final Intent response, final AllJoynServiceEntity service, String lightId) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { LampState state = app.getInterface(busName, sessionId, LampState.class); try { state.setOnOff(false); } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } private void onDeleteLightForLampController(Intent request, final Intent response, final AllJoynServiceEntity service, final String lightId) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { Lamp lamp = app.getInterface(busName, sessionId, Lamp.class); try { Map<String, Variant> newStates = new HashMap<>(); newStates.put("OnOff", new Variant(false, "b")); Lamp.TransitionLampState_return_value_us transLampStateResponse = lamp.transitionLampState(lightId, newStates, TRANSITION_PERIOD); if (transLampStateResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to turn off the light."); getContext().sendBroadcast(response); return; } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } @Override protected boolean onPutLight(Intent request, Intent response, String serviceId, String lightId, String name, Float brightness, int[] color) { if (serviceId == null || lightId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } final AllJoynDeviceApplication app = getApplication(); final AllJoynServiceEntity service = app.getDiscoveredAlljoynServices().get(serviceId); if (service == null) { MessageUtils.setNotFoundServiceError(response); return true; } switch (getLampServiceType(service)) { case TYPE_SINGLE_LAMP: { onPutLightForSingleLamp(request, response, service, lightId, name, brightness, color); return false; } case TYPE_LAMP_CONTROLLER: { onPutLightForLampController(request, response, service, lightId, name, brightness, color); return false; } case TYPE_UNKNOWN: default: { setUnsupportedError(response); return true; } } } // TODO: Implement name change functionality using AllJoyn Config service. private void onPutLightForSingleLamp(Intent request, final Intent response, AllJoynServiceEntity service, String lightId, String name, final Float brightness, final int[] color) { if (lightId == null) { MessageUtils.setInvalidRequestParameterError(response, "Parameter 'lightId' must be specified."); getContext().sendBroadcast(response); return; } if (name == null) { } if (brightness != null && (brightness < 0 || brightness > 1)) { MessageUtils.setInvalidRequestParameterError(response, "Parameter 'brightness' must be within range [0, 1]."); getContext().sendBroadcast(response); return; } if (color != null && color.length != 3) { MessageUtils.setInvalidRequestParameterError(response, "Parameter 'color' must be a string representing " + "an RGB hexadecimal (e.g. ff0000)."); getContext().sendBroadcast(response); return; } final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { LampState state = app.getInterface(busName, sessionId, LampState.class); LampDetails details = app.getInterface(busName, sessionId, LampDetails.class); try { HashMap<String, Variant> newStates = new HashMap<>(); // NOTE: Arithmetic operations in primitive types may lead to arithmetic // overflow. To retain precision, BigDecimal objects are used. if (details.getColor() && color != null) { int[] hsb = ColorUtil.convertRGB_8_8_8_To_HSB_32_32_32(color); newStates.put("Hue", new Variant(hsb[0], "u")); newStates.put("Saturation", new Variant(hsb[1], "u")); } if (details.getDimmable() && brightness != null) { // [0, 1] -> [0, 0xffffffff] BigDecimal tmp = BigDecimal.valueOf(0xffffffffl); tmp = tmp.multiply(BigDecimal.valueOf(brightness)); long scaledVal = tmp.longValue(); int intScaledVal = ByteBuffer.allocate(8).putLong(scaledVal).getInt(4); newStates.put("Brightness", new Variant(intScaledVal, "u")); } int responseCode = state.transitionLampState(0, newStates, TRANSITION_PERIOD); if (responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to change lamp states."); getContext().sendBroadcast(response); return; } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } private void onPutLightForLampController(Intent request, final Intent response, final AllJoynServiceEntity service, final String lightId, final String name, final Float brightness, final int[] color) { if (lightId == null) { MessageUtils.setInvalidRequestParameterError(response, "Parameter 'lightId' must be specified."); getContext().sendBroadcast(response); return; } if (brightness != null && (brightness < 0 || brightness > 1)) { MessageUtils.setInvalidRequestParameterError(response, "Parameter 'brightness' must be within range [0, 1]."); getContext().sendBroadcast(response); return; } if (color != null && color.length != 3) { MessageUtils.setInvalidRequestParameterError(response, "Parameter 'color' must be a string representing " + "an RGB hexadecimal (e.g. ff0000)."); getContext().sendBroadcast(response); return; } final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { Lamp lamp = app.getInterface(busName, sessionId, Lamp.class); try { HashMap<String, Variant> newStates = new HashMap<>(); // NOTE: Arithmetic operations in primitive types may lead to arithmetic // overflow. To retain precision, BigDecimal objects are used. Lamp.GetLampDetails_return_value_usa_sv lampDetailsResponse = lamp.getLampDetails(lightId); if (lampDetailsResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to obtain lamp details."); getContext().sendBroadcast(response); return; } if (lampDetailsResponse.lampDetails.containsKey("Color")) { if (lampDetailsResponse.lampDetails.get("Color").getObject(boolean.class) && color != null) { int[] hsb = ColorUtil.convertRGB_8_8_8_To_HSB_32_32_32(color); newStates.put("Hue", new Variant(hsb[0], "u")); newStates.put("Saturation", new Variant(hsb[1], "u")); } } if (lampDetailsResponse.lampDetails.containsKey("Dimmable")) { if (lampDetailsResponse.lampDetails.get("Dimmable").getObject(boolean.class) && brightness != null) { // [0, 1] -> [0, 0xffffffff] BigDecimal tmp = BigDecimal.valueOf(0xffffffffl); tmp = tmp.multiply(BigDecimal.valueOf(brightness)); long scaledVal = tmp.longValue(); int intScaledVal = ByteBuffer.allocate(8).putLong(scaledVal).getInt(4); newStates.put("Brightness", new Variant(intScaledVal, "u")); } } Lamp.TransitionLampState_return_value_us transitionLampStateResponse = lamp.transitionLampState(lightId, newStates, TRANSITION_PERIOD); if (transitionLampStateResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to change lamp states."); getContext().sendBroadcast(response); return; } if (name != null) { Lamp.SetLampName_return_value_uss lampNameResponse = lamp.setLampName(lightId, name, service.defaultLanguage); if (lampNameResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to change name."); getContext().sendBroadcast(response); return; } } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } @Override protected boolean onGetLightGroup(Intent request, Intent response, String serviceId) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } final AllJoynDeviceApplication app = getApplication(); final AllJoynServiceEntity service = app.getDiscoveredAlljoynServices().get(serviceId); if (service == null) { MessageUtils.setNotFoundServiceError(response); return true; } switch (getLampServiceType(service)) { case TYPE_LAMP_CONTROLLER: { onGetLightGroupForLampController(request, response, service); return false; } case TYPE_SINGLE_LAMP: case TYPE_UNKNOWN: default: { setUnsupportedError(response); return true; } } } private void onGetLightGroupForLampController(Intent request, final Intent response, final AllJoynServiceEntity service) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { LampGroup proxyLampGroup = app.getInterface(busName, sessionId, LampGroup.class); if (proxyLampGroup == null) { MessageUtils.setUnknownError(response, "Failed to obtain a proxy object for org.allseen.LSF.ControllerService.LampGroup ."); getContext().sendBroadcast(response); return; } try { LampGroup.GetAllLampGroupIDs_return_value_uas allLampGroupIDsResponse = proxyLampGroup.getAllLampGroupIDs(); if (allLampGroupIDsResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to obtain lamp group IDs."); getContext().sendBroadcast(response); return; } // Obtain lamp group info. HashMap<String, LampGroupInfo> lampGroups = new HashMap<>(); for (String lampGroupID : allLampGroupIDsResponse.lampGroupIDs) { LampGroupInfo lampGroupInfo = new LampGroupInfo(); lampGroupInfo.ID = lampGroupID; { LampGroup.GetLampGroupName_return_value_usss lampGroupNameResponse = proxyLampGroup.getLampGroupName(lampGroupID, service.defaultLanguage); if (lampGroupNameResponse.responseCode != ResponseCode.OK.getValue()) { Log.w(AllJoynLightProfile.this.getClass().getSimpleName(), "Failed to obtain lamp group name. Skipping this lamp group..."); continue; } lampGroupInfo.name = lampGroupNameResponse.lampGroupName; } { LampGroup.GetLampGroup_return_value_usasas lampGroupResponse = proxyLampGroup.getLampGroup(lampGroupID); if (lampGroupResponse.responseCode != ResponseCode.OK.getValue()) { Log.w(AllJoynLightProfile.this.getClass().getSimpleName(), "Failed to obtain IDs of lamps and lamp groups contained in a lamp group. Skipping this lamp group..."); continue; } lampGroupInfo.lampIDs = new HashSet<>(Arrays.asList(lampGroupResponse.lampID)); lampGroupInfo.lampGroupIDs = new HashSet<>(Arrays.asList(lampGroupResponse.lampGroupIDs)); } lampGroupInfo.config = ""; lampGroups.put(lampGroupID, lampGroupInfo); } // Expand lamp IDs contained in lamp groups. for (LampGroupInfo searchTarget : lampGroups.values()) { for (LampGroupInfo expandTarget : lampGroups.values()) { if (searchTarget.ID.equals(expandTarget.ID)) { continue; } if (expandTarget.lampGroupIDs.contains(searchTarget.ID)) { expandTarget.lampIDs.addAll(searchTarget.lampIDs); expandTarget.lampGroupIDs.addAll(searchTarget.lampGroupIDs); expandTarget.lampGroupIDs.remove(searchTarget.ID); } } } // Obtain lamp info. HashMap<String, LampInfo> lamps = new HashMap<>(); Lamp proxyLamp = app.getInterface(busName, sessionId, Lamp.class); if (proxyLamp == null) { MessageUtils.setUnknownError(response, "Failed to obtain a proxy object for org.allseen.LSF.ControllerService.Lamp ."); getContext().sendBroadcast(response); return; } for (LampGroupInfo lampGroup : lampGroups.values()) { for (String lampID : lampGroup.lampIDs) { if (lamps.containsKey(lampID)) { continue; } LampInfo lamp = new LampInfo(); lamp.ID = lampID; { Lamp.GetLampName_return_value_usss lampNameResponse = proxyLamp.getLampName(lampID, service.defaultLanguage); if (lampNameResponse.responseCode == ResponseCode.OK.getValue()) { lamp.name = lampNameResponse.lampName; } else { Log.w(AllJoynLightProfile.this.getClass().getSimpleName(), "Failed to obtain lamp name..."); } } { Lamp.GetLampState_return_value_usa_sv lampStateResponse = proxyLamp.getLampState(lampID); if (lampStateResponse.responseCode == ResponseCode.OK.getValue()) { if (lampStateResponse.lampState.containsKey("OnOff")) { lamp.on = lampStateResponse .lampState.get("OnOff").getObject(Boolean.class); } else { Log.w(AllJoynLightProfile.this.getClass().getSimpleName(), "Failed to obtain on/off state..."); } } else { Log.w(AllJoynLightProfile.this.getClass().getSimpleName(), "Failed to obtain lamp state..."); } } lamp.config = ""; lamps.put(lampID, lamp); } } List<Bundle> lightGroupsBundle = new ArrayList<>(); for (LampGroupInfo lampGroup : lampGroups.values()) { Bundle lightGroupBundle = new Bundle(); lightGroupBundle.putString(PARAM_GROUP_ID, lampGroup.ID); lightGroupBundle.putString(PARAM_NAME, lampGroup.name); List<Bundle> lightsBundle = new ArrayList<>(); for (String lampID : lampGroup.lampIDs) { LampInfo lamp = lamps.get(lampID); Bundle lightBundle = new Bundle(); lightBundle.putString(PARAM_LIGHT_ID, lamp.ID); if (lamp.name != null) { lightBundle.putString(PARAM_NAME, lamp.name); } if (lamp.on != null) { lightBundle.putBoolean(PARAM_ON, lamp.on); } lightBundle.putString(PARAM_CONFIG, lamp.config); lightsBundle.add(lightBundle); } lightGroupBundle.putParcelableArray(PARAM_LIGHTS, lightsBundle.toArray(new Bundle[lightsBundle.size()])); lightGroupBundle.putString(PARAM_CONFIG, lampGroup.config); lightGroupsBundle.add(lightGroupBundle); } response.putExtra(PARAM_LIGHT_GROUPS, lightGroupsBundle.toArray(new Bundle[lightGroupsBundle.size()])); setResultOK(response); getContext().sendBroadcast(response); } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } @Override protected boolean onPostLightGroup(final Intent request, final Intent response, final String serviceId, final String groupId, final Float brightness, final int[] color) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } final AllJoynDeviceApplication app = getApplication(); final AllJoynServiceEntity service = app.getDiscoveredAlljoynServices().get(serviceId); if (service == null) { MessageUtils.setNotFoundServiceError(response); return true; } switch (getLampServiceType(service)) { case TYPE_LAMP_CONTROLLER: { onPostLightGroupForLampController(request, response, service, groupId , brightness, color); return false; } case TYPE_SINGLE_LAMP: case TYPE_UNKNOWN: default: { setUnsupportedError(response); return true; } } } private void onPostLightGroupForLampController(Intent request, final Intent response, AllJoynServiceEntity service, final String groupID, final Float brightness, final int[] color) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { LampGroup proxyLampGroup = app.getInterface(busName, sessionId, LampGroup.class); if (proxyLampGroup == null) { MessageUtils.setUnknownError(response, "Failed to obtain a proxy object for org.allseen.LSF.ControllerService.LampGroup ."); getContext().sendBroadcast(response); return; } try { HashMap<String, Variant> newStates = new HashMap<>(); // NOTE: Arithmetic operations in primitive types may lead to arithmetic // overflow. To retain precision, BigDecimal objects are used. newStates.put("OnOff", new Variant(true, "b")); if (color != null) { int[] hsb = ColorUtil.convertRGB_8_8_8_To_HSB_32_32_32(color); newStates.put("Hue", new Variant(hsb[0], "u")); newStates.put("Saturation", new Variant(hsb[1], "u")); } if (brightness != null) { // [0, 1] -> [0, 0xffffffff] BigDecimal tmp = BigDecimal.valueOf(0xffffffffl); tmp = tmp.multiply(BigDecimal.valueOf(brightness)); long scaledVal = tmp.longValue(); int intScaledVal = ByteBuffer.allocate(8).putLong(scaledVal).getInt(4); newStates.put("Brightness", new Variant(intScaledVal, "u")); } LampGroup.TransitionLampGroupState_return_value_us transLampGroupStateResponse = proxyLampGroup.transitionLampGroupState(groupID, newStates, TRANSITION_PERIOD); if (transLampGroupStateResponse == null || transLampGroupStateResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to change lamp group states."); getContext().sendBroadcast(response); return; } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } @Override protected boolean onDeleteLightGroup(Intent request, Intent response, String serviceId, String groupID) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } final AllJoynDeviceApplication app = getApplication(); final AllJoynServiceEntity service = app.getDiscoveredAlljoynServices().get(serviceId); if (service == null) { MessageUtils.setNotFoundServiceError(response); return true; } switch (getLampServiceType(service)) { case TYPE_LAMP_CONTROLLER: { onDeleteLightGroupForLampController(request, response, service, groupID); return false; } case TYPE_SINGLE_LAMP: case TYPE_UNKNOWN: default: { setUnsupportedError(response); return true; } } } private void onDeleteLightGroupForLampController(Intent request, final Intent response , AllJoynServiceEntity service, final String groupID) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { LampGroup proxy = app.getInterface(busName, sessionId, LampGroup.class); try { Map<String, Variant> newStates = new HashMap<>(); newStates.put("OnOff", new Variant(false, "b")); LampGroup.TransitionLampGroupState_return_value_us transLampGroupStateResponse = proxy.transitionLampGroupState(groupID, newStates, TRANSITION_PERIOD); if (transLampGroupStateResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to turn off the light group."); getContext().sendBroadcast(response); return; } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } @Override protected boolean onPutLightGroup(Intent request, Intent response, String serviceId , String groupId, String name, Float brightness, int[] color) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } final AllJoynDeviceApplication app = getApplication(); final AllJoynServiceEntity service = app.getDiscoveredAlljoynServices().get(serviceId); if (service == null) { MessageUtils.setNotFoundServiceError(response); return true; } switch (getLampServiceType(service)) { case TYPE_LAMP_CONTROLLER: { onPutLightGroupForLampController(request, response, service, groupId, name , brightness, color); return false; } case TYPE_SINGLE_LAMP: case TYPE_UNKNOWN: default: { setUnsupportedError(response); return true; } } } private void onPutLightGroupForLampController(Intent request, final Intent response , final AllJoynServiceEntity service, final String groupID, final String name , final Float brightness, final int[] color) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { LampGroup proxyLampGroup = app.getInterface(busName, sessionId, LampGroup.class); if (proxyLampGroup == null) { MessageUtils.setUnknownError(response, "Failed to obtain a proxy object for org.allseen.LSF.ControllerService.LampGroup ."); getContext().sendBroadcast(response); return; } try { HashMap<String, Variant> newStates = new HashMap<>(); // NOTE: Arithmetic operations in primitive types may lead to arithmetic // overflow. To retain precision, BigDecimal objects are used. if (color != null) { int[] hsb = ColorUtil.convertRGB_8_8_8_To_HSB_32_32_32(color); newStates.put("Hue", new Variant(hsb[0], "u")); newStates.put("Saturation", new Variant(hsb[1], "u")); } if (brightness != null) { // [0, 1] -> [0, 0xffffffff] BigDecimal tmp = BigDecimal.valueOf(0xffffffffl); tmp = tmp.multiply(BigDecimal.valueOf(brightness)); long scaledVal = tmp.longValue(); int intScaledVal = ByteBuffer.allocate(8).putLong(scaledVal).getInt(4); newStates.put("Brightness", new Variant(intScaledVal, "u")); } LampGroup.TransitionLampGroupState_return_value_us transLampGroupStateResponse = proxyLampGroup.transitionLampGroupState(groupID, newStates, TRANSITION_PERIOD); if (transLampGroupStateResponse == null || transLampGroupStateResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to change lamp group states."); getContext().sendBroadcast(response); return; } if (name != null) { LampGroup.SetLampGroupName_return_value_uss setLampGroupNameResponse = proxyLampGroup.setLampGroupName(groupID, name, service.defaultLanguage); if (setLampGroupNameResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to change group name."); getContext().sendBroadcast(response); return; } } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } @Override protected boolean onPostLightGroupCreate(Intent request, Intent response, String serviceId , String[] lightIDs, String groupName) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } final AllJoynDeviceApplication app = getApplication(); final AllJoynServiceEntity service = app.getDiscoveredAlljoynServices().get(serviceId); if (service == null) { MessageUtils.setNotFoundServiceError(response); return true; } switch (getLampServiceType(service)) { case TYPE_LAMP_CONTROLLER: { onPostLightGroupCreateForLampController(request, response, service , lightIDs, groupName); return false; } case TYPE_SINGLE_LAMP: case TYPE_UNKNOWN: default: { setUnsupportedError(response); return true; } } } private void onPostLightGroupCreateForLampController(Intent request, final Intent response , final AllJoynServiceEntity service, final String[] lightIDs, final String groupName) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { LampGroup proxyLampGroup = app.getInterface(busName, sessionId, LampGroup.class); if (proxyLampGroup == null) { MessageUtils.setUnknownError(response, "Failed to obtain a proxy object for org.allseen.LSF.ControllerService.LampGroup ."); getContext().sendBroadcast(response); return; } try { LampGroup.CreateLampGroup_return_value_us createLampGroupResponse = proxyLampGroup.createLampGroup(lightIDs, new String[0], groupName , service.defaultLanguage); if (createLampGroupResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to create a light group."); getContext().sendBroadcast(response); return; } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } @Override protected boolean onDeleteLightGroupClear(Intent request, Intent response , String serviceId, String groupID) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } final AllJoynDeviceApplication app = getApplication(); final AllJoynServiceEntity service = app.getDiscoveredAlljoynServices().get(serviceId); if (service == null) { MessageUtils.setNotFoundServiceError(response); return true; } switch (getLampServiceType(service)) { case TYPE_LAMP_CONTROLLER: { onDeleteLightGroupClearForLampController(request, response, service, groupID); return false; } case TYPE_SINGLE_LAMP: case TYPE_UNKNOWN: default: { setUnsupportedError(response); return true; } } } private void onDeleteLightGroupClearForLampController(Intent request, final Intent response , final AllJoynServiceEntity service, final String groupID) { final AllJoynDeviceApplication app = getApplication(); OneShotSessionHandler.SessionJoinCallback callback = new OneShotSessionHandler.SessionJoinCallback() { @Override public void onSessionJoined(@NonNull String busName, short port, int sessionId) { LampGroup proxyLampGroup = app.getInterface(busName, sessionId, LampGroup.class); if (proxyLampGroup == null) { MessageUtils.setUnknownError(response, "Failed to obtain a proxy object for org.allseen.LSF.ControllerService.LampGroup ."); getContext().sendBroadcast(response); return; } try { LampGroup.DeleteLampGroup_return_value_us deleteLampGroupResponse = proxyLampGroup.deleteLampGroup(groupID); if (deleteLampGroupResponse.responseCode != ResponseCode.OK.getValue()) { MessageUtils.setUnknownError(response, "Failed to delete the light group."); getContext().sendBroadcast(response); return; } } catch (BusException e) { MessageUtils.setUnknownError(response, e.getLocalizedMessage()); getContext().sendBroadcast(response); return; } setResultOK(response); getContext().sendBroadcast(response); } @Override public void onSessionFailed(@NonNull String busName, short port) { MessageUtils.setUnknownError(response, "Failed to join session."); getContext().sendBroadcast(response); } }; OneShotSessionHandler.run(getContext(), service.busName, service.port, callback); } /** * Error * * @param response response */ private void setResultERR(final Intent response) { setResult(response, DConnectMessage.RESULT_ERROR); } /** * * * @param response response */ private void setResultOK(final Intent response) { setResult(response, DConnectMessage.RESULT_OK); } private boolean isSupportingInterfaces(@NonNull AllJoynServiceEntity service, String... interfaces) { if (interfaces == null || interfaces.length == 0 || service.proxyObjects == null) { return false; } for (String ifaceCheck : interfaces) { boolean found = false; for (BusObjectDescription busObject : service.proxyObjects) { if (Arrays.asList(busObject.interfaces).contains(ifaceCheck)) { found = true; break; } } if (!found) { return false; } } return true; } private LampServiceType getLampServiceType(@NonNull AllJoynServiceEntity service) { if (isSupportingInterfaces(service, "org.allseen.LSF.ControllerService.Lamp")) { // Can manage and control multiple lamps. return LampServiceType.TYPE_LAMP_CONTROLLER; } else if (isSupportingInterfaces(service, "org.allseen.LSF.LampState")) { // Can control a single lamp. return LampServiceType.TYPE_SINGLE_LAMP; } return LampServiceType.TYPE_UNKNOWN; } private static class LampGroupInfo { public String ID; public String name; public Set<String> lampIDs; public Set<String> lampGroupIDs; public String config; } private static class LampInfo { public String ID; public String name; public Boolean on; public String config; } }
package com.jcabi.github; import com.rexsl.test.Request; import com.rexsl.test.mock.MkAnswer; import com.rexsl.test.mock.MkContainer; import com.rexsl.test.mock.MkGrizzlyContainer; import com.rexsl.test.request.ApacheRequest; import java.net.HttpURLConnection; import javax.json.Json; import javax.json.JsonObject; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mockito; /** * Test case for {@link com.jcabi.github.Repos}. * @author Gena Svarovski (g.svarovski@gmail.com) * @version $Id$ */ public final class RtReposTest { /** * The key for name in JSON. */ private static final String NAME_KEY = "name"; /** * RtRepos can create a repo. * @throws Exception if some problem inside */ @Test public void createRepo() throws Exception { final String owner = "test-owner"; final String name = "test-repo"; final String response = response(owner, name).toString(); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_CREATED, response) ).next(new MkAnswer.Simple(HttpURLConnection.HTTP_OK, response)) .start(); final RtRepos repos = new RtRepos( Mockito.mock(Github.class), new ApacheRequest(container.home()) ); final Repo repo = repos.create(request(name)); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( repo.coordinates(), Matchers.equalTo((Coordinates) new Coordinates.Simple(owner, name)) ); container.stop(); } /** * Create and return JsonObject to test request. * * @param name Repo name * @return JsonObject * @throws Exception If some problem inside */ private static JsonObject request( final String name) throws Exception { return Json.createObjectBuilder() .add(NAME_KEY, name) .build(); } /** * Create and return JsonObject to test response. * * @param owner Owner name * @param name Repo name * @return JsonObject * @throws Exception If some problem inside */ private static JsonObject response( final String owner, final String name) throws Exception { return Json.createObjectBuilder() .add(NAME_KEY, name) .add("full_name", String.format("%s/%s", owner, name)) .add( "owner", Json.createObjectBuilder().add("login", owner).build() ) .build(); } }
package com.qiniu.storage; import com.qiniu.TestConfig; import com.qiniu.common.QiniuException; import com.qiniu.http.Response; import com.qiniu.storage.model.BatchStatus; import com.qiniu.storage.model.FileInfo; import com.qiniu.storage.model.FileListing; import com.qiniu.util.StringMap; import com.qiniu.util.StringUtils; import org.junit.Test; import static org.junit.Assert.*; @SuppressWarnings("ConstantConditions") public class BucketTest { private BucketManager bucketManager = new BucketManager(TestConfig.testAuth); private BucketManager dummyBucketManager = new BucketManager(TestConfig.dummyAuth); @Test public void testBuckets() { try { String[] buckets = bucketManager.buckets(); assertTrue(StringUtils.inStringArray(TestConfig.bucket, buckets)); } catch (QiniuException e) { fail(e.getMessage()); } try { dummyBucketManager.buckets(); fail(); } catch (QiniuException e) { assertEquals(401, e.code()); } } @Test public void testList() { try { FileListing l = bucketManager.listFiles(TestConfig.bucket, null, null, 2, null); assertNotNull(l.items[0]); assertNotNull(l.marker); } catch (QiniuException e) { e.printStackTrace(); fail(); } } @Test public void testListUseDelimiter() { try { bucketManager.copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, "test/", true); bucketManager.copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, "test/1", true); bucketManager.copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, "test/2", true); bucketManager.copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, "test/3/", true); FileListing l = bucketManager.listFiles(TestConfig.bucket, "test/", null, 10, "/"); assertEquals(3, l.items.length); assertEquals(1, l.commonPrefixes.length); } catch (QiniuException e) { e.printStackTrace(); fail(); } } @Test public void testListIterator() { BucketManager.FileListIterator it = bucketManager .createFileListIterator(TestConfig.bucket, "", 20, null); assertTrue(it.hasNext()); FileInfo[] items0 = it.next(); assertNotNull(items0[0]); while (it.hasNext()) { FileInfo[] items = it.next(); if (items.length > 1) { assertNotNull(items[0]); } } } @Test public void testStat() { try { FileInfo info = bucketManager.stat(TestConfig.bucket, TestConfig.key); assertEquals("FmYW4RYti94tr4ncaKzcTJz9M4Y9", info.hash); } catch (QiniuException e) { e.printStackTrace(); fail(); } try { bucketManager.stat(TestConfig.bucket, "noFile"); fail(); } catch (QiniuException e) { assertEquals(612, e.code()); } try { bucketManager.stat(TestConfig.bucket, null); fail(); } catch (QiniuException e) { assertEquals(612, e.code()); } try { bucketManager.stat("noBucket", "noFile"); fail(); } catch (QiniuException e) { assertEquals(631, e.code()); } } @Test public void testDelete() { try { bucketManager.delete(TestConfig.bucket, "del"); fail(); } catch (QiniuException e) { assertEquals(612, e.code()); } try { bucketManager.delete(TestConfig.bucket, null); fail(); } catch (QiniuException e) { assertEquals(612, e.code()); } try { bucketManager.delete("noBucket", null); fail(); } catch (QiniuException e) { assertEquals(631, e.code()); } } @Test public void testRename() { String key = "renameFrom" + Math.random(); try { bucketManager.copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, key); String key2 = "renameTo" + key; bucketManager.rename(TestConfig.bucket, key, key2); bucketManager.delete(TestConfig.bucket, key2); } catch (QiniuException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testCopy() { String key = "copyTo" + Math.random(); try { bucketManager.copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, key); bucketManager.delete(TestConfig.bucket, key); } catch (QiniuException e) { e.printStackTrace(); fail(); } } @Test public void testChangeMime() { try { bucketManager.changeMime(TestConfig.bucket, "java-sdk.html", "text.html"); } catch (QiniuException e) { e.printStackTrace(); fail(); } } @Test public void testPrefetch() { try { bucketManager.prefetch(TestConfig.bucket, "java-sdk.html"); } catch (QiniuException e) { e.printStackTrace(); fail(); } } @Test public void testFetch() { try { bucketManager.fetch("http://developer.qiniu.com/docs/v6/sdk/java-sdk.html", TestConfig.bucket, "fetch.html"); } catch (QiniuException e) { fail(); } } @Test public void testBatchCopy() { String key = "copyTo" + Math.random(); BucketManager.Batch ops = new BucketManager.Batch(). copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, key); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); assertEquals(200, bs[0].code); } catch (QiniuException e) { e.printStackTrace(); fail(); } ops = new BucketManager.Batch().delete(TestConfig.bucket, key); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); assertEquals(200, bs[0].code); } catch (QiniuException e) { e.printStackTrace(); } } @Test public void testBatchMove() { String key = "moveFrom" + Math.random(); try { bucketManager.copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, key); } catch (QiniuException e) { e.printStackTrace(); fail(); } String key2 = key + "to"; StringMap x = new StringMap().put(key, key2); BucketManager.Batch ops = new BucketManager.Batch().move(TestConfig.bucket, key, TestConfig.bucket, key2); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); assertEquals(200, bs[0].code); } catch (QiniuException e) { e.printStackTrace(); fail(); } try { bucketManager.delete(TestConfig.bucket, key2); } catch (QiniuException e) { e.printStackTrace(); fail(); } } @Test public void testBatchRename() { String key = "rename" + Math.random(); try { bucketManager.copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, key); } catch (QiniuException e) { e.printStackTrace(); fail(); } String key2 = key + "to"; BucketManager.Batch ops = new BucketManager.Batch().rename(TestConfig.bucket, key, key2); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); assertEquals(200, bs[0].code); } catch (QiniuException e) { e.printStackTrace(); fail(); } try { bucketManager.delete(TestConfig.bucket, key2); } catch (QiniuException e) { e.printStackTrace(); fail(); } } @Test public void testBatchStat() { String[] array = {"java-sdk.html"}; BucketManager.Batch ops = new BucketManager.Batch().stat(TestConfig.bucket, array); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); assertEquals(200, bs[0].code); } catch (QiniuException e) { e.printStackTrace(); fail(); } } @Test public void testBatch() { String[] array = {"java-sdk.html"}; String key = "copyFrom" + Math.random(); String key1 = "moveFrom" + Math.random(); String key2 = "moveTo" + Math.random(); String key3 = "moveFrom" + Math.random(); String key4 = "moveTo" + Math.random(); try { bucketManager.copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, key1); bucketManager.copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, key3); } catch (QiniuException e) { e.printStackTrace(); fail(); } BucketManager.Batch ops = new BucketManager.Batch() .copy(TestConfig.bucket, TestConfig.key, TestConfig.bucket, key) .move(TestConfig.bucket, key1, TestConfig.bucket, key2) .rename(TestConfig.bucket, key3, key4) .stat(TestConfig.bucket, array) .stat(TestConfig.bucket, array[0]); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); for (BatchStatus b : bs) { assertEquals(200, b.code); } } catch (QiniuException e) { e.printStackTrace(); fail(); } } }
package org.opennms.features.topology.app.internal; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.xml.bind.JAXBException; import org.opennms.features.topology.api.topo.Criteria; import org.opennms.features.topology.api.topo.Edge; import org.opennms.features.topology.api.topo.EdgeListener; import org.opennms.features.topology.api.topo.EdgeRef; import org.opennms.features.topology.api.topo.GraphProvider; import org.opennms.features.topology.api.topo.RefComparator; import org.opennms.features.topology.api.topo.Vertex; import org.opennms.features.topology.api.topo.VertexListener; import org.opennms.features.topology.api.topo.VertexRef; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class will be used to filter a topology so that the semantic zoom level is * interpreted as a hop distance away from a set of selected vertices. The vertex * selection is specified using a {@link Criteria} filter. * * @author Seth */ public class VertexHopGraphProvider implements GraphProvider { private static final Logger LOG = LoggerFactory.getLogger(VertexHopGraphProvider.class); public static class VertexHopCriteria implements Criteria { private static final long serialVersionUID = 2904432878716561926L; private static final Set<VertexRef> m_vertices = new TreeSet<VertexRef>(new RefComparator()); //private int m_hops; public VertexHopCriteria() { super(); //m_hops = hops; } public VertexHopCriteria(List<VertexRef> objects/*, int hops */) { //m_hops = hops; } @Override public ElementType getType() { return ElementType.VERTEX; } /* public int getHops() { return m_hops; } */ /** * TODO: This return value doesn't matter since we just delegate * to the m_delegate provider. */ @Override public String getNamespace() { return "nodes"; } public void add(VertexRef ref) { m_vertices.add(ref); } public void remove(VertexRef ref) { m_vertices.remove(ref); } public void clear(VertexRef ref) { m_vertices.clear(); } public boolean contains(VertexRef ref) { return m_vertices.contains(ref); } } private final GraphProvider m_delegate; private final Map<VertexRef,Integer> m_semanticZoomLevels = new LinkedHashMap<VertexRef,Integer>(); public VertexHopGraphProvider(GraphProvider delegate) { m_delegate = delegate; } @Override public void save() { m_delegate.save(); } @Override public void load(String filename) throws MalformedURLException, JAXBException { m_delegate.load(filename); } @Override public void refresh() { m_delegate.refresh(); } @Override public String getVertexNamespace() { return m_delegate.getVertexNamespace(); } @Override public boolean contributesTo(String namespace) { return m_delegate.contributesTo(namespace); } @Override public boolean containsVertexId(String id) { return m_delegate.containsVertexId(id); } @Override public boolean containsVertexId(VertexRef id) { return m_delegate.containsVertexId(id); } @Override public Vertex getVertex(String namespace, String id) { return m_delegate.getVertex(namespace, id); } @Override public Vertex getVertex(VertexRef reference) { return m_delegate.getVertex(reference); } @Override public int getSemanticZoomLevel(VertexRef vertex) { Integer szl = m_semanticZoomLevels.get(vertex); return szl == null ? 0 : szl; } /** * TODO: OVERRIDE THIS FUNCTION */ @Override public List<Vertex> getVertices(Criteria... criteria) { List<Vertex> retval = new ArrayList<Vertex>(); List<VertexRef> currentHops = new ArrayList<VertexRef>(); List<VertexRef> nextHops = new ArrayList<VertexRef>(); List<Vertex> allVertices = new ArrayList<Vertex>(); // Get the entire list of vertices allVertices.addAll(m_delegate.getVertices(criteria)); // Find the vertices that match a required HopDistanceCriteria for (Criteria criterium : criteria) { try { VertexHopCriteria hdCriteria = (VertexHopCriteria)criterium; for (Iterator<Vertex> itr = allVertices.iterator();itr.hasNext();) { Vertex vertex = itr.next(); if (hdCriteria.contains(vertex)) { // Put the vertex into the return value and remove it // from the list of all eligible vertices retval.add(vertex); nextHops.add(vertex); itr.remove(); LOG.debug("Added {} to selected vertex list", vertex); } } } catch (ClassCastException e) {} } // Clear the existing semantic zoom level values m_semanticZoomLevels.clear(); int semanticZoomLevel = 0; // Put a limit on the SZL in case we infinite loop for some reason while (semanticZoomLevel < 100 && nextHops.size() > 0) { currentHops.addAll(nextHops); nextHops.clear(); for (VertexRef vertex : currentHops) { // Mark the current vertex as belonging to a particular SZL if (m_semanticZoomLevels.get(vertex) != null) { throw new IllegalStateException("Calculating semantic zoom level for vertex that has already been calculated: " + vertex.toString()); } m_semanticZoomLevels.put(vertex, semanticZoomLevel); // Fetch all edges attached to this vertex for (EdgeRef edgeRef : m_delegate.getEdgeIdsForVertex(vertex)) { Edge edge = m_delegate.getEdge(edgeRef); // Find everything attached to those edges VertexRef nextVertex = null; if (vertex.equals(edge.getSource().getVertex())) { nextVertex = edge.getTarget().getVertex(); } else if (vertex.equals(edge.getTarget().getVertex())) { nextVertex = edge.getSource().getVertex(); } else { throw new IllegalStateException(String.format("Vertex %s was not the source or target of edge %s", vertex.toString(), edge.toString())); } // If we haven't assigned a SZL to the vertices that were located, // then put the vertex into the next collection of hops if (allVertices.contains(nextVertex)) { nextHops.add(nextVertex); allVertices.remove(nextVertex); } } } // Clear the temp list of current hops currentHops.clear(); // Increment the semantic zoom level semanticZoomLevel++; } return retval; } /** * TODO: OVERRIDE THIS FUNCTION? */ @Override public List<Vertex> getVertices(Collection<? extends VertexRef> references) { return m_delegate.getVertices(references); } /** * TODO: Is this correct? */ @Override public List<Vertex> getRootGroup() { return getVertices(); } @Override public boolean hasChildren(VertexRef group) { throw new UnsupportedOperationException("Grouping is unsupported by " + getClass().getName()); } @Override public Vertex getParent(VertexRef vertex) { throw new UnsupportedOperationException("Grouping is unsupported by " + getClass().getName()); } @Override public boolean setParent(VertexRef child, VertexRef parent) { throw new UnsupportedOperationException("Grouping is unsupported by " + getClass().getName()); } @Override public List<Vertex> getChildren(VertexRef group) { throw new UnsupportedOperationException("Grouping is unsupported by " + getClass().getName()); } @Override public void addVertexListener(VertexListener vertexListener) { m_delegate.addVertexListener(vertexListener); } @Override public void removeVertexListener(VertexListener vertexListener) { m_delegate.removeVertexListener(vertexListener); } @Override public void clearVertices() { m_delegate.clearVertices(); } @Override public String getEdgeNamespace() { return m_delegate.getEdgeNamespace(); } @Override public Edge getEdge(String namespace, String id) { return m_delegate.getEdge(namespace, id); } @Override public Edge getEdge(EdgeRef reference) { return m_delegate.getEdge(reference); } /** * TODO OVERRIDE THIS FUNCTION */ @Override public List<Edge> getEdges(Criteria... criteria) { return m_delegate.getEdges(criteria); } @Override public List<Edge> getEdges(Collection<? extends EdgeRef> references) { return m_delegate.getEdges(references); } @Override public void addEdgeListener(EdgeListener listener) { m_delegate.addEdgeListener(listener); } @Override public void removeEdgeListener(EdgeListener listener) { m_delegate.removeEdgeListener(listener); } @Override public void clearEdges() { m_delegate.clearEdges(); } @Override public void resetContainer() { m_delegate.resetContainer(); } @Override public void addVertices(Vertex... vertices) { m_delegate.addVertices(vertices); } @Override public void removeVertex(VertexRef... vertexId) { m_delegate.removeVertex(vertexId); } @Override public Vertex addVertex(int x, int y) { return m_delegate.addVertex(x, y); } @Override public Vertex addGroup(String label, String iconKey) { throw new UnsupportedOperationException("Grouping is unsupported by " + getClass().getName()); } @Override public EdgeRef[] getEdgeIdsForVertex(VertexRef vertex) { return m_delegate.getEdgeIdsForVertex(vertex); } @Override public void addEdges(Edge... edges) { m_delegate.addEdges(edges); } @Override public void removeEdges(EdgeRef... edges) { m_delegate.removeEdges(edges); } @Override public Edge connectVertices(VertexRef sourceVertextId, VertexRef targetVertextId) { return m_delegate.connectVertices(sourceVertextId, targetVertextId); } }
package de.osiam.client; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseSetup; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.osiam.client.connector.OsiamConnector; import org.osiam.client.oauth.GrantType; import org.osiam.client.update.UpdateUser; import org.osiam.resources.scim.Address; import org.osiam.resources.scim.MultiValuedAttribute; import org.osiam.resources.scim.User; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.UUID; import static junit.framework.Assert.assertNotSame; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/context.xml") @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class}) @DatabaseSetup("/database_seed.xml") public class UpdateUserIT extends AbstractIntegrationTestBase{ private UUID ID_EXISITNG_USER = UUID.fromString("7d33bcbe-a54c-43d8-867e-f6146164941e"); private UpdateUser UPDATE_USER; private User RETURN_USER; private User ORIGINAL_USER; private String IRRELEVANT = "Irrelevant"; @Test public void delete_multivalue_attributes(){ getOriginalUser("dma"); createUpdateUserWithMultiDeleteFields(); updateUser(); assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getEmails(), "hsimpson@atom-example.com")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getEmails(), "hsimpson@atom-example.com")); assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getPhoneNumbers(), "0245817964")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getPhoneNumbers(), "0245817964")); // assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getEntitlements(), "right2"));TODO at the second run it will fail // assertFalse(isValuePartOfMultivalueList(RETURN_USER.getEntitlements(), "right2"));TODO at the second run it will fail //assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getGroups(), "d30a77eb-d7cf-4cd1-9fb3-cc640ef09578"));TODO Gruppen werden nicht gespeicher //assertFalse(isValuePartOfMultivalueList(RETURN_USER.getGroups(), "d30a77eb-d7cf-4cd1-9fb3-cc640ef09578")); TODO Gruppen werden nicht gespeicher assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getIms(), "ims01")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getIms(), "ims01")); assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getPhotos(), "photo01.jpg")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getPhotos(), "photo01.jpg")); assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getRoles(), "role01")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getRoles(), "role01")); assertTrue(isValuePartOfMultivalueList(ORIGINAL_USER.getX509Certificates(), "certificate01")); assertFalse(isValuePartOfMultivalueList(RETURN_USER.getX509Certificates(), "certificate01")); } @Test public void delete_all_multivalue_attributes(){ getOriginalUser("dama"); createUpdateUserWithMultiAllDeleteFields(); updateUser(); assertNotNull(ORIGINAL_USER.getEmails()); assertNull(RETURN_USER.getEmails()); assertNull(RETURN_USER.getAddresses()); //assertNull(RETURN_USER.getEntitlements());TODO at the second run it will fail assertNull(RETURN_USER.getGroups());//TODO da Gruppen nicht gespeichert werden sind sie immer null assertNull(RETURN_USER.getIms()); assertNull(RETURN_USER.getPhoneNumbers()); assertNull(RETURN_USER.getPhotos()); assertNull(RETURN_USER.getRoles()); } @Test public void add_multivalue_attributes(){ getOriginalUser("ama"); createUpdateUserWithMultiAddFields(); String userString = getUpdateUser(); updateUser(); assertEquals(ORIGINAL_USER.getPhoneNumbers().size() + 1, RETURN_USER.getPhoneNumbers().size()); assertTrue(isValuePartOfMultivalueList(RETURN_USER.getPhoneNumbers(), "99999999991")); assertTrue(isValuePartOfMultivalueList(RETURN_USER.getEmails(), "mac@muster.de")); getAddress(RETURN_USER.getAddresses(), "new Address"); //assertEquals(ORIGINAL_USER.getEntitlements().size() + 1, RETURN_USER.getEntitlements().size());TODO at the second run it will fail //assertTrue(isValuePartOfMultivalueList(RETURN_USER.getEntitlements(), "right3"));TODO at the second run it will fail //assertEquals(ORIGINAL_USER.getGroups().size() + 1, RETURN_USER.getGroups().size());TODO gruppen werden aktuell nicht gespeichert //assertTrue(isValuePartOfMultivalueList(RETURN_USER.getGroups(), "d30a77eb-d7cf-4cd1-9fb3-cc640ef09578"));TODO gruppen werden aktuell nicht gespeichert assertEquals(ORIGINAL_USER.getIms().size() + 1, RETURN_USER.getIms().size()); assertEquals(ORIGINAL_USER.getPhotos().size() + 1, RETURN_USER.getPhotos().size()); assertTrue(isValuePartOfMultivalueList(RETURN_USER.getPhotos(), "photo03.jpg")); assertEquals(ORIGINAL_USER.getRoles().size() + 1, RETURN_USER.getRoles().size()); assertTrue(isValuePartOfMultivalueList(RETURN_USER.getRoles(), "role03")); } @Test public void update_multivalue_attributes(){ getOriginalUser("uma"); createUpdateUserWithMultiUpdateFields(); updateUser(); //phonenumber MultiValuedAttribute multi = getSingleMultiValueAttribute(RETURN_USER.getPhoneNumbers(), "+497845/1157"); //assertFalse(multi.isPrimary());TODO primary wird beim telefon nicht gesetzt multi = getSingleMultiValueAttribute(RETURN_USER.getPhoneNumbers(), "0245817964"); //assertTrue(multi.isPrimary());TODO primary wird beim telefon nicht gesetzt //email //MultiValuedAttribute multi = getSingleMultiValueAttribute(RETURN_USER.getEmails(), "hsimpson@atom-example.com"); //multi = getSingleMultiValueAttribute(RETURN_USER.getEmails(), "hsimpson@home-example.com"); //assertTrue(multi.isPrimary()); //assertEquals("other", multi.getType()); multi = getSingleMultiValueAttribute(RETURN_USER.getIms(), "ims01"); //assertEquals("icq", multi.getType());//TODO der type wird nicht upgedatet multi = getSingleMultiValueAttribute(RETURN_USER.getPhotos(), "photo01.jpg"); //assertEquals("photo", multi.getType());//TODO der type wird nicht upgedatet assertEquals("other", multi.getType()); } @Test public void update_all_single_values(){ getOriginalUser("uasv"); createUpdateUserWithUpdateFields(); updateUser(); assertNotEquals(ORIGINAL_USER.getUserName(), RETURN_USER.getUserName()); assertNotEquals(ORIGINAL_USER.getNickName(), RETURN_USER.getNickName()); assertNotEquals(ORIGINAL_USER.isActive(), RETURN_USER.isActive()); assertNotEquals(ORIGINAL_USER.getDisplayName(), RETURN_USER.getDisplayName()); assertNotEquals(ORIGINAL_USER.getExternalId(), RETURN_USER.getExternalId()); assertNotEquals(ORIGINAL_USER.getLocale(), RETURN_USER.getLocale()); assertNotEquals(ORIGINAL_USER.getPreferredLanguage(), RETURN_USER.getPreferredLanguage()); assertNotEquals(ORIGINAL_USER.getProfileUrl(), RETURN_USER.getProfileUrl()); assertNotEquals(ORIGINAL_USER.getTimezone(), RETURN_USER.getTimezone()); assertNotEquals(ORIGINAL_USER.getTitle(), RETURN_USER.getTitle()); assertNotEquals(ORIGINAL_USER.getUserType(), RETURN_USER.getUserType()); } @Test public void delete_all_single_values(){ getOriginalUser("desv"); createUpdateUserWithDeleteFields(); updateUser(); assertNull(RETURN_USER.getNickName()); assertNull(RETURN_USER.getDisplayName()); assertNull(RETURN_USER.getLocale()); assertNull(RETURN_USER.getPreferredLanguage()); assertNull(RETURN_USER.getProfileUrl()); assertNull(RETURN_USER.getTimezone()); assertNull(RETURN_USER.getTitle()); assertNull(RETURN_USER.getUserType()); } @Test public void update_password() { getOriginalUser("uasv"); createUpdateUserWithUpdateFields(); updateUser(); makeNewConnectionWithNewPassword(); } private String getUpdateUser(){ ObjectMapper mapper = new ObjectMapper(); mapper.configure( SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false ); String userAsString = null; try { userAsString = mapper.writeValueAsString(UPDATE_USER.getUserToUpdate()); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return userAsString; } public boolean isValuePartOfMultivalueList(List<MultiValuedAttribute> list, String value){ if(list != null){ for (MultiValuedAttribute actAttribute : list) { if(actAttribute.getValue().equals(value)){ return true; } } } return false; } public MultiValuedAttribute getSingleMultiValueAttribute(List<MultiValuedAttribute> multiValues, Object value){ if(multiValues != null){ for (MultiValuedAttribute actMultiValuedAttribute : multiValues) { if(actMultiValuedAttribute.getValue().equals(value)){ return actMultiValuedAttribute; } } } fail("The value " + value + " could not be found"); return null; //Can't be reached } public void getOriginalUser(String userName){ User.Builder userBuilder = new User.Builder(userName); MultiValuedAttribute email01 = new MultiValuedAttribute.Builder().setValue("hsimpson@atom-example.com").setType("work").setPrimary(true).build(); MultiValuedAttribute email02 = new MultiValuedAttribute.Builder().setValue("hsimpson@home-example.com").setType("work").build(); List<MultiValuedAttribute> emails = new ArrayList<>(); emails.add(email01); emails.add(email02); MultiValuedAttribute phoneNumber01 = new MultiValuedAttribute.Builder().setValue("+497845/1157").setType("work").setPrimary(true).build(); MultiValuedAttribute phoneNumber02 = new MultiValuedAttribute.Builder().setValue("0245817964").setType("home").build(); List<MultiValuedAttribute> phoneNumbers = new ArrayList<>(); phoneNumbers.add(phoneNumber01); phoneNumbers.add(phoneNumber02); Address simpleAddress01 = new Address.Builder().setCountry("de").setFormatted("formated address").setLocality("Berlin").setPostalCode("111111").build(); Address simpleAddress02 = new Address.Builder().setCountry("en").setFormatted("address formated").setLocality("New York").setPostalCode("123456").build(); List<Address> addresses = new ArrayList<>(); addresses.add(simpleAddress01); addresses .add(simpleAddress02); MultiValuedAttribute entitlement01 = new MultiValuedAttribute.Builder().setValue("right1").build(); MultiValuedAttribute entitlement02 = new MultiValuedAttribute.Builder().setValue("right2").build(); List<MultiValuedAttribute> entitlements = new ArrayList<>(); entitlements.add(entitlement01); entitlements.add(entitlement02); MultiValuedAttribute group01 = new MultiValuedAttribute.Builder().setValue("69e1a5dc-89be-4343-976c-b5541af249f4").build(); MultiValuedAttribute group02 = new MultiValuedAttribute.Builder().setValue("d30a77eb-d7cf-4cd1-9fb3-cc640ef09578").build(); List<MultiValuedAttribute> groups = new ArrayList<>(); groups.add(group01); groups.add(group02); MultiValuedAttribute ims01 = new MultiValuedAttribute.Builder().setValue("ims01").setType("skype").build(); MultiValuedAttribute ims02 = new MultiValuedAttribute.Builder().setValue("ims02").build(); List<MultiValuedAttribute> ims = new ArrayList<>(); ims.add(ims01); ims.add(ims02); MultiValuedAttribute photo01 = new MultiValuedAttribute.Builder().setValue("photo01.jpg").setType("thumbnail").build(); MultiValuedAttribute photo02 = new MultiValuedAttribute.Builder().setValue("photo02.jpg").build(); List<MultiValuedAttribute> photos = new ArrayList<>(); photos.add(photo01); photos.add(photo02); MultiValuedAttribute role01 = new MultiValuedAttribute.Builder().setValue("role01").setType("some").build(); MultiValuedAttribute role02 = new MultiValuedAttribute.Builder().setValue("role02").build(); List<MultiValuedAttribute> roles = new ArrayList<>(); roles.add(role01); roles.add(role02); MultiValuedAttribute certificate01 = new MultiValuedAttribute.Builder().setValue("certificate01").setType("some").build(); MultiValuedAttribute certificate02 = new MultiValuedAttribute.Builder().setValue("certificate02").build(); List<MultiValuedAttribute> certificates = new ArrayList<>(); certificates.add(certificate01); certificates.add(certificate02); userBuilder.setNickName("irgendwas") .setEmails(emails) .setPhoneNumbers(phoneNumbers) .setActive(false) .setDisplayName("irgendwas") .setLocale("de") .setPassword("geheim") .setPreferredLanguage("de") .setProfileUrl("irgendwas") .setTimezone("irgendwas") .setTitle("irgendwas") .setUserType("irgendwas") .setAddresses(addresses) .setGroups(groups) .setIms(ims) .setPhotos(photos) .setRoles(roles) .setX509Certificates(certificates) //.setEntitlements(entitlements)TODO at the second run it will fail ; User newUser = userBuilder.build(); ORIGINAL_USER = oConnector.createUser(newUser, accessToken); ID_EXISITNG_USER = UUID.fromString(ORIGINAL_USER.getId()); } private void createUpdateUserWithUpdateFields(){ UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) .updateNickname(IRRELEVANT) .updateExternalId(IRRELEVANT) .updateDisplayName(IRRELEVANT) .updatePassword(IRRELEVANT) .updateLocal(IRRELEVANT) .updatePreferredLanguage(IRRELEVANT) .updateProfileUrl(IRRELEVANT) .updateTimezone(IRRELEVANT) .updateTitle(IRRELEVANT) .updateUserType(IRRELEVANT) .setActiv(true).build(); } private void createUpdateUserWithMultiUpdateFields(){ MultiValuedAttribute email = new MultiValuedAttribute.Builder() .setValue("hsimpson@home-example.com").setType("other").setPrimary(true).build(); MultiValuedAttribute phoneNumber = new MultiValuedAttribute.Builder().setValue("0245817964").setType("other") .setPrimary(true).build(); //Now the other should not be primary anymore MultiValuedAttribute ims = new MultiValuedAttribute.Builder().setValue("ims01").setType("icq").build(); MultiValuedAttribute photo = new MultiValuedAttribute.Builder().setValue("photo01.jpg").setType("photo").build(); MultiValuedAttribute role = new MultiValuedAttribute.Builder().setValue("role01").setType("other").build(); UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .updateEmail(email) .updatePhoneNumber(phoneNumber) .updateIms(ims) .updateRole(role) .build(); } private void createUpdateUserWithDeleteFields(){ UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .deleteDisplayName() .deleteNickname() .deleteLocal() .deletePreferredLanguage() .deleteProfileUrl() .deleteTimezone() .deleteTitle() .deleteUserType() .build(); } private void createUpdateUserWithMultiDeleteFields(){ UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .deleteEmail("hsimpson@atom-example.com") //.deleteEntitlement("right2")TODO at the second run it will fail .deleteGroup(UUID.fromString("d30a77eb-d7cf-4cd1-9fb3-cc640ef09578")) .deleteIms("ims01") .deletePhoneNumber("0245817964") .deletePhoto("photo01.jpg") .deleteRole("role01") .deleteX509Certificate("certificate01") .build(); } private void createUpdateUserWithMultiAddFields(){ MultiValuedAttribute email = new MultiValuedAttribute.Builder() .setValue("mac@muster.de").setType("home").build(); MultiValuedAttribute phonenumber = new MultiValuedAttribute.Builder() .setValue("99999999991").setType("home").build(); Address newSimpleAddress = new Address.Builder().setCountry("fr").setFormatted("new Address").setLocality("New City").setPostalCode("66666").build(); MultiValuedAttribute entitlement = new MultiValuedAttribute.Builder().setValue("right3").build(); MultiValuedAttribute ims = new MultiValuedAttribute.Builder().setValue("ims03").build(); MultiValuedAttribute photo = new MultiValuedAttribute.Builder().setValue("photo03.jpg").build(); MultiValuedAttribute role = new MultiValuedAttribute.Builder().setValue("role03").build(); UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .addEmail(email) .addPhoneNumber(phonenumber) .addAddress(newSimpleAddress) //.addEntitlement(entitlement)TODO at the second run it will fail .addGroup(UUID.fromString("d30a77eb-d7cf-4cd1-9fb3-cc640ef09578")) //TODO Gruppen werden nicht gespeichert .addIms(ims) .addPhotos(photo) .addRole(role) .build(); } private void createUpdateUserWithMultiAllDeleteFields(){ UPDATE_USER = new UpdateUser.Builder(IRRELEVANT) //TODO username nur solange bug im server existiert .deleteEmails() .deleteAddresses() //.deleteEntitlements()TODO at the second run it will fail .deleteGroups() .deleteIms() .deletePhoneNumbers() .deletePhotos() .deleteRoles() .build(); } private void updateUser(){ RETURN_USER = oConnector.updateUser(ID_EXISITNG_USER, UPDATE_USER, accessToken); } private void makeNewConnectionWithNewPassword() { OsiamConnector.Builder oConBuilder = new OsiamConnector.Builder(endpointAddress). setClientId(clientId). setClientSecret(clientSecret). setGrantType(GrantType.PASSWORD). setUsername(IRRELEVANT). setPassword(IRRELEVANT); oConnector = oConBuilder.build(); oConnector.retrieveAccessToken(); } public Address getAddress(List<Address> addresses, String formated){ if(addresses != null){ for (Address actAddress : addresses) { if(actAddress.getFormatted().equals(formated)){ return actAddress; } } } fail("The address with the formated part of " + formated + " could not be found"); return null; //Can't be reached } }
package eu.diachron.qualitymetrics.intrinsic.syntacticvalidity; import java.util.ArrayList; import java.util.List; import com.hp.hpl.jena.datatypes.RDFDatatype; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.rdf.model.AnonId; import com.hp.hpl.jena.rdf.model.Bag; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.impl.StatementImpl; import com.hp.hpl.jena.sparql.core.Quad; import com.hp.hpl.jena.vocabulary.RDF; import de.unibonn.iai.eis.diachron.semantics.DQM; import de.unibonn.iai.eis.diachron.technques.probabilistic.ReservoirSampler; import de.unibonn.iai.eis.luzzu.assessment.QualityMetric; import de.unibonn.iai.eis.luzzu.datatypes.ProblemList; import de.unibonn.iai.eis.luzzu.properties.EnvironmentProperties; import de.unibonn.iai.eis.luzzu.semantics.utilities.Commons; /** * This metric checks the compatability of the literal datatype * against the lexical form of the said literal. * This metric only catches literals with a datatype * whilst untyped literals are not checked in this metric * as their lexical form cannot be validated. * * Therefore, in order to check for untyped literals, * the metric UntypedLiterals in the same dimension * checks for such quality problems. * * @author Jeremy Debattista * */ public class CompatibleDatatype implements QualityMetric { // private static Logger logger = LoggerFactory.getLogger(CompatibleDatatype.class); // Sampling of problems - testing for LOD Evaluation ReservoirSampler<ProblemReport> problemSampler = new ReservoirSampler<ProblemReport>(10000, false); private Model problemModel = ModelFactory.createDefaultModel(); private Resource bagURI = Commons.generateURI(); private Bag problemBag = problemModel.createBag(bagURI.getURI()); { //TODO: fix problemModel.createStatement(bagURI, RDF.type, problemModel.createResource(DQM.NAMESPACE+"CompatibleDatatypeException")); } private int numberCorrectLiterals = 0; private int numberIncorrectLiterals = 0; @Override public void compute(Quad quad) { Node obj = quad.getObject(); if (obj.isLiteral()){ if (obj.getLiteralDatatype() != null){ // unknown datatypes cannot be checked for their correctness, // but in the UsageOfIncorrectDomainOrRangeDatatypes metric // we check if these literals are used correctly against their // defined property. We also check for untyped literals in another metric if (this.compatibleDatatype(obj)) numberCorrectLiterals++; else { this.addToProblem(quad); numberIncorrectLiterals++; } } } } // private void addToProblem(Quad q){ // Resource anon = problemModel.createResource(AnonId.create()); // problemModel.createStatement(anon, RDF.subject, Commons.asRDFNode(q.getSubject())); // problemModel.createStatement(anon, RDF.predicate, Commons.asRDFNode(q.getPredicate())); // problemModel.createStatement(anon, RDF.object, Commons.asRDFNode(q.getObject())); // problemBag.add(anon); private void addToProblem(Quad q){ ProblemReport pr = new ProblemReport(q); Boolean isAdded = this.problemSampler.add(pr); if (!isAdded) pr = null; } @Override public double metricValue() { double metricValue = (double) numberCorrectLiterals / ((double)numberIncorrectLiterals + (double)numberCorrectLiterals); statsLogger.info("CompatibleDatatype. Dataset: {} - Total # Correct Literals : {}; # Incorrect Literals : {}; # Metric Value: {}", EnvironmentProperties.getInstance().getDatasetURI(), numberCorrectLiterals, numberIncorrectLiterals, metricValue); return metricValue; } @Override public Resource getMetricURI() { return DQM.CompatibleDatatype; } // @Override // public ProblemList<?> getQualityProblems() { // ProblemList<Model> tmpProblemList = null; // try { // if(this.problemModel != null && this.problemModel.size() > 0) { // List<Model> problemList = new ArrayList<Model>(); // problemList.add(problemModel); // tmpProblemList = new ProblemList<Model>(problemList); // } else { // tmpProblemList = new ProblemList<Model>(); // } } catch (ProblemListInitialisationException problemListInitialisationException) { // logger.error(problemListInitialisationException.getMessage()); // return tmpProblemList; @Override public ProblemList<?> getQualityProblems() { ProblemList<Model> tmpProblemList = new ProblemList<Model>(); if(this.problemSampler != null && this.problemSampler.size() > 0) { for(ProblemReport pr : this.problemSampler.getItems()){ List<Statement> stmt = pr.createProblemModel(); this.problemBag.add(stmt.get(0).getSubject()); this.problemModel.add(stmt); } tmpProblemList.getProblemList().add(this.problemModel); } else { tmpProblemList = new ProblemList<Model>(); } return tmpProblemList; } @Override public boolean isEstimate() { return false; } @Override public Resource getAgentURI() { return DQM.LuzzuProvenanceAgent; } private boolean compatibleDatatype(Node lit_obj){ RDFNode n = Commons.asRDFNode(lit_obj); Literal lt = (Literal) n; RDFDatatype dt = lt.getDatatype(); String stringValue = lt.getLexicalForm(); return dt.isValid(stringValue); } private class ProblemReport{ private Quad q; ProblemReport(Quad q){ this.q = q; } List<Statement> createProblemModel(){ List<Statement> lst = new ArrayList<Statement>(); Resource anon = ModelFactory.createDefaultModel().createResource(AnonId.create()); lst.add(new StatementImpl(anon, RDF.subject, Commons.asRDFNode(q.getSubject()))); lst.add(new StatementImpl(anon, RDF.predicate, Commons.asRDFNode(q.getPredicate()))); lst.add(new StatementImpl(anon, RDF.object, Commons.asRDFNode(q.getObject()))); return lst; } } }
package io.subutai.core.channel.impl.interceptor; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.message.Message; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; import org.apache.cxf.transport.http.AbstractHTTPDestination; import io.subutai.common.peer.PeerException; import io.subutai.common.settings.ChannelSettings; import io.subutai.common.settings.Common; import io.subutai.core.channel.impl.ChannelManagerImpl; import io.subutai.core.channel.impl.util.InterceptorState; import io.subutai.core.channel.impl.util.MessageContentUtil; import io.subutai.core.peer.api.PeerManager; public class ClientOutInterceptor extends AbstractPhaseInterceptor<Message> { // private static final Logger LOG = LoggerFactory.getLogger( ClientOutInterceptor.class ); private final PeerManager peerManager; private ChannelManagerImpl channelManagerImpl = null;
package objektwerks; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class PatternMatchTest { String matchOn(Number number) { return switch (number) { case Integer i -> i.toString(); case Long l -> l.toString(); case Double d -> d.toString(); case Float f -> f.toString(); default -> ""; }; } @Test void matchTest() { assertEquals(matchOn(1), "1"); assertEquals(matchOn(2.0), "2.0"); } }
package org.openwms.tms.service.impl; import org.openwms.common.domain.TransportUnit; /** * A TransportOrderStateDelegate. Is called after state changes on a * TransportOrder have been performed. * * @author <a href="mailto:russelltina@users.sourceforge.net">Tina Russell</a> * @version $Revision$ * @since 0.1 */ public interface TransportOrderStateDelegate { /** * An action that should be triggered after a TransportOrder has been * created. * * @param transportUnit * The {@link TransportUnit} of the corresponding TransportOrder */ void afterCreation(TransportUnit transportUnit); /** * An action that should be triggered after a TransportOrder has been * canceled. * * @param id * The id of the TransportOrder */ void onCancel(Long id); /** * An action that should be triggered after a TransportOrder has been * finished successfully. * * @param id * The id of the TransportOrder */ void afterFinish(Long id); /** * An action that should be triggered after a TransportOrder has been set on * failure. * * @param id * The id of the TransportOrder */ void onFailure(Long id); /** * An action that should be triggered after a TransportOrder has been * interrupted. * * @param id * The id of the TransportOrder */ void onInterrupt(Long id); }
package org.eclipsecon.it; import hudson.model.FreeStyleBuild; import hudson.model.Result; import hudson.model.FreeStyleProject; import java.util.concurrent.Future; import org.eclipsecon.FrenchBadgeAction; import org.eclipsecon.HelloWorldBuilder; import org.junit.Test; import org.jvnet.hudson.test.HudsonTestCase; import org.jvnet.hudson.test.recipes.LocalData; public class FrenchTest extends HudsonTestCase { @Test @LocalData public void test_build_was_french() throws Exception { FreeStyleProject job1 = createFreeStyleProject("job1"); job1.getBuildersList().add(new HelloWorldBuilder("anthony")); Future<FreeStyleBuild> scheduleBuild2 = job1.scheduleBuild2(0); FreeStyleBuild freeStyleBuild = scheduleBuild2.get(); assertBuildStatus(Result.SUCCESS, freeStyleBuild); assertNotNull(freeStyleBuild.getAction(FrenchBadgeAction.class)); assertTrue(freeStyleBuild.getLog(100).get(1).contains("Bonjour")); } }
package org.apereo.cas.ticket.registry; import org.apereo.cas.authentication.CoreAuthenticationTestUtils; import org.apereo.cas.config.CasCoreAuthenticationConfiguration; import org.apereo.cas.config.CasCoreAuthenticationHandlersConfiguration; import org.apereo.cas.config.CasCoreAuthenticationMetadataConfiguration; import org.apereo.cas.config.CasCoreAuthenticationPolicyConfiguration; import org.apereo.cas.config.CasCoreAuthenticationPrincipalConfiguration; import org.apereo.cas.config.CasCoreAuthenticationServiceSelectionStrategyConfiguration; import org.apereo.cas.config.CasCoreAuthenticationSupportConfiguration; import org.apereo.cas.config.CasCoreConfiguration; import org.apereo.cas.config.CasCoreHttpConfiguration; import org.apereo.cas.config.CasCoreServicesAuthenticationConfiguration; import org.apereo.cas.config.CasCoreServicesConfiguration; import org.apereo.cas.config.CasCoreTicketCatalogConfiguration; import org.apereo.cas.config.CasCoreTicketsConfiguration; import org.apereo.cas.config.CasCoreUtilConfiguration; import org.apereo.cas.config.CasCoreWebConfiguration; import org.apereo.cas.config.CasPersonDirectoryConfiguration; import org.apereo.cas.config.DynamoDbTicketRegistryConfiguration; import org.apereo.cas.config.DynamoDbTicketRegistryTicketCatalogConfiguration; import org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration; import org.apereo.cas.logout.config.CasCoreLogoutConfiguration; import org.apereo.cas.mock.MockTicketGrantingTicket; import org.apereo.cas.ticket.Ticket; import org.apereo.cas.util.CollectionUtils; import org.apereo.cas.util.junit.ConditionalIgnore; import org.apereo.cas.util.junit.ConditionalSpringRunner; import org.apereo.cas.util.junit.RunningContinuousIntegrationCondition; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; import org.springframework.test.context.TestPropertySource; import java.util.Arrays; import java.util.Collection; import java.util.Map; import static org.junit.Assert.*; /** * This is {@link DynamoDbTicketRegistryFacilitatorTests}. * * @author Misagh Moayyed * @since 5.3.0 */ @RunWith(ConditionalSpringRunner.class) @ConditionalIgnore(condition = RunningContinuousIntegrationCondition.class, port = 8000) @TestPropertySource(locations = "classpath:/dynamodb-ticketregistry.properties") @SpringBootTest(classes = { DynamoDbTicketRegistryConfiguration.class, DynamoDbTicketRegistryTicketCatalogConfiguration.class, CasCoreTicketsConfiguration.class, CasCoreTicketCatalogConfiguration.class, CasCoreLogoutConfiguration.class, CasCoreHttpConfiguration.class, CasCoreServicesConfiguration.class, CasCoreAuthenticationConfiguration.class, CasCoreServicesAuthenticationConfiguration.class, CasCoreConfiguration.class, CasCoreWebConfiguration.class, CasCoreUtilConfiguration.class, CasWebApplicationServiceFactoryConfiguration.class, CasCoreAuthenticationServiceSelectionStrategyConfiguration.class, CasCoreAuthenticationHandlersConfiguration.class, CasCoreAuthenticationMetadataConfiguration.class, CasCoreAuthenticationPolicyConfiguration.class, CasCoreAuthenticationPrincipalConfiguration.class, CasCoreAuthenticationSupportConfiguration.class, CasPersonDirectoryConfiguration.class, RefreshAutoConfiguration.class}) public class DynamoDbTicketRegistryFacilitatorTests { @Rule public ExpectedException thrown = ExpectedException.none(); @Autowired @Qualifier("dynamoDbTicketRegistryFacilitator") private DynamoDbTicketRegistryFacilitator dynamoDbTicketRegistryFacilitator; @Test public void verifyBuildAttributeMap() { final Ticket ticket = new MockTicketGrantingTicket("casuser", CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(), CollectionUtils.wrap("name", "CAS")); final Map map = dynamoDbTicketRegistryFacilitator.buildTableAttributeValuesMapFromTicket(ticket, ticket); assertFalse(map.isEmpty()); Arrays.stream(DynamoDbTicketRegistryFacilitator.ColumnNames.values()) .forEach(c -> assertTrue(map.containsKey(c.getColumnName()))); } @Test public void verifyTicketOperations() { dynamoDbTicketRegistryFacilitator.createTicketTables(true); final Ticket ticket = new MockTicketGrantingTicket("casuser", CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(), CollectionUtils.wrap("name", "CAS")); dynamoDbTicketRegistryFacilitator.put(ticket, ticket); final Collection col = dynamoDbTicketRegistryFacilitator.getAll(); assertFalse(col.isEmpty()); final Ticket ticketFetched = dynamoDbTicketRegistryFacilitator.get(ticket.getId(), ticket.getId()); assertEquals(ticket, ticketFetched); assertFalse(dynamoDbTicketRegistryFacilitator.delete("badticket", "badticket")); assertTrue(dynamoDbTicketRegistryFacilitator.deleteAll() > 0); } }
package org.eclipse.birt.report.designer.ui.cubebuilder.dialog; import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.ui.cubebuilder.nls.Messages; import org.eclipse.birt.report.designer.ui.cubebuilder.provider.CubeExpressionProvider; import org.eclipse.birt.report.designer.ui.dialogs.BaseDialog; import org.eclipse.birt.report.designer.ui.dialogs.ExpressionBuilder; import org.eclipse.birt.report.designer.ui.util.ExceptionUtil; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.RuleHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.structures.Rule; import org.eclipse.birt.report.model.api.olap.TabularLevelHandle; import org.eclipse.birt.report.model.elements.interfaces.ILevelModel; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.resource.StringConverter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; public class LevelStaticAttributeDialog extends BaseDialog { private Text errorMessageText; private Text nameText; private Text expressionText; public LevelStaticAttributeDialog( String title ) { super( title ); } private TabularLevelHandle input; private RuleHandle rule; public void setInput( TabularLevelHandle input ) { this.input = input; } public void setInput( TabularLevelHandle input, RuleHandle rule ) { this.input = input; this.rule = rule; } protected Control createDialogArea( Composite parent ) { Composite composite = (Composite) super.createDialogArea( parent ); Composite container = new Composite( composite, SWT.NONE ); container.setLayoutData( new GridData( GridData.FILL_BOTH ) ); GridLayout layout = new GridLayout( ); layout.numColumns = 3; layout.marginWidth = layout.marginHeight = 0; container.setLayout( layout ); Label nameLabel = new Label( container, SWT.WRAP ); nameLabel.setText( Messages.getString( "LevelStaticAttributeDialog.Label.Member" ) ); //$NON-NLS-1$ nameLabel.setLayoutData( new GridData( ) ); nameLabel.setFont( parent.getFont( ) ); nameText = new Text( container, SWT.BORDER | SWT.SINGLE ); GridData gd = new GridData( GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL ); gd.horizontalSpan = 2; gd.widthHint = 250; nameText.setLayoutData( gd ); nameText.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { checkButtonStatus( ); } } ); Label expressionLabel = new Label( container, SWT.WRAP ); expressionLabel.setText( Messages.getString( "LevelStaticAttributeDialog.Label.Expression" ) ); //$NON-NLS-1$ expressionLabel.setLayoutData( new GridData( ) ); expressionLabel.setFont( parent.getFont( ) ); expressionText = new Text( container, SWT.BORDER | SWT.SINGLE ); expressionText.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); Button expressionButton = new Button( container, SWT.PUSH ); expressionButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { handleExpressionButtonSelectEvent( ); } } ); UIUtil.setExpressionButtonImage( expressionButton ); errorMessageText = new Text( container, SWT.READ_ONLY | SWT.WRAP ); gd = new GridData( GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL ); gd.horizontalSpan = 3; errorMessageText.setLayoutData( gd ); errorMessageText.setBackground( errorMessageText.getDisplay( ) .getSystemColor( SWT.COLOR_WIDGET_BACKGROUND ) ); applyDialogFont( composite ); UIUtil.bindHelp( parent, IHelpContextIds.LEVEL_STATIC_ATTRIBUTE_DIALOG ); initDialog( ); return composite; } protected boolean initDialog( ) { if ( rule != null ) { nameText.setText( DEUtil.resolveNull( rule.getDisplayExpression( ) ) ); expressionText.setText( DEUtil.resolveNull( rule.getRuleExpression( ) ) ); } return super.initDialog( ); } @Override protected Control createButtonBar( Composite parent ) { Control bar = super.createButtonBar( parent ); checkButtonStatus( ); return bar; } private void checkButtonStatus( ) { if ( nameText.getText( ).trim( ).length( ) == 0 ) { if ( getButton( IDialogConstants.OK_ID ) != null ) { getButton( IDialogConstants.OK_ID ).setEnabled( false ); setErrorMessage( Messages.getString( "LevelStaticAttributeDialog.Error.Message" ) ); //$NON-NLS-1$ } } else { if ( getButton( IDialogConstants.OK_ID ) != null ) { getButton( IDialogConstants.OK_ID ).setEnabled( true ); setErrorMessage( null ); } } } protected void handleExpressionButtonSelectEvent( ) { ExpressionBuilder expression = new ExpressionBuilder( expressionText.getText( ) ); expression.setExpressionProvider( new CubeExpressionProvider( input ) ); if ( expression.open( ) == OK ) { if ( expression.getResult( ) != null && expressionText != null ) expressionText.setText( expression.getResult( ) ); } } public void setErrorMessage( String errorMessage ) { if ( errorMessageText != null && !errorMessageText.isDisposed( ) ) { errorMessageText.setText( errorMessage == null ? " \n " : errorMessage ); //$NON-NLS-1$ boolean hasError = errorMessage != null && ( StringConverter.removeWhiteSpaces( errorMessage ) ).length( ) > 0; errorMessageText.setEnabled( hasError ); errorMessageText.setVisible( hasError ); errorMessageText.getParent( ).update( ); Control button = getButton( IDialogConstants.OK_ID ); if ( button != null ) { button.setEnabled( errorMessage == null ); } } } protected void okPressed( ) { if ( rule != null ) { if ( nameText.getText( ).trim( ).length( ) > 0 ) rule.setDisplayExpression( nameText.getText( ).trim( ) ); rule.setRuleExpression( expressionText.getText( ).trim( ) ); } else { Rule rule = StructureFactory.createRule( ); rule.setProperty( Rule.DISPLAY_EXPRE_MEMBER, nameText.getText( ) .trim( ) ); rule.setProperty( Rule.RULE_EXPRE_MEMBER, expressionText.getText( ) .trim( ) ); try { input.getPropertyHandle( ILevelModel.STATIC_VALUES_PROP ) .addItem( rule ); } catch ( SemanticException e ) { ExceptionUtil.handle( e ); } } super.okPressed( ); } }
package org.eclipse.birt.report.designer.internal.ui.palette; import org.eclipse.birt.report.designer.core.DesignerConstants; import org.eclipse.birt.report.designer.core.IReportElementConstants; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.model.views.data.DataSetItemModel; import org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest; import org.eclipse.birt.report.designer.internal.ui.command.CommandUtils; import org.eclipse.birt.report.designer.internal.ui.dnd.DNDLocation; import org.eclipse.birt.report.designer.internal.ui.dnd.DNDService; import org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportDesignEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.tools.AbstractToolHandleExtends; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.tools.LibraryElementsToolHandleExtends; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.tools.ReportCreationTool; import org.eclipse.birt.report.designer.internal.ui.extension.experimental.EditpartExtensionManager; import org.eclipse.birt.report.designer.internal.ui.extension.experimental.PaletteEntryExtension; import org.eclipse.birt.report.designer.internal.ui.palette.BasePaletteFactory.DataSetColumnToolExtends; import org.eclipse.birt.report.designer.internal.ui.palette.BasePaletteFactory.DataSetToolExtends; import org.eclipse.birt.report.designer.internal.ui.palette.BasePaletteFactory.DimensionHandleToolExtends; import org.eclipse.birt.report.designer.internal.ui.palette.BasePaletteFactory.ImageToolExtends; import org.eclipse.birt.report.designer.internal.ui.palette.BasePaletteFactory.MeasureHandleToolExtends; import org.eclipse.birt.report.designer.internal.ui.palette.BasePaletteFactory.ParameterToolExtends; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.internal.ui.views.actions.InsertInLayoutAction; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.util.DNDUtil; import org.eclipse.birt.report.model.api.CellHandle; import org.eclipse.birt.report.model.api.CommandStack; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DataSourceHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.EmbeddedImageHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.ImageHandle; import org.eclipse.birt.report.model.api.LibraryHandle; import org.eclipse.birt.report.model.api.MasterPageHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ParameterHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.eclipse.birt.report.model.api.ResultSetColumnHandle; import org.eclipse.birt.report.model.api.RowHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.ThemeHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.structures.EmbeddedImage; import org.eclipse.birt.report.model.api.olap.DimensionHandle; import org.eclipse.birt.report.model.api.olap.MeasureHandle; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPartViewer; import org.eclipse.gef.Request; import org.eclipse.gef.commands.Command; import org.eclipse.gef.dnd.TemplateTransfer; import org.eclipse.gef.dnd.TemplateTransferDropTargetListener; import org.eclipse.gef.requests.CreationFactory; import org.eclipse.jface.util.Assert; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTargetEvent; /** * Drag&Drop listener */ public class ReportTemplateTransferDropTargetListener extends TemplateTransferDropTargetListener { private static final String TRANS_LABEL_CREATE_ELEMENT = Messages.getString( "ReportTemplateTransferDropTargetListener.transLabel.createElement" ); //$NON-NLS-1$ private static final String IMG_TRANS_MSG = Messages.getString( "ImageEditPart.trans.editImage" ); //$NON-NLS-1$ /** * Constructor * * @param viewer */ public ReportTemplateTransferDropTargetListener( EditPartViewer viewer ) { super( viewer ); } /* * (non-Javadoc) * * @see * org.eclipse.gef.dnd.TemplateTransferDropTargetListener#getFactory(java * .lang.Object) */ protected CreationFactory getFactory( Object template ) { if ( handleValidateDrag( template ) ) { if ( template instanceof String ) { return new ReportElementFactory( template ); } return new ReportElementFactory( getSingleTransferData( template ), template ); } return null; } /* * (non-Javadoc) * * @see org.eclipse.gef.dnd.AbstractTransferDropTargetListener#handleDrop() */ protected void handleDrop( ) { updateTargetRequest( ); updateTargetEditPart( ); // use new DNDService if ( DNDService.getInstance( ) .performDrop( TemplateTransfer.getInstance( ).getTemplate( ), getTargetEditPart( ), DND.DROP_DEFAULT, new DNDLocation( getDropLocation( ) ) ) ) { return; } boolean isScalarparameter = false; boolean isResultSetColumn = false; boolean isEmbeddImage = false; final Object template = TemplateTransfer.getInstance( ).getTemplate( ); Assert.isNotNull( template ); Assert.isTrue( handleValidateDrag( template ) ); AbstractToolHandleExtends preHandle = null; String transName = null; if ( template instanceof String ) { PaletteEntryExtension[] entries = EditpartExtensionManager.getPaletteEntries( ); if ( template.toString( ) .startsWith( IReportElementConstants.REPORT_ELEMENT_EXTENDED ) ) { String extensionName = template.toString( ) .substring( IReportElementConstants.REPORT_ELEMENT_EXTENDED.length( ) ); for ( int i = 0; i < entries.length; i++ ) { if ( entries[i].getItemName( ).equals( extensionName ) ) { try { CommandUtils.setVariable( "targetEditPart", //$NON-NLS-1$ getTargetEditPart( ) ); CommandUtils.setVariable( "request", getTargetRequest( ) ); //$NON-NLS-1$ getCreateRequest( ).getExtendedData( ) .put( DesignerConstants.KEY_NEWOBJECT, entries[i].executeCreate( ) ); selectAddedObject( ); return; } catch ( Exception e ) { ExceptionHandler.handle( e ); } } } } transName = TRANS_LABEL_CREATE_ELEMENT; preHandle = BasePaletteFactory.getAbstractToolHandleExtendsFromPaletteName( template ); } else if ( handleValidateInsert( template ) ) { transName = InsertInLayoutAction.DISPLAY_TEXT; Object objectType = getFactory( template ).getObjectType( ); if ( objectType instanceof DataSetHandle ) { preHandle = new DataSetToolExtends( ); } else if ( objectType instanceof DataSetItemModel ) { preHandle = new DataSetColumnToolExtends( ); } else if ( objectType instanceof ResultSetColumnHandle ) { isResultSetColumn = true; preHandle = new DataSetColumnToolExtends( ); } else if ( objectType instanceof ScalarParameterHandle ) { isScalarparameter = true; preHandle = new ParameterToolExtends( ); } else if ( objectType instanceof DimensionHandle ) { preHandle = new DimensionHandleToolExtends( ); } else if ( objectType instanceof MeasureHandle ) { preHandle = new MeasureHandleToolExtends( ); } } else if ( handleValidateLibrary( template ) ) { Object dragObj = getSingleTransferData( template ); if ( dragObj instanceof EmbeddedImageHandle ) { isEmbeddImage = true; preHandle = new ImageToolExtends( ); } else preHandle = new LibraryElementsToolHandleExtends( (DesignElementHandle) dragObj ); } else if ( handleValidateOutline( template ) ) { Object dragObj = getSingleTransferData( template ); if ( dragObj instanceof EmbeddedImageHandle ) { isEmbeddImage = true; preHandle = new ImageToolExtends( ); } } if ( preHandle != null ) { CommandStack stack = SessionHandleAdapter.getInstance( ) .getCommandStack( ); stack.startTrans( transName ); preHandle.setRequest( this.getCreateRequest( ) ); preHandle.setTargetEditPart( getTargetEditPart( ) ); if ( isEmbeddImage ) { Object dragObj = getSingleTransferData( template ); if ( dragObj instanceof EmbeddedImageHandle ) { if ( ( (EmbeddedImageHandle) dragObj ).getElementHandle( ) .getRoot( ) instanceof LibraryHandle ) { ModuleHandle moduleHandle = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ); LibraryHandle library = (LibraryHandle) ( (EmbeddedImageHandle) dragObj ).getElementHandle( ) .getRoot( ); try { if ( UIUtil.includeLibrary( moduleHandle, library ) ) { EmbeddedImage image = StructureFactory.newEmbeddedImageFrom( (EmbeddedImageHandle) dragObj, moduleHandle ); image.setType( ( (EmbeddedImageHandle) dragObj ).getType( ) ); DNDUtil.addEmbeddedImageHandle( getTargetEditPart( ).getModel( ), image ); } } catch ( Exception e ) { ExceptionHandler.handle( e ); } } } } Command command = this.getCommand( ); if ( command != null && command.canExecute( ) ) { if ( !( preHandle.preHandleMouseUp( ) ) ) { stack.rollback( ); return; } } boolean isTheme = checkTheme( preHandle, getSingleTransferData( template ) ); if ( !isTheme ) { super.handleDrop( ); // fix bugzilla#145284 if ( !preHandle.postHandleCreation( ) ) { stack.rollback( ); return; } Request request = new Request( ); if ( getCreateRequest( ).getExtendedData( ) .get( DesignerConstants.NEWOBJECT_FROM_LIBRARY ) != null ) { request.getExtendedData( ) .put( DesignerConstants.NEWOBJECT_FROM_LIBRARY, getCreateRequest( ).getExtendedData( ) .get( DesignerConstants.NEWOBJECT_FROM_LIBRARY ) ); } if ( isScalarparameter || isResultSetColumn ) { request.setType( ReportRequest.CREATE_SCALARPARAMETER_OR_RESULTSETCOLUMN ); Object model = getCreateRequest( ).getExtendedData( ) .get( DesignerConstants.KEY_NEWOBJECT ); if ( model instanceof GroupHandle ) { GroupHandle handle = (GroupHandle) model; getCreateRequest( ).getExtendedData( ) .put( DesignerConstants.KEY_NEWOBJECT, ( (CellHandle) ( (RowHandle) handle.getHeader( ) .get( 0 ) ).getCells( ).get( 0 ) ).getContent( ) .get( 0 ) ); } selectAddedObject( request ); } else if ( isEmbeddImage ) { Object dragObj = getSingleTransferData( template ); final Object model = getCreateRequest( ).getExtendedData( ) .get( DesignerConstants.KEY_NEWOBJECT ); try { ( (ImageHandle) model ).setImageName( ( (EmbeddedImageHandle) dragObj ).getName( ) ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } request.setType( ReportRequest.SELECTION ); selectAddedObject( request ); } else { request.setType( ReportRequest.CREATE_ELEMENT ); selectAddedObject( request ); } } stack.commit( ); } } private boolean checkTheme( AbstractToolHandleExtends preHandle, Object obj ) { if ( preHandle instanceof LibraryElementsToolHandleExtends && obj instanceof ThemeHandle ) { return true; } return false; } /** * Validates drag source from palette, layout, or data view * * @param dragObj * @return validate result */ private boolean handleValidateDrag( Object dragObj ) { if ( DNDService.getInstance( ) .validDrop( TemplateTransfer.getInstance( ).getTemplate( ), getTargetEditPart( ), DND.DROP_DEFAULT, new DNDLocation( getDropLocation( ) ) ) ) { return true; } return dragObj != null && ( handleValidatePalette( dragObj ) || handleValidateOutline( dragObj ) || handleValidateInsert( dragObj ) || handleValidateLibrary( dragObj ) ); } private boolean handleValidatePalette( Object dragObj ) { return dragObj instanceof String && ( getTargetEditPart( ) == null || ReportCreationTool.handleValidatePalette( dragObj, getTargetEditPart( ) ) ); } /** * Validates drag from data view to layout * * @param template * @return validate result */ private boolean handleValidateInsert( Object template ) { return InsertInLayoutUtil.handleValidateInsert( template ) && ( getTargetEditPart( ) == null || InsertInLayoutUtil.handleValidateInsertToLayout( template, getTargetEditPart( ) ) ); } // test for the crosstab private boolean isCrossType( Object obj ) { return obj instanceof DimensionHandle || obj instanceof MeasureHandle; } /** * Validates drag source of outline view and drop target of layout * * @return validate result */ private boolean handleValidateOutline( Object dragSource ) { EditPart targetEditPart = getTargetEditPart( ); if ( targetEditPart == null ) { return true; } if ( dragSource != null ) { Object[] dragObjs; if ( dragSource instanceof Object[] ) { dragObjs = (Object[]) dragSource; } else { dragObjs = new Object[]{ dragSource }; } if ( dragObjs.length == 0 ) { return false; } for ( int i = 0; i < dragObjs.length; i++ ) { if ( dragObjs[i] instanceof EmbeddedImageHandle && !( ( (EmbeddedImageHandle) dragObjs[i] ).getElementHandle( ) .getRoot( ) instanceof LibraryHandle ) ) { return true; } else { return false; } } } return false; } private boolean handleValidateLibrary( Object dragObj ) { EditPart targetEditPart = getTargetEditPart( ); if ( targetEditPart == null ) { return true; } if ( dragObj != null ) { Object[] dragObjs; if ( dragObj instanceof Object[] ) { dragObjs = (Object[]) dragObj; } else { dragObjs = new Object[]{ dragObj }; } if ( dragObjs.length == 0 ) { return false; } for ( int i = 0; i < dragObjs.length; i++ ) { dragObj = dragObjs[i]; if ( dragObj instanceof ReportElementHandle ) { if ( ( (ReportElementHandle) dragObj ).getRoot( ) instanceof LibraryHandle ) { // enable DataSetHandle,ParameterHandle to drag in lib // explorer view. // 180426 disabled drop to library editor if ( ( dragObj instanceof DataSetHandle || dragObj instanceof ParameterHandle ) && getTargetEditPart( ) == null ) return true; if ( dragObj instanceof DataSourceHandle || dragObj instanceof MasterPageHandle ) { return targetEditPart instanceof ReportDesignEditPart && ( (ReportElementHandle) dragObj ).getRoot( ) != targetEditPart.getModel( ); } if ( !DNDUtil.handleValidateTargetCanContain( targetEditPart.getModel( ), dragObj ) || !DNDUtil.handleValidateTargetCanContainMore( targetEditPart.getModel( ), 1 ) ) { return false; } } else { return false; } } else if ( dragObj instanceof EmbeddedImageHandle && ( (EmbeddedImageHandle) dragObj ).getElementHandle( ) .getRoot( ) instanceof LibraryHandle ) { int canContain = DNDUtil.handleValidateTargetCanContain( targetEditPart.getModel( ), dragObj, true ); return canContain == DNDUtil.CONTAIN_THIS; } else { return false; } } Object root = getTargetEditPart( ).getRoot( ).getContents( ).getModel( ); return root instanceof ReportDesignHandle || root instanceof LibraryHandle; //return true; } return false; } /* * (non-Javadoc) * * @see * org.eclipse.gef.dnd.AbstractTransferDropTargetListener#dragOver(org.eclipse * .swt.dnd.DropTargetEvent) */ public void dragOver( DropTargetEvent event ) { super.dragOver( event ); if ( !handleValidateDrag( TemplateTransfer.getInstance( ).getTemplate( ) ) ) { event.detail = DND.DROP_NONE; } } /* * Add the newly created object to the viewer's selected objects. */ private void selectAddedObject( ) { final Object model = getCreateRequest( ).getExtendedData( ) .get( DesignerConstants.KEY_NEWOBJECT ); final EditPartViewer viewer = getViewer( ); viewer.getControl( ).setFocus( ); ReportCreationTool.selectAddedObject( model, viewer ); } /* * Add the newly created object(ScalarParameter or ResultSetColumn) to the * viewer's selected objects. */ private void selectAddedObject( Request request ) { final Object model = getCreateRequest( ).getExtendedData( ) .get( DesignerConstants.KEY_NEWOBJECT ); final EditPartViewer viewer = getViewer( ); viewer.getControl( ).setFocus( ); ReportCreationTool.selectAddedObject( model, viewer, request ); } /** * Gets single transfer data from TemplateTransfer * * @param template * object transfered by TemplateTransfer * @return single transfer data in array or itself */ private Object getSingleTransferData( Object template ) { if ( template instanceof Object[] ) { return ( (Object[]) template )[0]; } return template; } }
package org.eclipse.smarthome.core.thing.internal.firmware; import static org.eclipse.smarthome.core.thing.firmware.FirmwareStatusInfo.*; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.config.core.validation.ConfigDescriptionValidator; import org.eclipse.smarthome.config.core.validation.ConfigValidationException; import org.eclipse.smarthome.core.common.SafeCaller; import org.eclipse.smarthome.core.common.ThreadPoolManager; import org.eclipse.smarthome.core.events.Event; import org.eclipse.smarthome.core.events.EventFilter; import org.eclipse.smarthome.core.events.EventPublisher; import org.eclipse.smarthome.core.events.EventSubscriber; import org.eclipse.smarthome.core.i18n.LocaleProvider; import org.eclipse.smarthome.core.i18n.TranslationProvider; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingUID; import org.eclipse.smarthome.core.thing.binding.firmware.Firmware; import org.eclipse.smarthome.core.thing.binding.firmware.FirmwareUpdateBackgroundTransferHandler; import org.eclipse.smarthome.core.thing.binding.firmware.FirmwareUpdateHandler; import org.eclipse.smarthome.core.thing.events.ThingStatusInfoChangedEvent; import org.eclipse.smarthome.core.thing.firmware.FirmwareEventFactory; import org.eclipse.smarthome.core.thing.firmware.FirmwareRegistry; import org.eclipse.smarthome.core.thing.firmware.FirmwareStatus; import org.eclipse.smarthome.core.thing.firmware.FirmwareStatusInfo; import org.eclipse.smarthome.core.thing.firmware.FirmwareUpdateService; import org.eclipse.smarthome.core.util.BundleResolver; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Modified; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Component(immediate = true, service = { EventSubscriber.class, FirmwareUpdateService.class }) @NonNullByDefault public final class FirmwareUpdateServiceImpl implements FirmwareUpdateService, EventSubscriber { private static final String THREAD_POOL_NAME = FirmwareUpdateServiceImpl.class.getSimpleName(); private static final Set<String> SUPPORTED_TIME_UNITS = Collections.unmodifiableSet( Stream.of(TimeUnit.SECONDS.name(), TimeUnit.MINUTES.name(), TimeUnit.HOURS.name(), TimeUnit.DAYS.name()) .collect(Collectors.toSet())); protected static final String PERIOD_CONFIG_KEY = "period"; protected static final String DELAY_CONFIG_KEY = "delay"; protected static final String TIME_UNIT_CONFIG_KEY = "timeUnit"; private static final String CONFIG_DESC_URI_KEY = "system:firmware-status-info-job"; private final Logger logger = LoggerFactory.getLogger(FirmwareUpdateServiceImpl.class); private int firmwareStatusInfoJobPeriod = 3600; private int firmwareStatusInfoJobDelay = 3600; private TimeUnit firmwareStatusInfoJobTimeUnit = TimeUnit.SECONDS; private @Nullable ScheduledFuture<?> firmwareStatusInfoJob; protected int timeout = 30 * 60 * 1000; private final Set<String> subscribedEventTypes = Collections.singleton(ThingStatusInfoChangedEvent.TYPE); private final Map<ThingUID, FirmwareStatusInfo> firmwareStatusInfoMap = new ConcurrentHashMap<>(); private final Map<ThingUID, ProgressCallbackImpl> progressCallbackMap = new ConcurrentHashMap<>(); private final List<FirmwareUpdateHandler> firmwareUpdateHandlers = new CopyOnWriteArrayList<>(); private @NonNullByDefault({}) FirmwareRegistry firmwareRegistry; private @NonNullByDefault({}) EventPublisher eventPublisher; private @NonNullByDefault({}) TranslationProvider i18nProvider; private @NonNullByDefault({}) LocaleProvider localeProvider; private @NonNullByDefault({}) SafeCaller safeCaller; private @NonNullByDefault({}) ConfigDescriptionValidator configDescriptionValidator; private @NonNullByDefault({}) BundleResolver bundleResolver; private final Runnable firmwareStatusRunnable = new Runnable() { @Override public void run() { logger.debug("Running firmware status check."); for (FirmwareUpdateHandler firmwareUpdateHandler : firmwareUpdateHandlers) { try { logger.debug("Executing firmware status check for thing with UID {}.", firmwareUpdateHandler.getThing().getUID()); Firmware latestFirmware = getLatestSuitableFirmware(firmwareUpdateHandler.getThing()); FirmwareStatusInfo newFirmwareStatusInfo = getFirmwareStatusInfo(firmwareUpdateHandler, latestFirmware); processFirmwareStatusInfo(firmwareUpdateHandler, newFirmwareStatusInfo, latestFirmware); } catch (Exception e) { logger.debug("Exception occurred during firmware status check.", e); } } } }; @Activate protected void activate(Map<String, Object> config) { modified(config); } @Modified protected synchronized void modified(Map<String, Object> config) { logger.debug("Modifying the configuration of the firmware update service."); if (!isValid(config)) { return; } cancelFirmwareUpdateStatusInfoJob(); firmwareStatusInfoJobPeriod = config.containsKey(PERIOD_CONFIG_KEY) ? (Integer) config.get(PERIOD_CONFIG_KEY) : firmwareStatusInfoJobPeriod; firmwareStatusInfoJobDelay = config.containsKey(DELAY_CONFIG_KEY) ? (Integer) config.get(DELAY_CONFIG_KEY) : firmwareStatusInfoJobDelay; firmwareStatusInfoJobTimeUnit = config.containsKey(TIME_UNIT_CONFIG_KEY) ? TimeUnit.valueOf((String) config.get(TIME_UNIT_CONFIG_KEY)) : firmwareStatusInfoJobTimeUnit; if (!firmwareUpdateHandlers.isEmpty()) { createFirmwareUpdateStatusInfoJob(); } } @Deactivate protected void deactivate() { cancelFirmwareUpdateStatusInfoJob(); firmwareStatusInfoMap.clear(); progressCallbackMap.clear(); } @Override @Nullable public FirmwareStatusInfo getFirmwareStatusInfo(ThingUID thingUID) { ParameterChecks.checkNotNull(thingUID, "Thing UID"); FirmwareUpdateHandler firmwareUpdateHandler = getFirmwareUpdateHandler(thingUID); if (firmwareUpdateHandler == null) { logger.trace("No firmware update handler available for thing with UID {}.", thingUID); return null; } Firmware latestFirmware = getLatestSuitableFirmware(firmwareUpdateHandler.getThing()); FirmwareStatusInfo firmwareStatusInfo = getFirmwareStatusInfo(firmwareUpdateHandler, latestFirmware); processFirmwareStatusInfo(firmwareUpdateHandler, firmwareStatusInfo, latestFirmware); return firmwareStatusInfo; } @Override public void updateFirmware(final ThingUID thingUID, final String firmwareVersion, final @Nullable Locale locale) { ParameterChecks.checkNotNull(thingUID, "Thing UID"); ParameterChecks.checkNotNullOrEmpty(firmwareVersion, "Firmware version"); final FirmwareUpdateHandler firmwareUpdateHandler = getFirmwareUpdateHandler(thingUID); if (firmwareUpdateHandler == null) { throw new IllegalArgumentException( String.format("There is no firmware update handler for thing with UID %s.", thingUID)); } final Thing thing = firmwareUpdateHandler.getThing(); final Firmware firmware = getFirmware(thing, firmwareVersion); validateFirmwareUpdateConditions(firmwareUpdateHandler, firmware); final Locale currentLocale = locale != null ? locale : localeProvider.getLocale(); final ProgressCallbackImpl progressCallback = new ProgressCallbackImpl(firmwareUpdateHandler, eventPublisher, i18nProvider, bundleResolver, thingUID, firmware, currentLocale); progressCallbackMap.put(thingUID, progressCallback); logger.debug("Starting firmware update for thing with UID {} and firmware {}", thingUID, firmware); safeCaller.create(firmwareUpdateHandler, FirmwareUpdateHandler.class).withTimeout(timeout).withAsync() .onTimeout(() -> { logger.error("Timeout occurred for firmware update of thing with UID {} and firmware {}.", thingUID, firmware); progressCallback.failedInternal("timeout-error"); }).onException(e -> { logger.error( "Unexpected exception occurred for firmware update of thing with UID {} and firmware {}.", thingUID, firmware, e.getCause()); progressCallback.failedInternal("unexpected-handler-error"); }).build().updateFirmware(firmware, progressCallback); } @Override public void cancelFirmwareUpdate(final ThingUID thingUID) { ParameterChecks.checkNotNull(thingUID, "Thing UID"); final FirmwareUpdateHandler firmwareUpdateHandler = getFirmwareUpdateHandler(thingUID); if (firmwareUpdateHandler == null) { throw new IllegalArgumentException( String.format("There is no firmware update handler for thing with UID %s.", thingUID)); } final ProgressCallbackImpl progressCallback = getProgressCallback(thingUID); logger.debug("Cancelling firmware update for thing with UID {}.", thingUID); safeCaller.create(firmwareUpdateHandler, FirmwareUpdateHandler.class).withTimeout(timeout).withAsync() .onTimeout(() -> { logger.error("Timeout occurred while cancelling firmware update of thing with UID {}.", thingUID); progressCallback.failedInternal("timeout-error-during-cancel"); }).onException(e -> { logger.error("Unexpected exception occurred while cancelling firmware update of thing with UID {}.", thingUID, e.getCause()); progressCallback.failedInternal("unexpected-handler-error-during-cancel"); }).withIdentifier(new Object()).build().cancel(); } @Override public Set<String> getSubscribedEventTypes() { return subscribedEventTypes; } @Override @Nullable public EventFilter getEventFilter() { return null; } @Override public void receive(Event event) { if (event instanceof ThingStatusInfoChangedEvent) { ThingStatusInfoChangedEvent changedEvent = (ThingStatusInfoChangedEvent) event; if (changedEvent.getStatusInfo().getStatus() != ThingStatus.ONLINE) { return; } ThingUID thingUID = changedEvent.getThingUID(); FirmwareUpdateHandler firmwareUpdateHandler = getFirmwareUpdateHandler(thingUID); if (firmwareUpdateHandler != null && !firmwareStatusInfoMap.containsKey(thingUID)) { initializeFirmwareStatus(firmwareUpdateHandler); } } } protected ProgressCallbackImpl getProgressCallback(ThingUID thingUID) { if (!progressCallbackMap.containsKey(thingUID)) { throw new IllegalStateException( String.format("No ProgressCallback available for thing with UID %s.", thingUID)); } return progressCallbackMap.get(thingUID); } @Nullable private Firmware getLatestSuitableFirmware(Thing thing) { Collection<Firmware> firmwares = firmwareRegistry.getFirmwares(thing); if (firmwares != null) { Optional<Firmware> first = firmwares.stream().findFirst(); if (first.isPresent()) { return first.get(); } } return null; } private FirmwareStatusInfo getFirmwareStatusInfo(FirmwareUpdateHandler firmwareUpdateHandler, @Nullable Firmware latestFirmware) { String thingFirmwareVersion = getThingFirmwareVersion(firmwareUpdateHandler); ThingUID thingUID = firmwareUpdateHandler.getThing().getUID(); if (latestFirmware == null || thingFirmwareVersion == null) { return createUnknownInfo(thingUID); } if (latestFirmware.isSuccessorVersion(thingFirmwareVersion)) { if (firmwareUpdateHandler.isUpdateExecutable()) { return createUpdateExecutableInfo(thingUID, latestFirmware.getVersion()); } return createUpdateAvailableInfo(thingUID); } return createUpToDateInfo(thingUID); } private synchronized void processFirmwareStatusInfo(FirmwareUpdateHandler firmwareUpdateHandler, FirmwareStatusInfo newFirmwareStatusInfo, @Nullable Firmware latestFirmware) { FirmwareStatusInfo previousFirmwareStatusInfo = firmwareStatusInfoMap.put(newFirmwareStatusInfo.getThingUID(), newFirmwareStatusInfo); if (previousFirmwareStatusInfo == null || !previousFirmwareStatusInfo.equals(newFirmwareStatusInfo)) { eventPublisher.post(FirmwareEventFactory.createFirmwareStatusInfoEvent(newFirmwareStatusInfo)); if (newFirmwareStatusInfo.getFirmwareStatus() == FirmwareStatus.UPDATE_AVAILABLE && firmwareUpdateHandler instanceof FirmwareUpdateBackgroundTransferHandler && !firmwareUpdateHandler.isUpdateExecutable()) { if (latestFirmware != null) { transferLatestFirmware((FirmwareUpdateBackgroundTransferHandler) firmwareUpdateHandler, latestFirmware, previousFirmwareStatusInfo); } } } } private void transferLatestFirmware(final FirmwareUpdateBackgroundTransferHandler fubtHandler, final Firmware latestFirmware, final FirmwareStatusInfo previousFirmwareStatusInfo) { getPool().submit(new Runnable() { @Override public void run() { try { fubtHandler.transferFirmware(latestFirmware); } catch (Exception e) { logger.error("Exception occurred during background firmware transfer.", e); synchronized (this) { if (previousFirmwareStatusInfo != null) { // restore previous firmware status info in order that transfer can be re-triggered firmwareStatusInfoMap.put(fubtHandler.getThing().getUID(), previousFirmwareStatusInfo); } } } } }); } private void validateFirmwareUpdateConditions(FirmwareUpdateHandler firmwareUpdateHandler, Firmware firmware) { if (!firmwareUpdateHandler.isUpdateExecutable()) { throw new IllegalStateException(String.format("The firmware update of thing with UID %s is not executable.", firmwareUpdateHandler.getThing().getUID())); } validateFirmwareSuitability(firmware, firmwareUpdateHandler); } private void validateFirmwareSuitability(Firmware firmware, FirmwareUpdateHandler firmwareUpdateHandler) { Thing thing = firmwareUpdateHandler.getThing(); if (!firmware.isSuitableFor(thing)) { throw new IllegalArgumentException( String.format("Firmware %s is not suitable for thing with UID %s.", firmware, thing.getUID())); } } private Firmware getFirmware(Thing thing, String firmwareVersion) { Firmware firmware = firmwareRegistry.getFirmware(thing, firmwareVersion); if (firmware == null) { throw new IllegalArgumentException(String.format( "Firmware with version %s for thing with UID %s was not found.", firmwareVersion, thing.getUID())); } return firmware; } @Nullable private FirmwareUpdateHandler getFirmwareUpdateHandler(ThingUID thingUID) { for (FirmwareUpdateHandler firmwareUpdateHandler : firmwareUpdateHandlers) { if (thingUID.equals(firmwareUpdateHandler.getThing().getUID())) { return firmwareUpdateHandler; } } return null; } @Nullable private String getThingFirmwareVersion(FirmwareUpdateHandler firmwareUpdateHandler) { return firmwareUpdateHandler.getThing().getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION); } private void createFirmwareUpdateStatusInfoJob() { if (firmwareStatusInfoJob == null || firmwareStatusInfoJob.isCancelled()) { logger.debug("Creating firmware status info job. [delay:{}, period:{}, time unit: {}]", firmwareStatusInfoJobDelay, firmwareStatusInfoJobPeriod, firmwareStatusInfoJobTimeUnit); firmwareStatusInfoJob = getPool().scheduleWithFixedDelay(firmwareStatusRunnable, firmwareStatusInfoJobDelay, firmwareStatusInfoJobPeriod, firmwareStatusInfoJobTimeUnit); } } private void cancelFirmwareUpdateStatusInfoJob() { if (firmwareStatusInfoJob != null && !firmwareStatusInfoJob.isCancelled()) { logger.debug("Cancelling firmware status info job."); firmwareStatusInfoJob.cancel(true); firmwareStatusInfoJob = null; } } private boolean isValid(Map<String, Object> config) { // the config description validator does not support option value validation at the moment; so we will validate // the time unit here if (!SUPPORTED_TIME_UNITS.contains(config.get(TIME_UNIT_CONFIG_KEY))) { logger.debug("Given time unit {} is not supported. Will keep current configuration.", config.get(TIME_UNIT_CONFIG_KEY)); return false; } try { configDescriptionValidator.validate(config, new URI(CONFIG_DESC_URI_KEY)); } catch (URISyntaxException | ConfigValidationException e) { logger.debug("Validation of new configuration values failed. Will keep current configuration.", e); return false; } return true; } private void initializeFirmwareStatus(final FirmwareUpdateHandler firmwareUpdateHandler) { getPool().submit(new Runnable() { @Override public void run() { ThingUID thingUID = firmwareUpdateHandler.getThing().getUID(); FirmwareStatusInfo info = getFirmwareStatusInfo(thingUID); logger.debug("Firmware status {} for thing {} initialized.", info.getFirmwareStatus(), thingUID); firmwareStatusInfoMap.put(thingUID, info); } }); } private static ScheduledExecutorService getPool() { return ThreadPoolManager.getScheduledPool(THREAD_POOL_NAME); } public int getFirmwareStatusInfoJobPeriod() { return firmwareStatusInfoJobPeriod; } public int getFirmwareStatusInfoJobDelay() { return firmwareStatusInfoJobDelay; } public TimeUnit getFirmwareStatusInfoJobTimeUnit() { return firmwareStatusInfoJobTimeUnit; } @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) protected synchronized void addFirmwareUpdateHandler(FirmwareUpdateHandler firmwareUpdateHandler) { if (firmwareUpdateHandlers.isEmpty()) { createFirmwareUpdateStatusInfoJob(); } firmwareUpdateHandlers.add(firmwareUpdateHandler); } protected synchronized void removeFirmwareUpdateHandler(FirmwareUpdateHandler firmwareUpdateHandler) { firmwareStatusInfoMap.remove(firmwareUpdateHandler.getThing().getUID()); firmwareUpdateHandlers.remove(firmwareUpdateHandler); if (firmwareUpdateHandlers.isEmpty()) { cancelFirmwareUpdateStatusInfoJob(); } progressCallbackMap.remove(firmwareUpdateHandler.getThing().getUID()); } @Reference protected void setFirmwareRegistry(FirmwareRegistry firmwareRegistry) { this.firmwareRegistry = firmwareRegistry; } protected void unsetFirmwareRegistry(FirmwareRegistry firmwareRegistry) { this.firmwareRegistry = null; } @Reference protected void setEventPublisher(EventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } protected void unsetEventPublisher(EventPublisher eventPublisher) { this.eventPublisher = null; } @Reference protected void setTranslationProvider(TranslationProvider i18nProvider) { this.i18nProvider = i18nProvider; } protected void unsetTranslationProvider(TranslationProvider i18nProvider) { this.i18nProvider = null; } @Reference protected void setLocaleProvider(final LocaleProvider localeProvider) { this.localeProvider = localeProvider; } protected void unsetLocaleProvider(final LocaleProvider localeProvider) { this.localeProvider = null; } @Reference protected void setSafeCaller(SafeCaller safeCaller) { this.safeCaller = safeCaller; } protected void unsetSafeCaller(SafeCaller safeCaller) { this.safeCaller = null; } @Reference protected void setConfigDescriptionValidator(ConfigDescriptionValidator configDescriptionValidator) { this.configDescriptionValidator = configDescriptionValidator; } protected void unsetConfigDescriptionValidator(ConfigDescriptionValidator configDescriptionValidator) { this.configDescriptionValidator = null; } @Reference protected void setBundleResolver(BundleResolver bundleResolver) { this.bundleResolver = bundleResolver; } protected void unsetBundleResolver(BundleResolver bundleResolver) { this.bundleResolver = bundleResolver; } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.action.BoundAction; import org.jdesktop.swingx.decorator.SortKey; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.test.AncientSwingTeam; import org.jdesktop.test.CellEditorReport; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.SerializableSupport; /** * Test to exposed known issues of <code>JXTable</code>. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * @author Jeanette Winzenburg */ public class JXTableIssues extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTableIssues.class .getName()); /** * test if created a new instance of the renderer. While the old * assertions are true, it's useless with swingx renderers: the renderer is * a new instance but not specialized to boolean. So added an assert * for the actual component type. Which fails for now - need to * think if we really need the functionality! * */ public void testNewRendererInstance() { JXTable table = new JXTable(); TableCellRenderer newRenderer = table.getNewDefaultRenderer(Boolean.class); TableCellRenderer sharedRenderer = table.getDefaultRenderer(Boolean.class); // following assertions are useful only with core renderers // (they differ by type on the renderer level) assertNotNull(newRenderer); assertNotSame("new renderer must be different from shared", sharedRenderer, newRenderer); assertNotSame("new renderer must be different from object renderer", table.getDefaultRenderer(Object.class), newRenderer); Component comp = newRenderer.getTableCellRendererComponent(table, Boolean.TRUE, false, false, -1, -1); assertTrue("Boolean rendering component is expected to be a Checkbox by default" + "\n but is " + comp.getClass(), comp instanceof AbstractButton); } /** * Issue #4614616: editor lookup broken for interface types. * With editors (vs. renderers), the solution is not obvious - * interfaces can't be instantiated. As a consequence, the * GenericEditor can't cope (returns null as component which * it must not but that's another issue). * */ public void testNPEEditorForInterface() { DefaultTableModel model = new DefaultTableModel(10, 2) { @Override public Class<?> getColumnClass(int columnIndex) { return Comparable.class; } }; JXTable table = new JXTable(model); table.prepareEditor(table.getCellEditor(0, 0), 0, 0); } /** * Issue 373-swingx: table must unsort column on sortable change. * * Here we test if switching sortable to false on the sorted column * resets the sorting, special case hidden column. This fails * because columnModel doesn't fire property change events for * hidden columns (see Issue #??-swingx). * */ public void testTableUnsortedColumnOnHiddenColumnSortableChange() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); Object identifier = columnExt.getIdentifier(); table.toggleSortOrder(identifier); assertTrue(table.getSortOrder(identifier).isSorted()); columnExt.setVisible(false); assertTrue(table.getSortOrder(identifier).isSorted()); columnExt.setSortable(false); assertFalse("table must have unsorted column on sortable change", table.getSortOrder(identifier).isSorted()); } /** * Not defined: what should happen if the edited column is hidden? * For sure, editing must be terminated - but canceled or stopped? * * Here we test if the table is not editing after editable property * of the currently edited column is changed to false. */ public void testTableNotEditingOnColumnVisibleChange() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); assertEquals(0, table.getEditingColumn()); columnExt.setVisible(false); assertFalse("table must have terminated edit",table.isEditing()); fail("forcing a fail - cancel editing is a side-effect of removal notification"); } /** * Issue 372-swingx: table must cancel edit if column property * changes to not editable. * Here we test if the table actually canceled the edit. */ public void testTableCanceledEditOnColumnEditableChange() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); assertEquals(0, table.getEditingColumn()); TableCellEditor editor = table.getCellEditor(); CellEditorReport report = new CellEditorReport(); editor.addCellEditorListener(report); columnExt.setEditable(false); // sanity assertFalse(table.isCellEditable(0, 0)); assertEquals("editor must have fired canceled", 1, report.getCanceledEventCount()); assertEquals("editor must not have fired stopped",0, report.getStoppedEventCount()); } /** * a quick sanity test: reporting okay?. * (doesn't belong here, should test the tools * somewhere else) * */ public void testCellEditorFired() { JXTable table = new JXTable(10, 2); table.editCellAt(0, 0); CellEditorReport report = new CellEditorReport(); TableCellEditor editor = table.getCellEditor(); editor.addCellEditorListener(report); editor.cancelCellEditing(); assertEquals("total count must be equals to canceled", report.getCanceledEventCount(), report.getEventCount()); assertEquals("editor must have fired canceled", 1, report.getCanceledEventCount()); assertEquals("editor must not have fired stopped", 0, report.getStoppedEventCount()); report.clear(); assertEquals("canceled cleared", 0, report.getCanceledEventCount()); assertEquals("total cleared", 0, report.getStoppedEventCount()); // same cell, same editor table.editCellAt(0, 0); editor.stopCellEditing(); assertEquals("total count must be equals to stopped", report.getStoppedEventCount(), report.getEventCount()); assertEquals("editor must not have fired canceled", 0, report.getCanceledEventCount()); // JW: surprising... it really fires twice? assertEquals("editor must have fired stopped", 1, report.getStoppedEventCount()); } /** * Issue #359-swing: find suitable rowHeight. * * Text selection in textfield has row of metrics.getHeight. * Suitable rowHeight should should take border into account: * for a textfield that's the metrics height plus 2. */ public void testRowHeightFontMetrics() { JXTable table = new JXTable(10, 2); TableCellEditor editor = table.getCellEditor(1, 1); Component comp = table.prepareEditor(editor, 1, 1); assertEquals(comp.getPreferredSize().height, table.getRowHeight()); } /** * Issue #349-swingx: table not serializable * * Part of the problem is in TableRolloverController. * */ public void testSerializationRollover() { JXTable table = new JXTable(); try { SerializableSupport.serialize(table); } catch (IOException e) { fail("not serializable " + e); } catch (ClassNotFoundException e) { fail("not serializable " + e); } } /** * Issue #349-swingx: table not serializable * * Part of it seems to be in BoundAction. * */ public void testSerializationRolloverFalse() { JXTable table = new JXTable(); table.setRolloverEnabled(false); ActionMap actionMap = table.getActionMap(); Object[] keys = actionMap.keys(); for (int i = 0; i < keys.length; i++) { if (actionMap.get(keys[i]) instanceof BoundAction) { actionMap.remove(keys[i]); } } try { SerializableSupport.serialize(table); } catch (IOException e) { fail("not serializable " + e); } catch (ClassNotFoundException e) { fail("not serializable " + e); } } /** * Issue #349-swingx: table not serializable * * Part of it seems to be in JXTableHeader. * */ public void testSerializationTableHeader() { JXTableHeader table = new JXTableHeader(); try { SerializableSupport.serialize(table); } catch (IOException e) { fail("not serializable " + e); } catch (ClassNotFoundException e) { fail("not serializable " + e); } } /** * Issue??-swingx: turn off scrollbar doesn't work if the * table was initially in autoResizeOff mode. * * Problem with state management. * */ public void testHorizontalScrollEnabled() { JXTable table = new JXTable(); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); assertEquals("horizontalScroll must be on", true, table.isHorizontalScrollEnabled()); table.setHorizontalScrollEnabled(false); assertEquals("horizontalScroll must be off", false, table.isHorizontalScrollEnabled()); } /** * we have a slight inconsistency in event values: setting the * client property to null means "false" but the event fired * has the newValue null. * * The way out is to _not_ set the client prop manually, always go * through the property setter. */ public void testClientPropertyNull() { JXTable table = new JXTable(); // sanity assert: setting client property set's property PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.putClientProperty("terminateEditOnFocusLost", null); assertFalse(table.isTerminateEditOnFocusLost()); assertEquals(1, report.getEventCount()); assertEquals(1, report.getEventCount("terminateEditOnFocusLost")); assertEquals(false, report.getLastNewValue("terminateEditOnFocusLost")); } /** * JXTable has responsibility to guarantee usage of * TableColumnExt comparator and update the sort if * the columns comparator changes. * */ public void testComparatorToPipelineDynamic() { JXTable table = new JXTable(new AncientSwingTeam()); TableColumnExt columnX = table.getColumnExt(0); table.toggleSortOrder(0); columnX.setComparator(Collator.getInstance()); // invalid assumption .. only the comparator must be used. // assertEquals("interactive sorter must be same as sorter in column", // columnX.getSorter(), table.getFilters().getSorter()); SortKey sortKey = SortKey.getFirstSortKeyForColumn(table.getFilters().getSortController().getSortKeys(), 0); assertNotNull(sortKey); assertEquals(columnX.getComparator(), sortKey.getComparator()); } /** * Issue #256-swingX: viewport - toggle track height must * revalidate. * * PENDING JW: the visual test looks okay - probably something wrong with the * test setup ... invoke doesn't help * */ public void testToggleTrackViewportHeight() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run trackViewportHeight - headless environment"); return; } final JXTable table = new JXTable(10, 2); table.setFillsViewportHeight(true); final Dimension tablePrefSize = table.getPreferredSize(); JScrollPane scrollPane = new JScrollPane(table); JXFrame frame = wrapInFrame(scrollPane, ""); frame.setSize(500, tablePrefSize.height * 2); frame.setVisible(true); assertEquals("table height be equal to viewport", table.getHeight(), scrollPane.getViewport().getHeight()); table.setFillsViewportHeight(false); assertEquals("table height be equal to table pref height", tablePrefSize.height, table.getHeight()); } //-------------------- adapted jesse wilson: #223 /** * Enhancement: modifying (= filtering by resetting the content) should keep * selection * */ public void testModifyTableContentAndSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(2, 5); Object[] selectedObjects = new Object[] { "C", "D", "E", "F" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); compare.tableModel.setContents(new Object[] { "B", "C", "D", "F", "G", "H" }); Object[] selectedObjectsAfterModify = (new Object[] { "C", "D", "F" }); assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjectsAfterModify); } /** * Enhancement: modifying (= filtering by resetting the content) should keep * selection */ public void testModifyXTableContentAndSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.xTable.getSelectionModel().setSelectionInterval(2, 5); Object[] selectedObjects = new Object[] { "C", "D", "E", "F" }; assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); compare.tableModel.setContents(new Object[] { "B", "C", "D", "F", "G", "H" }); Object[] selectedObjectsAfterModify = (new Object[] { "C", "D", "F" }); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjectsAfterModify); } /** * test: deleting row below selection - should not change */ public void testDeleteRowBelowSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(2, 5); compare.xTable.getSelectionModel().setSelectionInterval(2, 5); Object[] selectedObjects = new Object[] { "C", "D", "E", "F" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); compare.tableModel.removeRow(compare.tableModel.getRowCount() - 1); assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); } /** * test: deleting last row in selection - should remove last item from selection. */ public void testDeleteLastRowInSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(7, 8); compare.xTable.getSelectionModel().setSelectionInterval(7, 8); Object[] selectedObjects = new Object[] { "H", "I" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); compare.tableModel.removeRow(compare.tableModel.getRowCount() - 1); Object[] selectedObjectsAfterDelete = new Object[] { "H" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjectsAfterDelete); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjectsAfterDelete); } private void assertSelection(TableModel tableModel, ListSelectionModel selectionModel, Object[] expected) { List selected = new ArrayList(); for(int r = 0; r < tableModel.getRowCount(); r++) { if(selectionModel.isSelectedIndex(r)) selected.add(tableModel.getValueAt(r, 0)); } List expectedList = Arrays.asList(expected); assertEquals("selected Objects must be as expected", expectedList, selected); } public void interactiveDeleteRowAboveSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(2, 5); compare.xTable.getSelectionModel().setSelectionInterval(2, 5); JComponent box = createContent(compare, createRowDeleteAction(0, compare.tableModel)); JFrame frame = wrapInFrame(box, "delete above selection"); frame.setVisible(true); } public void interactiveDeleteRowBelowSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(6, 7); compare.xTable.getSelectionModel().setSelectionInterval(6, 7); JComponent box = createContent(compare, createRowDeleteAction(-1, compare.tableModel)); JFrame frame = wrapInFrame(box, "delete below selection"); frame.setVisible(true); } /** * Issue #370-swingx: "jumping" selection while dragging. * */ public void interactiveExtendSelection() { final UpdatingTableModel model = new UpdatingTableModel(); JXTable table = new JXTable(model); // Swing Timer - EDT in Timer ActionListener l = new ActionListener() { int i = 0; public void actionPerformed(ActionEvent e) { model.updateCell(i++ % 10); } }; Timer timer = new Timer(1000, l); timer.start(); JXFrame frame = wrapWithScrollingInFrame(table, "#370 - extend selection by dragging"); frame.setVisible(true); } /** * Simple model for use in continous update tests. * Issue #370-swingx: jumping selection on dragging. */ private class UpdatingTableModel extends AbstractTableModel { private int[][] data = new int[10][5]; public UpdatingTableModel() { for (int row = 0; row < data.length; row++) { fillRow(row); } } public int getRowCount() { return 10; } public int getColumnCount() { return 5; } public Object getValueAt(int rowIndex, int columnIndex) { return data[rowIndex][columnIndex]; } /** * update first column of row on EDT. * @param row */ public void invokeUpdateCell(final int row) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateCell(row); } }); } /** * update first column of row. Sorting on any column except the first * doesn't change row sequence - shouldn't interfere with selection * extension. * * @param row */ public void updateCell(final int row) { updateCell(row, 0); fireTableCellUpdated(row, 0); } public void fillRow(int row) { for (int col = 0; col < data[row].length; col++) { updateCell(row, col); } } /** * Fills the given cell with random value. * @param row * @param col */ private void updateCell(int row, int col) { data[row][col] = (int) Math.round(Math.random() * 200); } } /** * Issue #282-swingx: compare disabled appearance of * collection views. * */ public void interactiveDisabledCollectionViews() { final JXTable table = new JXTable(new AncientSwingTeam()); table.setEnabled(false); final JXList list = new JXList(new String[] {"one", "two", "and something longer"}); list.setEnabled(false); final JXTree tree = new JXTree(new FileSystemModel()); tree.setEnabled(false); JComponent box = Box.createHorizontalBox(); box.add(new JScrollPane(table)); box.add(new JScrollPane(list)); box.add(new JScrollPane(tree)); JXFrame frame = wrapInFrame(box, "disabled collection views"); AbstractAction action = new AbstractAction("toggle disabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); list.setEnabled(!list.isEnabled()); tree.setEnabled(!tree.isEnabled()); } }; addAction(frame, action); frame.setVisible(true); } public void interactiveDataChanged() { final DefaultTableModel model = createAscendingModel(0, 10, 5, false); JXTable xtable = new JXTable(model); xtable.setRowSelectionInterval(0, 0); // JTable table = new JTable(model); // table.setRowSelectionInterval(0, 0); AbstractAction action = new AbstractAction("fire dataChanged") { public void actionPerformed(ActionEvent e) { model.fireTableDataChanged(); } }; // JXFrame frame = wrapWithScrollingInFrame(xtable, table, "selection after data changed"); JXFrame frame = wrapWithScrollingInFrame(xtable, "selection after data changed"); addAction(frame, action); frame.setVisible(true); } private JComponent createContent(CompareTableBehaviour compare, Action action) { JComponent box = new JPanel(new BorderLayout()); box.add(new JScrollPane(compare.table), BorderLayout.WEST); box.add(new JScrollPane(compare.xTable), BorderLayout.EAST); box.add(new JButton(action), BorderLayout.SOUTH); return box; } private Action createRowDeleteAction(final int row, final ReallySimpleTableModel simpleTableModel) { Action delete = new AbstractAction("DeleteRow " + ((row < 0) ? "last" : "" + row)) { public void actionPerformed(ActionEvent e) { int rowToDelete = row; if (row < 0) { rowToDelete = simpleTableModel.getRowCount() - 1; } if ((rowToDelete < 0) || (rowToDelete >= simpleTableModel.getRowCount())) { return; } simpleTableModel.removeRow(rowToDelete); if (simpleTableModel.getRowCount() == 0) { setEnabled(false); } } }; return delete; } public static class CompareTableBehaviour { public ReallySimpleTableModel tableModel; public JTable table; public JXTable xTable; public CompareTableBehaviour(Object[] model) { tableModel = new ReallySimpleTableModel(); tableModel.setContents(model); table = new JTable(tableModel); xTable = new JXTable(tableModel); table.getColumnModel().getColumn(0).setHeaderValue("JTable"); xTable.getColumnModel().getColumn(0).setHeaderValue("JXTable"); } }; /** * A one column table model where all the data is in an Object[] array. */ static class ReallySimpleTableModel extends AbstractTableModel { private List contents = new ArrayList(); public void setContents(List contents) { this.contents.clear(); this.contents.addAll(contents); fireTableDataChanged(); } public void setContents(Object[] contents) { setContents(Arrays.asList(contents)); } public void removeRow(int row) { contents.remove(row); fireTableRowsDeleted(row, row); } public int getRowCount() { return contents.size(); } public int getColumnCount() { return 1; } public Object getValueAt(int row, int column) { if(column != 0) throw new IllegalArgumentException(); return contents.get(row); } } /** * returns a tableModel with count rows filled with * ascending integers in first column * starting from startRow. * @param startRow the value of the first row * @param rowCount the number of rows * @return */ private DefaultTableModel createAscendingModel(int startRow, final int rowCount, final int columnCount, boolean fillLast) { DefaultTableModel model = new DefaultTableModel(rowCount, columnCount) { public Class getColumnClass(int column) { Object value = rowCount > 0 ? getValueAt(0, column) : null; return value != null ? value.getClass() : super.getColumnClass(column); } }; int filledColumn = fillLast ? columnCount - 1 : 0; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Integer(startRow++), i, filledColumn); } return model; } private DefaultTableModel createAscendingModel(int startRow, int count) { DefaultTableModel model = new DefaultTableModel(count, 5); for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Integer(startRow++), i, 0); } return model; } /** * Issue #??: JXTable pattern search differs from * PatternHighlighter/Filter. * * Fixing the issue (respect the pattern as is by calling * pattern.matcher().matches instead of the find()) must * make sure that the search methods taking the string * include wildcards. * * Note: this method passes as long as the issue is not * fixed! * * TODO: check status! */ public void testWildCardInSearchByString() { JXTable table = new JXTable(createAscendingModel(0, 11)); int row = 1; String lastName = table.getValueAt(row, 0).toString(); int found = table.getSearchable().search(lastName, -1); assertEquals("found must be equal to row", row, found); found = table.getSearchable().search(lastName, found); assertEquals("search must succeed", 10, found); } /** * Issue #445-swingx: sort icon not updated on programatic sorting. * */ public void interactiveHeaderUpdateOnSorting() { final JXTable table = new JXTable(createAscendingModel(0, 10)); Action action = new AbstractActionExt("toggle sorter order") { public void actionPerformed(ActionEvent e) { table.toggleSortOrder(0); } }; JXFrame frame = wrapWithScrollingInFrame(table, "sort icon"); addAction(frame, action); frame.setVisible(true); } public static void main(String args[]) { JXTableIssues test = new JXTableIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Siz.*"); // test.runInteractiveTests("interactive.*Render.*"); // test.runInteractiveTests(".*DataChanged.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } }
package org.basex.query.util.format; import static org.basex.query.QueryError.*; import static org.basex.util.Token.*; import java.math.*; import java.util.*; import org.basex.query.*; import org.basex.query.value.item.*; import org.basex.query.value.type.*; import org.basex.util.*; import org.basex.util.hash.*; import org.basex.util.list.*; public abstract class Formatter extends FormatUtil { /** Military timezones. */ private static final byte[] MIL = token("YXWVUTSRQPONZABCDEFGHIKLM"); /** Token: Nn. */ private static final byte[] NN = { 'N', 'n' }; /** Allowed calendars. */ private static final byte[][] CALENDARS = tokens( "ISO", "AD", "AH", "AME", "AM", "AP", "AS", "BE", "CB", "CE", "CL", "CS", "EE", "FE", "JE", "KE", "KY", "ME", "MS", "NS", "OS", "RS", "SE", "SH", "SS", "TE", "VE", "VS"); /** Default language: English. */ public static final byte[] EN = token("en"); /** Formatter instances. */ private static final TokenObjMap<Formatter> MAP = new TokenObjMap<>(); // initialize hash map with English formatter as default static { MAP.put(EN, new FormatterEN()); MAP.put(token("de"), new FormatterDE()); } /** * Returns a formatter for the specified language. * @param ln language * @return formatter instance */ public static Formatter get(final byte[] ln) { // check if formatter has already been created Formatter form = MAP.get(ln); if(form == null) { final String clz = Util.className(Formatter.class) + string(uc(ln)); form = (Formatter) Reflect.get(Reflect.find(clz)); // instantiation not successful: return default formatter if(form == null) form = MAP.get(EN); } return form; } /** * Returns a word representation for the specified number. * @param n number to be formatted * @param ord ordinal suffix * @return token */ protected abstract byte[] word(final long n, final byte[] ord); /** * Returns an ordinal representation for the specified number. * @param n number to be formatted * @param ord ordinal suffix * @return ordinal */ protected abstract byte[] ordinal(final long n, final byte[] ord); /** * Returns the specified month (0-11). * @param n number to be formatted * @param min minimum length * @param max maximum length * @return month */ protected abstract byte[] month(final int n, final int min, final int max); /** * Returns the specified day of the week (0-6, Sunday-Saturday). * @param n number to be formatted * @param min minimum length * @param max maximum length * @return day of week */ protected abstract byte[] day(final int n, final int min, final int max); /** * Returns the am/pm marker. * @param am am flag * @return am/pm marker */ protected abstract byte[] ampm(final boolean am); /** * Returns the calendar. * @return calendar */ protected abstract byte[] calendar(); /** * Returns the era. * @param year year * @return era */ protected abstract byte[] era(final long year); /** * Formats the specified date. * @param date date to be formatted * @param lng language * @param pic picture * @param cal calendar * @param plc place * @param ii input info * @param sc static context * @return formatted string * @throws QueryException query exception */ public final byte[] formatDate(final ADate date, final byte[] lng, final byte[] pic, final byte[] cal, final byte[] plc, final InputInfo ii, final StaticContext sc) throws QueryException { final TokenBuilder tb = new TokenBuilder(); if(lng.length != 0 && MAP.get(lng) == null) tb.add("[Language: en]"); if(cal.length != 0) { final QNm qnm; try { qnm = QNm.resolve(cal, sc); } catch(final QueryException ex) { throw CALQNAME_X.get(ii, cal); } if(qnm.uri().length == 0) { int c = -1; final byte[] ln = qnm.local(); final int cl = CALENDARS.length; while(++c < cl && !eq(CALENDARS[c], ln)); if(c == cl) throw CALWHICH_X.get(ii, cal); if(c > 1) tb.add("[Calendar: AD]"); } } if(plc.length != 0) tb.add("[Place: ]"); final DateParser dp = new DateParser(ii, pic); while(dp.more()) { final int ch = dp.literal(); if(ch == -1) { // retrieve variable marker final byte[] marker = dp.marker(); if(marker.length == 0) throw PICDATE_X.get(ii, pic); // parse component specifier final int compSpec = ch(marker, 0); byte[] pres = ONE; boolean max = false; BigDecimal frac = null; long num = 0; final boolean dat = date.type == AtomType.DAT; final boolean tim = date.type == AtomType.TIM; boolean err = false; switch(compSpec) { case 'Y': num = Math.abs(date.yea()); max = true; err = tim; break; case 'M': num = date.mon(); err = tim; break; case 'D': num = date.day(); err = tim; break; case 'd': final long y = date.yea(); for(int m = (int) date.mon() - 1; --m >= 0;) num += ADate.dpm(y, m); num += date.day(); err = tim; break; case 'F': num = date.toJava().toGregorianCalendar().get(Calendar.DAY_OF_WEEK) - 1; if(num == 0) num = 7; pres = NN; err = tim; break; case 'W': num = date.toJava().toGregorianCalendar().get(Calendar.WEEK_OF_YEAR); err = tim; break; case 'w': num = date.toJava().toGregorianCalendar().get(Calendar.WEEK_OF_MONTH); // first week of month: fix value, according to ISO 8601 if(num == 0) num = new Dtm(new Dtm(date), new DTDur(date.day() * 24, 0), false, ii). toJava().toGregorianCalendar().get(Calendar.WEEK_OF_MONTH); err = tim; break; case 'H': num = date.hou(); err = dat; break; case 'h': num = date.hou() % 12; if(num == 0) num = 12; err = dat; break; case 'P': num = date.hou() / 12; pres = NN; err = dat; break; case 'm': num = date.min(); pres = token("01"); err = dat; break; case 's': num = date.sec().intValue(); pres = token("01"); err = dat; break; case 'f': frac = date.sec().remainder(BigDecimal.ONE); num = frac.movePointRight(3).intValue(); err = dat; break; case 'Z': case 'z': num = date.tz(); pres = token("01:01"); break; case 'C': pres = NN; break; case 'E': num = date.yea(); pres = NN; err = tim; break; default: throw INVCOMPSPEC_X.get(ii, marker); } if(err) throw PICINVCOMP_X_X.get(ii, marker, date.type); if(pres == null) continue; // parse presentation modifier(s) and width modifier final DateFormat fp = new DateFormat(substring(marker, 1), pres, ii); if(max) { // limit maximum length of numeric output int mx = 0; final int fl = fp.primary.length; for(int s = 0; s < fl; s += cl(fp.primary, s)) mx++; if(mx > 1) fp.max = mx; } if(compSpec == 'z' || compSpec == 'Z') { // output timezone tb.add(formatZone((int) num, fp, marker)); } else if(fp.first == 'n') { // output name representation byte[] in = null; if(compSpec == 'M') { in = month((int) num - 1, fp.min, fp.max); } else if(compSpec == 'F') { in = day((int) num - 1, fp.min, fp.max); } else if(compSpec == 'P') { in = ampm(num == 0); } else if(compSpec == 'C') { in = calendar(); } else if(compSpec == 'E') { in = era((int) num); } if(in != null) { if(fp.cs == Case.LOWER) in = lc(in); if(fp.cs == Case.UPPER) in = uc(in); tb.add(in); } else { // fallback representation fp.first = '0'; fp.primary = ONE; tb.add(formatInt(num, fp)); } } else { // output fractional component if(frac != null && frac.compareTo(BigDecimal.ZERO) != 0) { String s = frac.toString().replace("0.", ""); final int sl = s.length(); if(fp.min > sl) { s = frac(frac, fp.min); } else if(fp.max < sl) { s = frac(frac, fp.max); } else { final int fl = fp.primary.length; if(fl != 1 && fl != sl) s = frac(frac, fl); } num = Strings.toLong(s); } tb.add(formatInt(num, fp)); } } else { // print literal tb.add(ch); } } return tb.finish(); } /** * Returns the fractional part of a decimal number. * @param num number * @param len length of fractional part * @return string representation */ private static String frac(final BigDecimal num, final int len) { final String s = num.setScale(len, RoundingMode.HALF_UP).toString(); final int d = s.indexOf('.'); return d == -1 ? s : s.substring(d + 1); } /** * Returns a formatted integer. * @param num integer to be formatted * @param fp format parser * @return string representation */ public final byte[] formatInt(final long num, final FormatParser fp) { // prepend minus sign to negative values long n = num; final boolean sign = n < 0; if(sign) n = -n; final TokenBuilder tb = new TokenBuilder(); final int ch = fp.first; if(ch == 'w') { tb.add(word(n, fp.ordinal)); } else if(ch == KANJI[1]) { japanese(tb, n); } else if(ch == 'i') { roman(tb, n, fp.min); } else if(ch == '\u2460' || ch == '\u2474' || ch == '\u2488') { if(num < 1 || num > 20) tb.addLong(num); else tb.add((int) (ch + num - 1)); } else { final String seq = sequence(ch); if(seq != null) alpha(tb, num, seq); else tb.add(number(n, fp, zeroes(ch))); } // finalize formatted string byte[] in = tb.finish(); if(fp.cs == Case.LOWER) in = lc(in); if(fp.cs == Case.UPPER) in = uc(in); return sign ? concat(new byte[] { '-' }, in) : in; } /** * Returns a formatted timezone. * @param num integer to be formatted * @param fp format parser * @param marker marker * @return string representation * @throws QueryException query exception */ private byte[] formatZone(final int num, final FormatParser fp, final byte[] marker) throws QueryException { final boolean uc = ch(marker, 0) == 'Z'; final boolean mil = uc && ch(marker, 1) == 'Z'; // ignore values without timezone. exception: military timezone if(num == Short.MAX_VALUE) return mil ? new byte[] { 'J' } : EMPTY; final TokenBuilder tb = new TokenBuilder(); if(!mil || !addMilZone(num, tb)) { if(!uc) tb.add("GMT"); final boolean minus = num < 0; if(fp.trad && num == 0) { tb.add('Z'); } else { tb.add(minus ? '-' : '+'); final TokenParser tp = new TokenParser(fp.primary); final int c1 = tp.next(), c2 = tp.next(), c3 = tp.next(), c4 = tp.next(); final int z1 = zeroes(c1), z2 = zeroes(c2), z3 = zeroes(c3), z4 = zeroes(c4); if(z1 == -1) { tb.add(addZone(num, 0, new TokenBuilder("00"))).add(':'); tb.add(addZone(num, 1, new TokenBuilder("00"))); } else if(z2 == -1) { tb.add(addZone(num, 0, new TokenBuilder().add(c1))); if(c2 == -1) { if(num % 60 != 0) tb.add(':').add(addZone(num, 1, new TokenBuilder("00"))); } else { final TokenBuilder t = new TokenBuilder().add(z3 == -1 ? '0' : z3); if(z3 != -1 && z4 != -1) t.add(z4); tb.add(c2).add(addZone(num, 1, t)); } } else if(z3 == -1) { tb.add(addZone(num, 0, new TokenBuilder().add(c1).add(c2))); if(c3 == -1) { if(num % 60 != 0) tb.add(':').add(addZone(num, 1, new TokenBuilder("00"))); } else { final int c5 = tp.next(), z5 = zeroes(c5); final TokenBuilder t = new TokenBuilder().add(z4 == -1 ? '0' : z4); if(z4 != -1 && z5 != -1) t.add(z5); tb.add(c3).add(addZone(num % 60, 1, t)); } } else if(z4 == -1) { tb.add(addZone(num, 0, new TokenBuilder().add(c1))); tb.add(addZone(num, 1, new TokenBuilder().add(c2).add(c3))); } else { tb.add(addZone(num, 0, new TokenBuilder().add(c1).add(c2))); tb.add(addZone(num, 1, new TokenBuilder().add(c3).add(c4))); } } } return tb.finish(); } /** * Returns a timezone component. * @param num number to be formatted * @param c counter * @param format presentation format * @return timezone component * @throws QueryException query exception */ private byte[] addZone(final int num, final int c, final TokenBuilder format) throws QueryException { int n = c == 0 ? num / 60 : num % 60; if(num < 0) n = -n; return number(n, new IntFormat(format.toArray(), null), zeroes(format.cp(0))); } /** * Adds a military timezone component to the specified token builder. * @param num number to be formatted * @param tb token builder * @return {@code true} if timezone was added */ private static boolean addMilZone(final int num, final TokenBuilder tb) { final int n = num / 60; if(num % 60 != 0 || n < -12 || n > 12) return false; tb.add(MIL[n + 12]); return true; } /** * Returns a character sequence based on the specified alphabet. * @param tb token builder * @param n number to be formatted * @param a alphabet */ private static void alpha(final TokenBuilder tb, final long n, final String a) { final int al = a.length(); if(n > al) alpha(tb, (n - 1) / al, a); if(n > 0) tb.add(a.charAt((int) ((n - 1) % al))); else tb.add(ZERO); } /** * Adds a Roman character sequence. * @param tb token builder * @param n number to be formatted * @param min minimum width */ private static void roman(final TokenBuilder tb, final long n, final int min) { final int s = tb.size(); if(n > 0 && n < 4000) { final int v = (int) n; tb.add(ROMANM[v / 1000]); tb.add(ROMANC[v / 100 % 10]); tb.add(ROMANX[v / 10 % 10]); tb.add(ROMANI[v % 10]); } else { tb.addLong(n); } while(tb.size() - s < min) tb.add(' '); } /** * Adds a Japanese character sequence. * @param tb token builder * @param n number to be formatted */ private static void japanese(final TokenBuilder tb, final long n) { if(n == 0) { tb.add(KANJI[0]); } else { jp(tb, n, false); } } /** * Recursively adds a Japanese character sequence. * @param tb token builder * @param n number to be formatted * @param i initial call */ private static void jp(final TokenBuilder tb, final long n, final boolean i) { if(n == 0) { } else if(n <= 9) { if(n != 1 || !i) tb.add(KANJI[(int) n]); } else if(n == 10) { tb.add(KANJI[10]); } else if(n <= 99) { jp(tb, n, 10, 10); } else if(n <= 999) { jp(tb, n, 100, 11); } else if(n <= 9999) { jp(tb, n, 1000, 12); } else if(n <= 99999999) { jp(tb, n, 10000, 13); } else if(n <= 999999999999L) { jp(tb, n, 100000000, 14); } else if(n <= 9999999999999999L) { jp(tb, n, 1000000000000L, 15); } else { tb.addLong(n); } } /** * Recursively adds a Japanese character sequence. * @param tb token builder * @param n number to be formatted * @param f factor * @param o kanji offset */ private static void jp(final TokenBuilder tb, final long n, final long f, final int o) { jp(tb, n / f, true); tb.add(KANJI[o]); jp(tb, n % f, false); } /** * Creates a number character sequence. * @param num number to be formatted * @param fp format parser * @param zero zero digit * @return number character sequence */ private byte[] number(final long num, final FormatParser fp, final int zero) { // cache characters of presentation modifier final int[] mod = new TokenParser(fp.primary).toArray(); final int modSize = mod.length; int modStart = 0; while(modStart < modSize && mod[modStart] == '#') modStart++; // try to find regular separator pattern int sepPos = -1, sepChar = -1, digitPos = 0; boolean regSep = false; for(int mp = modSize - 1; mp >= modStart; --mp) { final int ch = mod[mp]; if(ch >= zero && ch <= zero + 9) { digitPos = mp; continue; } if(ch == '#') continue; if(sepPos == -1) { sepPos = modSize - mp; sepChar = ch; regSep = true; } else if(regSep) { regSep = (modSize - mp) % sepPos == 0 && ch == sepChar; } } if(!regSep) sepPos = Integer.MAX_VALUE; // cache characters in reverse order final IntList reverse = new IntList(); final byte[] in = token(num); int inPos = in.length - 1, modPos = modSize - 1; // add numbers and separators int min = fp.min, max = fp.max; while((--min >= 0 || inPos >= 0 || modPos >= modStart) && --max >= 0) { final boolean sep = reverse.size() % sepPos == sepPos - 1; int ch; if(modPos >= modStart) { ch = mod[modPos if(inPos >= 0) { if(ch == '#' && sep) reverse.add(sepChar); if(ch == '#' || ch >= zero && ch <= zero + 9) ch = in[inPos--] - '0' + zero; } else { // add remaining modifiers if(ch == '#') break; if(ch >= zero && ch <= zero + 9) ch = zero; if(regSep && modPos + 1 < digitPos) break; } } else if(inPos >= 0) { // add remaining numbers if(sep) reverse.add(sepChar); ch = in[inPos--] - '0' + zero; } else { // add minimum number of digits ch = zero; } reverse.add(ch); } while(min-- >= 0) reverse.add(zero); // reverse result and add ordinal suffix final TokenBuilder result = new TokenBuilder(); for(int rs = reverse.size() - 1; rs >= 0; --rs) result.add(reverse.get(rs)); return result.add(ordinal(num, fp.ordinal)).finish(); } }
package projet_poo2; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.SwingUtilities; public class IHM extends JFrame implements KeyListener,MouseListener { private static final long serialVersionUID = 1L; private JMenuBar menuBar = new JMenuBar(); private JMenu menu1 = new JMenu("Fichier"); private JMenuItem item1 = new JMenuItem("Ouvrir"); private JMenu menu2 = new JMenu("Calcul"); private JMenuItem item2 = new JMenuItem("Corrlation"); String pathopendirectory = "."; private ArrayList<ArrayList<Point>> reference=new ArrayList<ArrayList<Point>>(); private JLabel[] jltab=new JLabel[2]; private Picture[] pictures = new Picture[2]; int cpt=0; public IHM() { super(); this.reference.add(new ArrayList<Point>()); this.reference.add(new ArrayList<Point>()); this.setTitle("Project"); this.getContentPane().setPreferredSize(new Dimension(200,200)); this.addKeyListener(this); this.menuBar.add(menu1); this.menu1.add(item1); item1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event) { try { openFileLocation(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); this.menuBar.add(menu2); this.menu2.add(item2); item2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if(reference.get(0).size() >= 4 && reference.get(1).size() >= 4) { System.out.println("lancer fonction corrlation"); //// fonction corrlation de la classe Calcul /// Calcul.correlation() } } }); this.setJMenuBar(menuBar); } public void ouvrirImage(String filename) throws IOException { Picture pic=new Picture(filename); System.out.println(pic.width+" "+pic.height); System.out.println(Toolkit.getDefaultToolkit().getScreenSize().getWidth()+" "+Toolkit.getDefaultToolkit().getScreenSize().getHeight()); if(pic.width>Toolkit.getDefaultToolkit().getScreenSize().getWidth() || pic.height>Toolkit.getDefaultToolkit().getScreenSize().getHeight()) { System.out.println("resize"); pic=pic.resize(); Dimension dim_screen = Toolkit.getDefaultToolkit().getScreenSize(); this.getContentPane().setPreferredSize(new Dimension(dim_screen.width, dim_screen.height-20)); } else { this.getContentPane().setPreferredSize(new Dimension(pic.width*2,pic.height)); } ImageIcon ic = new ImageIcon(pic.image); JLabel jl=new JLabel(ic); this.setResizable(false); //this.getContentPane().setPreferredSize(new Dimension(576*2,720)); this.pack(); if(jltab[cpt]!=null) { this.remove(jltab[cpt]); } jltab[cpt]=jl; if(cpt==0) { this.getContentPane().add(jl,BorderLayout.WEST); } else { this.getContentPane().add(jl, BorderLayout.EAST); } SwingUtilities.updateComponentTreeUI(this); this.jltab[cpt].addMouseListener(this); if(cpt == 0) { //premire image en rouge pictures[cpt] = pic; } else { pictures[cpt] = pic; } cpt=(cpt+1)%2; System.out.println("Frame size = " + this.getSize()); } public void openFileLocation() throws IOException{ JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "JPG & PNG & GIF Images", "jpg", "png","gif","jpeg"); chooser.setFileFilter(filter); if(!pathopendirectory.equals(".")) { chooser.setCurrentDirectory(new File(pathopendirectory)); } chooser.showOpenDialog(IHM.this); if(chooser.getSelectedFile() != null) { pathopendirectory = chooser.getSelectedFile().getAbsolutePath(); ouvrirImage(chooser.getSelectedFile().getAbsolutePath()); } } public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } public void keyPressed(KeyEvent e) { if (e.isControlDown() && e.getKeyChar() != 'o' && e.getKeyCode() == 79) { try { openFileLocation(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } public void mouseClicked(MouseEvent arg0) { System.out.println("cpt: " + cpt + " "+ arg0.getX()+" "+arg0.getY()); System.out.println(arg0.getComponent().toString()); Component c = arg0.getComponent(); if(c.equals(jltab[0])) { System.out.println("image 1"); reference.get(0).add(new Point(arg0.getX(), arg0.getY())); } else { System.out.println("image2"); reference.get(1).add(new Point(arg0.getX(), arg0.getY())); } } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }
//$HeadURL$ package org.deegree.feature.persistence.sql.id; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.deegree.commons.jdbc.SQLIdentifier; import org.deegree.commons.jdbc.TableName; import org.deegree.feature.persistence.sql.FeatureTypeMapping; import org.deegree.feature.persistence.sql.MappedAppSchema; import org.deegree.feature.persistence.sql.expressions.TableJoin; import org.deegree.feature.persistence.sql.rules.CompoundMapping; import org.deegree.feature.persistence.sql.rules.FeatureMapping; import org.deegree.feature.persistence.sql.rules.Mapping; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TableDependencies { private static Logger LOG = LoggerFactory.getLogger( TableDependencies.class ); private final Map<TableName, LinkedHashSet<SQLIdentifier>> tableToGenerators = new HashMap<TableName, LinkedHashSet<SQLIdentifier>>(); private final Map<TableName, LinkedHashSet<KeyPropagation>> tableToParents = new HashMap<TableName, LinkedHashSet<KeyPropagation>>(); private final Map<TableName, LinkedHashSet<KeyPropagation>> tableToChildren = new HashMap<TableName, LinkedHashSet<KeyPropagation>>(); public TableDependencies( FeatureTypeMapping[] ftMappings ) { if ( ftMappings != null ) { for ( FeatureTypeMapping ftMapping : ftMappings ) { buildFIDGenerator( ftMapping ); TableName currentTable = ftMapping.getFtTable(); for ( Mapping particle : ftMapping.getMappings() ) { buildDependencies( particle, currentTable ); } } } } private void buildFIDGenerator( FeatureTypeMapping ftMapping ) { // fid auto column FIDMapping fidMapping = ftMapping.getFidMapping(); SQLIdentifier fidColumn = new SQLIdentifier( fidMapping.getColumn() ); addAutoColumn( ftMapping.getFtTable(), fidColumn ); } private void buildDependencies( Mapping particle, TableName currentTable ) { List<TableJoin> joins = particle.getJoinedTable(); if ( joins != null && !joins.isEmpty() ) { if ( particle instanceof FeatureMapping ) { FeatureMapping f = (FeatureMapping) particle; if ( joins.size() != 1 ) { String msg = "Feature type joins with more than one table are not supported yet."; throw new UnsupportedOperationException( msg ); } TableJoin join = joins.get( 0 ); if ( f.getValueFtName() == null || join.getToTable().getName().equals( "?" ) ) { LOG.debug( "Found special key propagation (involving ambigous feature table). Needs implementation." ); return; } } for ( TableJoin join : joins ) { boolean found = false; TableName joinTable = join.getToTable(); // check for propagations from current table to joined table for ( int i = 0; i < join.getFromColumns().size(); i++ ) { SQLIdentifier fromColumn = join.getFromColumns().get( i ); SQLIdentifier toColumn = join.getToColumns().get( i ); LinkedHashSet<SQLIdentifier> linkedHashSet = tableToGenerators.get( currentTable ); if ( tableToGenerators.get( currentTable ) != null && tableToGenerators.get( currentTable ).contains( fromColumn ) ) { KeyPropagation prop = new KeyPropagation( join.getFromTable(), fromColumn, joinTable, toColumn ); LOG.debug( "Found key propagation (to join table): " + prop ); addChild( currentTable, prop ); addParent( joinTable, prop ); found = true; } } // add generated columns and check for propagations from joined table to current table Map<SQLIdentifier, IDGenerator> keyColumnToGenerator = join.getKeyColumnToGenerator(); for ( SQLIdentifier autoGenColumn : keyColumnToGenerator.keySet() ) { addAutoColumn( joinTable, autoGenColumn ); for ( int i = 0; i < join.getToColumns().size(); i++ ) { SQLIdentifier fromColumn = join.getFromColumns().get( i ); SQLIdentifier toColumn = join.getToColumns().get( i ); if ( autoGenColumn.equals( toColumn ) ) { KeyPropagation prop = new KeyPropagation( joinTable, toColumn, join.getFromTable(), fromColumn ); LOG.debug( "Found key propagation (from join table): " + prop ); addChild( joinTable, prop ); addParent( currentTable, prop ); found = true; } } } if ( !found ) { String msg = "Mapping configuration not transaction capable. Join " + join + " does not contain key generator on either side."; LOG.warn( msg ); } currentTable = joinTable; } } if ( particle instanceof CompoundMapping ) { for ( Mapping child : ( (CompoundMapping) particle ).getParticles() ) { buildDependencies( child, currentTable ); } } } private void addAutoColumn( TableName table, SQLIdentifier autoColumn ) { LinkedHashSet<SQLIdentifier> autoColumns = tableToGenerators.get( table ); if ( autoColumns == null ) { autoColumns = new LinkedHashSet<SQLIdentifier>(); tableToGenerators.put( table, autoColumns ); } autoColumns.add( autoColumn ); } private void addParent( TableName table, KeyPropagation propagation ) { LinkedHashSet<KeyPropagation> parents = tableToParents.get( table ); if ( parents == null ) { parents = new LinkedHashSet<KeyPropagation>(); tableToParents.put( table, parents ); } parents.add( propagation ); } private void addChild( TableName table, KeyPropagation propagation ) { LinkedHashSet<KeyPropagation> children = tableToChildren.get( table ); if ( children == null ) { children = new LinkedHashSet<KeyPropagation>(); tableToChildren.put( table, children ); } children.add( propagation ); } public Set<KeyPropagation> getParents( TableName table ) { return tableToParents.get( table ); } public Set<KeyPropagation> getChildren( TableName table ) { return tableToChildren.get( table ); } public Set<SQLIdentifier> getGenColumns( TableName table ) { return tableToGenerators.get( table ); } @Override public String toString() { StringBuilder sb = new StringBuilder(); Set<TableName> tables = new TreeSet<TableName>(); tables.addAll( tableToGenerators.keySet() ); tables.addAll( tableToParents.keySet() ); tables.addAll( tableToChildren.keySet() ); for ( TableName table : tables ) { sb.append( "\n\nTable: " + table ); sb.append( "\n -Generated key columns:" ); if ( tableToGenerators.get( table ) != null ) { for ( SQLIdentifier autoColumn : tableToGenerators.get( table ) ) { sb.append( "\n -" + autoColumn ); } } sb.append( "\n -Parents:" ); if ( tableToParents.get( table ) != null ) { for ( KeyPropagation parent : tableToParents.get( table ) ) { sb.append( "\n -" + parent ); } } sb.append( "\n -Children:" ); if ( tableToChildren.get( table ) != null ) { for ( KeyPropagation child : tableToChildren.get( table ) ) { sb.append( "\n -" + child ); } } } return sb.toString(); } public KeyPropagation getKeyPropagation( TableName fromTable, List<SQLIdentifier> fromColumns, TableName toTable, List<SQLIdentifier> toColumns ) { if ( fromColumns.size() != 1 ) { throw new UnsupportedOperationException( "Multi-column joins are not support for INSERT key propagation." ); } SQLIdentifier fromColumn = fromColumns.get( 0 ); SQLIdentifier toColumn = toColumns.get( 0 ); Set<KeyPropagation> candidates = tableToChildren.get( fromTable ); if ( candidates != null ) { for ( KeyPropagation candidate : candidates ) { if ( candidate.getFKTable().equals( toTable ) ) { if ( candidate.getPKColumn().equals( fromColumn ) && candidate.getFKColumn().equals( toColumn ) ) { return candidate; } } } } candidates = tableToParents.get( fromTable ); if ( candidates != null ) { for ( KeyPropagation candidate : candidates ) { if ( candidate.getPKTable().equals( toTable ) ) { if ( candidate.getFKColumn().equals( fromColumn ) && candidate.getPKColumn().equals( toColumn ) ) { return candidate; } } } } return null; } }
package se.raddo.raddose3D; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; /** * Holds X-ray cross section information for all elements of the periodic table. * The ElementDatabase class is a Singleton. Its constructor is not publically * accessible. * To obtain an instance of the ElementDatabase class, call the getInstance() * function. */ public class ElementDatabase { /** * Reference to the singleton instance of ElementDatabase. */ private static ElementDatabase singleton; /** * Map of all Element objects in the database. */ private final Map<Object, Element> elements; /** * List of available fields in the database file. */ public static enum DatabaseFields { /** K edge in Angstroms. */ EDGE_K(2), /** L edge in Angstroms. */ EDGE_L(3), /** M edge in Angstroms. */ EDGE_M(4), /** K coefficients in polynomial expansion. */ K_COEFF_0(5), K_COEFF_1(6), K_COEFF_2(7), K_COEFF_3(8), /** L coefficients in polynomial expansion. */ L_COEFF_0(9), L_COEFF_1(10), L_COEFF_2(11), L_COEFF_3(12), /** M coefficients in polynomial expansion. */ M_COEFF_0(13), M_COEFF_1(14), M_COEFF_2(15), M_COEFF_3(16), /** N coefficients for polynomial expansion. */ N_COEFF_0(17), N_COEFF_1(18), N_COEFF_2(19), N_COEFF_3(20), /** Atomic weight. */ ATOMIC_WEIGHT(23), /** Coherent coefficients for polynomial expansion. */ COHERENT_COEFF_0(24), COHERENT_COEFF_1(25), /** Coherent coefficients for polynomial expansion. */ COHERENT_COEFF_2(26), COHERENT_COEFF_3(27), /** Incoherent coefficients for polynomial expansion. */ INCOHERENT_COEFF_0(28), INCOHERENT_COEFF_1(29), /** Incoherent coefficients for polynomial expansion. */ INCOHERENT_COEFF_2(30), INCOHERENT_COEFF_3(31), L2(36), L3(37); /** * The position of each element in the database line. Index starting at 0. */ private final int field; /** * Initialization of each enum type entry. * * @param fieldnumber * The position of this element in the database line. Index * starting at 0. */ DatabaseFields(final int fieldnumber) { field = fieldnumber; } /** * Returns the position of this element in the database line. * * @return * Position of this element in the database line. Index starting at * 0. */ private int fieldNumber() { return field; } } /** * Location of MuCalcConstants library. */ private static final String MUCALC_FILE = "constants/MuCalcConstants.txt"; /** Position of the atomic number in the database file. */ private static final int ATOMIC_NUMBER = 0; /** Position of the element name in the database file. */ private static final int ELEMENT_NAME = 1; /** * Protected constructor of ElementDatabase. This reads in and parses the * constant file and creates the element map. * To obtain an instance of the ElementDatabase class, call the getInstance() * function. */ protected ElementDatabase() { elements = new HashMap<Object, Element>(); InputStreamReader isr = locateConstantsFile(); BufferedReader br = new BufferedReader(isr); // Read in constants file, consider some kind of error checking try { int totalLines = 0; String line; String[] components; Map<DatabaseFields, Double> elementInfo; while ((line = br.readLine()) != null) { totalLines++; // ignore commented out lines. if (Character.toString(line.charAt(0)).equals(" continue; } // array containing all those numbers from the calculator file components = line.split("\t", -1); // for (int j = 0; j < components.length; j++) { // // set components to -1 if they're empty, because // // otherwise Java gets upset. // String component = components[j]; // if ("".equals(component)) { // components[j] = "-1"; // Setting all the properties of the new atom. // component[x] where the values of x are in order // as listed in the constants file. try { elementInfo = new HashMap<DatabaseFields, Double>(); for (DatabaseFields df : DatabaseFields.values()) { elementInfo.put(df, new Double(components[df.fieldNumber()])); } int atomicNumber = Integer.valueOf(components[ATOMIC_NUMBER]); Element el = new Element(components[ELEMENT_NAME], atomicNumber, elementInfo); elements.put(components[ELEMENT_NAME].toLowerCase(), el); elements.put(atomicNumber, el); } catch (NumberFormatException e) { System.err.println("Could not parse line " + totalLines + " of element database file " + MUCALC_FILE); e.printStackTrace(); } } br.close(); isr.close(); } catch (IOException e) { throw new RuntimeException("Error accessing element database file " + MUCALC_FILE, e); } } /** * Try to locate MUCALC_FILE. This may be in the class path (ie. within a .jar * file), or in the file system. * * @return * InputStreamReader pointing to the correct resource. * @throws RuntimeException * If the file could not be found. */ private InputStreamReader locateConstantsFile() throws RuntimeException { // Try to find it within class path; InputStream is = getClass().getResourceAsStream("/" + MUCALC_FILE); if (is == null) { // If it is not within the class path, try via the file system. try { is = new FileInputStream(MUCALC_FILE); } catch (FileNotFoundException e) { // give up throw new RuntimeException("Cannot find element database file " + MUCALC_FILE, e); } } return new InputStreamReader(is); } /** * Returns an instance of the element database. The true constructor of * ElementDatabase is private, as ElementDatabase is a Singleton. * * @return * Instance of the element database. */ @SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel") public static synchronized ElementDatabase getInstance() { if (singleton == null) { singleton = new ElementDatabase(); } return singleton; } /** * Returns the Element object associated with the chemical element with z * protons. * * @param z * atomic number * @return * associated Element object */ public Element getElement(final int z) { return elements.get(z); } /** * Returns the Element object associated with the specified chemical element. * * @param name * name of a chemical element * @return * associated Element object */ public Element getElement(final String name) { return elements.get(name.toLowerCase()); } }
package org.eclipse.smarthome.binding.tradfri.handler; import static org.eclipse.smarthome.binding.tradfri.TradfriBindingConstants.*; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.TimeUnit; import org.eclipse.smarthome.binding.tradfri.DeviceConfig; import org.eclipse.smarthome.binding.tradfri.internal.CoapCallback; import org.eclipse.smarthome.binding.tradfri.internal.TradfriCoapClient; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.binding.BaseThingHandler; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; /** * The {@link TradfriLightHandler} is responsible for handling commands for * individual lights. * * @author Kai Kreuzer - Initial contribution */ public class TradfriLightHandler extends BaseThingHandler implements CoapCallback { private final Logger logger = LoggerFactory.getLogger(TradfriLightHandler.class); // step size for increase/decrease commands private static final int STEP = 10; // keeps track of the current state for handling of increase/decrease private LightData state; // the unique instance id of the light private Integer id; // used to check whether we have already been disposed when receiving data asynchronously private volatile boolean active; private TradfriCoapClient coapClient; public TradfriLightHandler(Thing thing) { super(thing); } @Override public synchronized void initialize() { this.id = getConfigAs(DeviceConfig.class).id; TradfriGatewayHandler handler = (TradfriGatewayHandler) getBridge().getHandler(); String uriString = handler.getGatewayURI() + "/" + id; try { URI uri = new URI(uriString); coapClient = new TradfriCoapClient(uri); coapClient.setEndpoint(handler.getEndpoint()); } catch (URISyntaxException e) { logger.debug("Illegal device URI `{}`: {}", uriString, e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage()); return; } updateStatus(ThingStatus.UNKNOWN); active = true; scheduler.schedule(() -> { coapClient.startObserve(this); }, 3, TimeUnit.SECONDS); } @Override public synchronized void dispose() { active = false; if (coapClient != null) { coapClient.shutdown(); } super.dispose(); } @Override public void setStatus(ThingStatus status, ThingStatusDetail statusDetail) { if (active && getBridge().getStatus() != ThingStatus.OFFLINE && status != ThingStatus.ONLINE) { updateStatus(status, statusDetail); // we are offline and lost our observe relation - let's try to establish the connection in 10 seconds again scheduler.schedule(() -> { coapClient.startObserve(this); }, 10, TimeUnit.SECONDS); } } @Override public void onUpdate(JsonElement data) { if (active && !(data.isJsonNull())) { state = new LightData(data); updateStatus(state.getReachabilityStatus() ? ThingStatus.ONLINE : ThingStatus.OFFLINE); if (!state.getOnOffState()) { logger.debug("Setting state to OFF"); updateState(CHANNEL_BRIGHTNESS, PercentType.ZERO); // if we are turned off, we do not set any brightness value return; } PercentType dimmer = state.getBrightness(); if (dimmer != null) { logger.debug("Updating brightness to {}", dimmer); updateState(CHANNEL_BRIGHTNESS, dimmer); } PercentType colorTemp = state.getColorTemperature(); if (colorTemp != null) { logger.debug("Updating color temperature to {} ", colorTemp); updateState(CHANNEL_COLOR_TEMPERATURE, colorTemp); } } } private void set(String payload) { logger.debug("Sending payload: {}", payload); coapClient.asyncPut(payload, this); } private void setBrightness(PercentType percent) { LightData data = new LightData(); data.setBrightness(percent).setTransitionTime(DEFAULT_DIMMER_TRANSITION_TIME); set(data.getJsonString()); } private void setState(OnOffType onOff) { LightData data = new LightData(); data.setOnOffState(onOff == OnOffType.ON); set(data.getJsonString()); } private void setColorTemperature(PercentType percent) { LightData data = new LightData(); data.setColorTemperature(percent).setTransitionTime(DEFAULT_DIMMER_TRANSITION_TIME); set(data.getJsonString()); } @Override public void handleCommand(ChannelUID channelUID, Command command) { if (command instanceof RefreshType) { logger.debug("Refreshing channel {}", channelUID); coapClient.asyncGet(this); return; } switch (channelUID.getId()) { case CHANNEL_BRIGHTNESS: handleBrightnessCommand(command); break; case CHANNEL_COLOR_TEMPERATURE: handleColorTemperatureCommand(command); break; default: logger.error("Unknown channel UID {}", channelUID); } } private void handleBrightnessCommand(Command command) { if (command instanceof PercentType) { setBrightness((PercentType) command); } else if (command instanceof OnOffType) { setState(((OnOffType) command)); } else if (command instanceof IncreaseDecreaseType) { if (state != null && state.getBrightness() != null) { int current = state.getBrightness().intValue(); if (IncreaseDecreaseType.INCREASE.equals(command)) { setBrightness(new PercentType(Math.min(current + STEP, PercentType.HUNDRED.intValue()))); } else { setBrightness(new PercentType(Math.max(current - STEP, PercentType.ZERO.intValue()))); } } else { logger.debug("Cannot handle inc/dec as current state is not known."); } } else { logger.debug("Cannot handle command {} for channel {}", command, CHANNEL_BRIGHTNESS); } } private void handleColorTemperatureCommand(Command command) { if (command instanceof PercentType) { setColorTemperature((PercentType) command); } else if (command instanceof IncreaseDecreaseType) { if (state != null && state.getColorTemperature() != null) { int current = state.getColorTemperature().intValue(); if (IncreaseDecreaseType.INCREASE.equals(command)) { setColorTemperature(new PercentType(Math.min(current + STEP, PercentType.HUNDRED.intValue()))); } else { setColorTemperature(new PercentType(Math.max(current - STEP, PercentType.ZERO.intValue()))); } } else { logger.debug("Cannot handle inc/dec as current state is not known."); } } else { logger.debug("Can't handle command {} on channel {}", command, CHANNEL_COLOR_TEMPERATURE); } } /** * This class is a Java wrapper for the raw JSON data about the light state. */ private static class LightData { // which uses x,y-coordinates. // Its own app comes with 3 predefined color temperature settings (0,1,2), which have those values: private final static double[] X = new double[] { 24933.0, 30138.0, 33137.0 }; private final static double[] Y = new double[] { 24691.0, 26909.0, 27211.0 }; private final Logger logger = LoggerFactory.getLogger(LightData.class); JsonObject root; JsonArray array; JsonObject attributes; public LightData() { root = new JsonObject(); array = new JsonArray(); attributes = new JsonObject(); array.add(attributes); root.add(LIGHT, array); } public LightData(JsonElement json) { try { root = json.getAsJsonObject(); array = root.getAsJsonArray(LIGHT); attributes = array.get(0).getAsJsonObject(); } catch (JsonSyntaxException e) { logger.error("JSON error: {}", e.getMessage(), e); } } public LightData setBrightness(PercentType brightness) { attributes.add(DIMMER, new JsonPrimitive(Math.round(brightness.floatValue() / 100.0f * 254))); return this; } public PercentType getBrightness() { JsonElement dimmer = attributes.get(DIMMER); if (dimmer != null) { int b = dimmer.getAsInt(); if (b == 1) { return new PercentType(1); } return new PercentType((int) Math.round(b / 2.54)); } else { return null; } } public boolean getReachabilityStatus() { if (root.get(REACHABILITY_STATE) != null) { return root.get(REACHABILITY_STATE).getAsInt() == 1; } else { return false; } } public LightData setTransitionTime(int seconds) { attributes.add(TRANSITION_TIME, new JsonPrimitive(seconds)); return this; } @SuppressWarnings("unused") public int getTransitionTime() { JsonElement transitionTime = attributes.get(TRANSITION_TIME); if (transitionTime != null) { return transitionTime.getAsInt(); } else { return 0; } } public LightData setColorTemperature(PercentType c) { double percent = c.doubleValue(); long x, y; if (percent < 50.0) { // we calculate a value that is between preset 0 and 1 double p = percent / 50.0; x = Math.round(X[0] + p * (X[1] - X[0])); y = Math.round(Y[0] + p * (Y[1] - Y[0])); } else { // we calculate a value that is between preset 1 and 2 double p = (percent - 50) / 50.0; x = Math.round(X[1] + p * (X[2] - X[1])); y = Math.round(Y[1] + p * (Y[2] - Y[1])); } logger.debug("New color temperature: {},{} ({} %)", x, y, percent); attributes.add(COLOR_X, new JsonPrimitive(x)); attributes.add(COLOR_Y, new JsonPrimitive(y)); return this; } PercentType getColorTemperature() { // we only need to check one of the coordinates and figure out where between the presets we are JsonElement colorX = attributes.get(COLOR_X); if (colorX != null) { double x = colorX.getAsInt(); double value = 0.0; if (x > X[1]) { // is it between preset 1 and 2? value = (x - X[1]) / (X[2] - X[1]) / 2.0 + 0.5; } else { // it is between preset 0 and 1 value = (x - X[0]) / (X[1] - X[0]) / 2.0; } return new PercentType((int) Math.round(value * 100.0)); } else { return null; } } LightData setOnOffState(boolean on) { attributes.add(ONOFF, new JsonPrimitive(on ? 1 : 0)); return this; } boolean getOnOffState() { JsonElement onOff = attributes.get(ONOFF); if (onOff != null) { return attributes.get(ONOFF).getAsInt() == 1; } else { return false; } } String getJsonString() { return root.toString(); } } }
package org.opendaylight.controller.sal.binding.test.connect.dom; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.base.Optional; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.MoreExecutors; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.opendaylight.controller.md.sal.binding.api.MountPoint; import org.opendaylight.controller.md.sal.binding.api.MountPointService; import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener; import org.opendaylight.controller.md.sal.dom.api.DOMRpcException; import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult; import org.opendaylight.controller.md.sal.dom.api.DOMRpcService; import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult; import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry; import org.opendaylight.controller.sal.binding.test.util.BindingBrokerTestFactory; import org.opendaylight.controller.sal.binding.test.util.BindingTestContext; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.rpcservice.rev140701.OpendaylightTestRpcServiceService; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.rpcservice.rev140701.RockTheHouseInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.binding.YangModuleInfo; import org.opendaylight.yangtools.yang.binding.util.BindingReflections; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; public class DOMRpcServiceTestBugfix560 { private final static String RPC_SERVICE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:bi:ba:rpcservice"; private final static String REVISION_DATE = "2014-07-01"; private final static QName RPC_NAME = QName.create(RPC_SERVICE_NAMESPACE, REVISION_DATE, "rock-the-house"); private static final String TLL_NAME = "id"; private static final QName TLL_NAME_QNAME = QName.create(TopLevelList.QNAME, "name"); private static final InstanceIdentifier<TopLevelList> BA_MOUNT_ID = createBATllIdentifier(TLL_NAME); private static final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier BI_MOUNT_ID = createBITllIdentifier(TLL_NAME); private BindingTestContext testContext; private DOMMountPointService domMountPointService; private MountPointService bindingMountPointService; private SchemaContext schemaContext; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { final BindingBrokerTestFactory testFactory = new BindingBrokerTestFactory(); testFactory.setExecutor(MoreExecutors.newDirectExecutorService()); testFactory.setStartWithParsedSchema(true); testContext = testFactory.getTestContext(); testContext.start(); domMountPointService = testContext.getDomMountProviderService(); bindingMountPointService = testContext.getBindingMountPointService(); assertNotNull(domMountPointService); final YangModuleInfo moduleInfo = BindingReflections.getModuleInfo(OpendaylightTestRpcServiceService.class); assertNotNull(moduleInfo); schemaContext = YangParserTestUtils.parseYangSources(StatementParserMode.DEFAULT_MODE, null, YangTextSchemaSource.delegateForByteSource(RevisionSourceIdentifier.create( moduleInfo.getName().getLocalName(), moduleInfo.getName().getRevision()), moduleInfo.getYangTextByteSource())); } private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBITllIdentifier( final String mount) { return org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier .builder().node(Top.QNAME) .node(TopLevelList.QNAME) .nodeWithKey(TopLevelList.QNAME, TLL_NAME_QNAME, mount) .build(); } private static InstanceIdentifier<TopLevelList> createBATllIdentifier( final String mount) { return InstanceIdentifier.builder(Top.class) .child(TopLevelList.class, new TopLevelListKey(mount)).build(); } @Test public void test() throws ExecutionException, InterruptedException { // FIXME: This is made to only make sure instance identifier codec for path is instantiated. domMountPointService .createMountPoint(BI_MOUNT_ID).addService(DOMRpcService.class, new DOMRpcService() { @Override public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(final T arg0) { // TODO Auto-generated method stub return null; } @Override public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final SchemaPath arg0, final NormalizedNode<?, ?> arg1) { final DOMRpcResult result = new DefaultDOMRpcResult((NormalizedNode<?, ?>) null); return Futures.immediateCheckedFuture(result); } }).register(); final Optional<MountPoint> mountInstance = bindingMountPointService.getMountPoint(BA_MOUNT_ID); assertTrue(mountInstance.isPresent()); final Optional<RpcConsumerRegistry> rpcRegistry = mountInstance.get().getService(RpcConsumerRegistry.class); assertTrue(rpcRegistry.isPresent()); final OpendaylightTestRpcServiceService rpcService = rpcRegistry.get() .getRpcService(OpendaylightTestRpcServiceService.class); assertNotNull(rpcService); try { final Future<RpcResult<Void>> result = rpcService .rockTheHouse(new RockTheHouseInputBuilder().build()); assertTrue(result.get().isSuccessful()); } catch (final IllegalStateException ex) { fail("OpendaylightTestRpcServiceService class doesn't contain rockTheHouse method!"); } } /** * @throws java.lang.Exception */ @After public void teardown() throws Exception { testContext.close(); } }
package fr.openwide.core.wicket.more.security.page; import org.apache.wicket.Page; import org.springframework.security.web.savedrequest.SavedRequest; import fr.openwide.core.spring.util.StringUtils; import fr.openwide.core.wicket.more.AbstractCoreSession; import fr.openwide.core.wicket.more.link.descriptor.IPageLinkDescriptor; import fr.openwide.core.wicket.more.link.descriptor.builder.LinkDescriptorBuilder; import fr.openwide.core.wicket.more.markup.html.CoreWebPage; import fr.openwide.core.wicket.more.request.cycle.RequestCycleUtils; public class LoginSuccessPage extends CoreWebPage { private static final long serialVersionUID = -875304387617628398L; public static final String SPRING_SECURITY_SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST"; public static final String WICKET_BEHAVIOR_LISTENER_URL_FRAGMENT = "IBehaviorListener"; public static IPageLinkDescriptor linkDescriptor() { return new LinkDescriptorBuilder().page(LoginSuccessPage.class).build(); } public LoginSuccessPage() { } @Override protected void onInitialize() { super.onInitialize(); redirectToSavedPage(); } protected void redirectToSavedPage() { AbstractCoreSession<?> session = AbstractCoreSession.get(); IPageLinkDescriptor pageLinkDescriptor = session.getRedirectPageLinkDescriptor(); if (pageLinkDescriptor != null) { throw pageLinkDescriptor.newRestartResponseException(); } String redirectUrl = null; if (StringUtils.hasText(session.getRedirectUrl())) { redirectUrl = session.getRedirectUrl(); } else { Object savedRequest = RequestCycleUtils.getCurrentContainerRequest().getSession().getAttribute(SPRING_SECURITY_SAVED_REQUEST); if (savedRequest instanceof SavedRequest) { redirectUrl = ((SavedRequest) savedRequest).getRedirectUrl(); } RequestCycleUtils.getCurrentContainerRequest().getSession().removeAttribute(SPRING_SECURITY_SAVED_REQUEST); } if (isUrlValid(redirectUrl)) { redirect(redirectUrl); } else { redirect(getDefaultRedirectPage()); } } protected Class<? extends Page> getDefaultRedirectPage() { return getApplication().getHomePage(); } protected boolean isUrlValid(String url) { return StringUtils.hasText(url) && !StringUtils.contains(url, WICKET_BEHAVIOR_LISTENER_URL_FRAGMENT); } }
package org.geomajas.widget.advancedviews.client.widget; import java.util.ArrayList; import java.util.List; import org.geomajas.annotation.Api; import org.geomajas.configuration.FeatureStyleInfo; import org.geomajas.configuration.NamedStyleInfo; import org.geomajas.configuration.client.ClientLayerInfo; import org.geomajas.configuration.client.ClientLayerTreeInfo; import org.geomajas.configuration.client.ClientLayerTreeNodeInfo; import org.geomajas.configuration.client.ClientToolInfo; import org.geomajas.gwt.client.action.ToolbarBaseAction; import org.geomajas.gwt.client.action.layertree.LayerTreeAction; import org.geomajas.gwt.client.action.layertree.LayerTreeModalAction; import org.geomajas.gwt.client.action.layertree.LayerTreeRegistry; import org.geomajas.gwt.client.map.event.LayerChangedHandler; import org.geomajas.gwt.client.map.event.LayerFilteredEvent; import org.geomajas.gwt.client.map.event.LayerFilteredHandler; import org.geomajas.gwt.client.map.event.LayerLabeledEvent; import org.geomajas.gwt.client.map.event.LayerShownEvent; import org.geomajas.gwt.client.map.event.LayerStyleChangeEvent; import org.geomajas.gwt.client.map.event.LayerStyleChangedHandler; import org.geomajas.gwt.client.map.layer.Layer; import org.geomajas.gwt.client.map.layer.RasterLayer; import org.geomajas.gwt.client.map.layer.VectorLayer; import org.geomajas.gwt.client.widget.MapWidget; import org.geomajas.widget.advancedviews.client.AdvancedViewsMessages; import org.geomajas.widget.advancedviews.client.util.LayerIconUtil; import org.geomajas.widget.advancedviews.client.util.UrlBuilder; import org.geomajas.widget.advancedviews.client.util.WidgetInfoUtil; import org.geomajas.widget.advancedviews.configuration.client.LayerTreeWithLegendInfo; import com.google.gwt.core.client.GWT; import com.google.gwt.event.shared.HandlerRegistration; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.SelectionType; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.ImgButton; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.LayoutSpacer; import com.smartgwt.client.widgets.tree.TreeGrid; import com.smartgwt.client.widgets.tree.TreeNode; import com.smartgwt.client.widgets.tree.events.LeafClickEvent; /** * A layertree widget with combined legend per layer. * * @author Kristof Heirwegh * @since 1.0.0 */ @Api public class LayerTreeWithLegend extends LayerTreeBase { private static final String LEGEND_ICONS_PATH = "d/legendIcons"; private static final String SHOW_LAYERINFO_ICON = "[ISOMORPHIC]/geomajas/silk/cog.png"; private AdvancedViewsMessages messages = GWT.create(AdvancedViewsMessages.class); private static final String EXPANDED_ATTR = "isExpanded"; private final MapWidget mapWidget; private final List<HandlerRegistration> registrations = new ArrayList<HandlerRegistration>(); protected LayerTreeTreeNode rollOverLayerTreeNode; public LayerTreeWithLegend(final MapWidget mapWidget) { super(mapWidget); this.mapWidget = mapWidget; treeGrid.setShowRollOverCanvas(true); } public int getIconSize() { return treeGrid.getImageSize(); } public void setIconSize(int iconSize) { treeGrid.setIconSize(iconSize); } /** * Processes a treeNode (add it to the TreeGrid). * * @param treeNode * The treeNode to process * @param nodeRoot * The root node to which the treeNode has to be added * @param refresh * True if the tree is refreshed (causing it to keep its expanded * state) */ protected void processNode(final ClientLayerTreeNodeInfo treeNode, final TreeNode nodeRoot, final boolean refresh) { if (null != treeNode) { String treeNodeLabel = treeNode.getLabel(); final TreeNode node = new TreeNode(treeNodeLabel); node.setAttribute(EXPANDED_ATTR, treeNode.isExpanded()); tree.add(node, nodeRoot); // (final leafs) for (ClientLayerInfo info : treeNode.getLayers()) { Layer<?> layer = mapModel.getLayer(info.getId()); LayerTreeLegendNode ltln = new LayerTreeLegendNode(this.tree, layer); tree.add(ltln, node); ltln.init(); } // treeNodes List<ClientLayerTreeNodeInfo> childs = treeNode.getTreeNodes(); for (ClientLayerTreeNodeInfo newNode : childs) { processNode(newNode, node, refresh); } } } /** * When a legendItem is selected, select the layer instead. */ public void onLeafClick(LeafClickEvent event) { LayerTreeTreeNode layerTreeNode; if (event.getLeaf() instanceof LayerTreeLegendItemNode) { layerTreeNode = ((LayerTreeLegendItemNode) event.getLeaf()).parent; treeGrid.deselectRecord(event.getLeaf()); treeGrid.selectRecord(layerTreeNode); } else { layerTreeNode = (LayerTreeTreeNode) event.getLeaf(); } // -- update model mapModel.selectLayer(layerTreeNode.getLayer()); } /** * Node with legend for LayerNode. */ public class LayerTreeLegendNode extends LayerTreeTreeNode { public LayerTreeLegendNode(RefreshableTree tree, Layer<?> layer) { super(tree, layer); } public void init() { if (layer instanceof VectorLayer) { VectorLayer vl = (VectorLayer) layer; NamedStyleInfo nsi = vl.getLayerInfo().getNamedStyleInfo(); for (FeatureStyleInfo fsi : nsi.getFeatureStyles()) { LayerTreeLegendItemNode tn = new LayerTreeLegendItemNode(this, vl.getServerLayerId(), nsi.getName(), fsi); tree.add(tn, this); } } else { RasterLayer rl = (RasterLayer) layer; LayerTreeLegendItemNode tn = new LayerTreeLegendItemNode(this, rl.getServerLayerId(), LayerIconUtil.getSmallLayerIconUrl(rl)); tree.add(tn, this); } } } /** * Node which displays a legend icon + description. */ public class LayerTreeLegendItemNode extends LayerTreeTreeNode { private LayerTreeLegendNode parent; private UrlBuilder url = new UrlBuilder(GWT.getHostPageBaseURL()); // rasterlayer public LayerTreeLegendItemNode(LayerTreeLegendNode parent, String layerId, String rasterIconUrl) { super(parent.tree, parent.layer); this.parent = parent; setTitle(layer.getLabel()); setName(parent.getAttribute("id") + "_legend"); url.addPath(LEGEND_ICONS_PATH); url.addParameter("widgetId", LayerTreeWithLegend.this.getID()); if (rasterIconUrl != null) { url.addParameter("styleName", rasterIconUrl); } url.addParameter("layerId", layerId); setIcon(url.toString()); } // vectorlayer public LayerTreeLegendItemNode(LayerTreeLegendNode parent, String layerId, String styleName, FeatureStyleInfo fsi) { super(parent.tree, parent.layer); this.parent = parent; setName(fsi.getName()); url.addPath(LEGEND_ICONS_PATH); url.addParameter("widgetId", LayerTreeWithLegend.this.getID()); url.addParameter("layerId", layerId); url.addParameter("styleName", styleName); url.addParameter("featureStyleId", fsi.getStyleId()); setIcon(url.toString()); } @Override public void updateIcon() { // leave my icons alone! } public LayerTreeLegendNode getParent() { return parent; } public void setParent(LayerTreeLegendNode parent) { this.parent = parent; } } @Override protected void syncNodeState(boolean layersOnly) { for (TreeNode childnode : tree.getAllNodes(tree.getRoot())) { if (childnode instanceof LayerTreeLegendNode) { if (((LayerTreeLegendNode) childnode).layer.isShowing()) { tree.openFolder(childnode); } else { tree.closeFolder(childnode); } } else if (!layersOnly && !(childnode instanceof LayerTreeLegendItemNode)) { if (childnode.getAttributeAsBoolean(EXPANDED_ATTR)) { tree.openFolder(childnode); } else { tree.closeFolder(childnode); } } } } @Override protected TreeGrid createTreeGrid() { return createTreeGridInfoWindowRollover(); } @Override protected void onIconClick(TreeNode node) { if (node instanceof LayerTreeLegendNode) { super.onIconClick(node); } else if (node instanceof TreeNode) { // TODO -- show/hide all layers in folder GWT.log("TODO"); } } protected TreeGrid createTreeGridInfoWindowRollover() { return new TreeGrid() { private HLayout rollOverTools; private HLayout emptyRollOver; @Override protected Canvas getRollOverCanvas(Integer rowNum, Integer colNum) { if (rollOverTools == null) { rollOverTools = new HLayout(); rollOverTools.setSnapTo("TR"); rollOverTools.setWidth(25); rollOverTools.setHeight(LAYERTREEBUTTON_SIZE); emptyRollOver = new HLayout(); emptyRollOver.setWidth(1); emptyRollOver.setHeight(LAYERTREEBUTTON_SIZE); ImgButton showInfo = new ImgButton(); showInfo.setShowDown(false); showInfo.setShowRollOver(false); showInfo.setLayoutAlign(Alignment.CENTER); showInfo.setSrc(SHOW_LAYERINFO_ICON); showInfo.setPrompt(messages.layerTreeWithLegendLayerActionsToolTip()); showInfo.setHeight(16); showInfo.setWidth(16); showInfo.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { LayerActions la = new LayerActions(rollOverLayerTreeNode.getLayer()); la.draw(); } }); rollOverTools.addMember(showInfo); } ListGridRecord lgr = this.getRecord(rowNum); if (lgr instanceof LayerTreeLegendItemNode) { rollOverLayerTreeNode = ((LayerTreeLegendItemNode) lgr).parent; } else if (lgr instanceof LayerTreeLegendNode) { rollOverLayerTreeNode = (LayerTreeTreeNode) lgr; } else { rollOverLayerTreeNode = null; rollOverTools.setVisible(false); return emptyRollOver; } rollOverTools.setVisible(true); return rollOverTools; } }; } protected TreeGrid createTreeGridFullRollover() { return new TreeGrid() { private HLayout rollOverTools; private HLayout emptyRollOver; private Canvas[] toolButtons; @Override protected Canvas getRollOverCanvas(Integer rowNum, Integer colNum) { if (rollOverTools == null) { rollOverTools = new HLayout(); rollOverTools.setSnapTo("TR"); rollOverTools.setWidth(50); rollOverTools.setHeight(LAYERTREEBUTTON_SIZE); emptyRollOver = new HLayout(); emptyRollOver.setWidth(1); emptyRollOver.setHeight(LAYERTREEBUTTON_SIZE); ClientLayerTreeInfo layerTreeInfo = mapModel.getMapInfo().getLayerTree(); if (layerTreeInfo != null) { for (ClientToolInfo tool : layerTreeInfo.getTools()) { String id = tool.getId(); IButton button = null; ToolbarBaseAction action = LayerTreeRegistry.getToolbarAction(id, mapWidget); if (action instanceof LayerTreeAction) { button = new LayerTreeButton(LayerTreeWithLegend.this, (LayerTreeAction) action); } else if (action instanceof LayerTreeModalAction) { button = new LayerTreeModalButton(LayerTreeWithLegend.this, (LayerTreeModalAction) action); } if (button != null) { rollOverTools.addMember(button); LayoutSpacer spacer = new LayoutSpacer(); spacer.setWidth(2); rollOverTools.addMember(spacer); } } } toolButtons = rollOverTools.getMembers(); } ListGridRecord lgr = this.getRecord(rowNum); if (lgr instanceof LayerTreeLegendItemNode) { rollOverLayerTreeNode = ((LayerTreeLegendItemNode) lgr).parent; } else if (lgr instanceof LayerTreeLegendNode) { rollOverLayerTreeNode = (LayerTreeTreeNode) lgr; } else { rollOverLayerTreeNode = null; rollOverTools.setVisible(false); return emptyRollOver; } rollOverTools.setVisible(true); updateButtonIconsAndStates(); return rollOverTools; } /** * Updates the icons and the state of the buttons in the toolbar * based upon the current layer * * @param toolStripMembers * data for the toolbar */ private void updateButtonIconsAndStates() { for (Canvas toolButton : toolButtons) { if (toolButton instanceof LayerTreeModalButton) { ((LayerTreeModalButton) toolButton).update(); } else if (toolButton instanceof LayerTreeButton) { ((LayerTreeButton) toolButton).update(); } } } }; } /** * General definition of an action button for the layer tree. * * @author Frank Wynants * @author Pieter De Graef */ private class LayerTreeButton extends IButton { private LayerTreeWithLegend tree; private LayerTreeAction action; public LayerTreeButton(final LayerTreeWithLegend tree, final LayerTreeAction action) { this.tree = tree; this.action = action; setWidth(LAYERTREEBUTTON_SIZE); setHeight(LAYERTREEBUTTON_SIZE); setIconSize(LAYERTREEBUTTON_SIZE - 8); setIcon(action.getIcon()); setTooltip(action.getTooltip()); setActionType(SelectionType.BUTTON); setShowDisabledIcon(false); addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { try { action.onClick(tree.rollOverLayerTreeNode.getLayer()); update(); } catch (Throwable t) { GWT.log("LayerTreeButton onClick error", t); } } }); } public void update() { LayerTreeTreeNode selected = tree.rollOverLayerTreeNode; if (selected != null && action.isEnabled(selected.getLayer())) { setDisabled(false); setIcon(action.getIcon()); setTooltip(action.getTooltip()); } else { setDisabled(true); GWT.log("LayerTreeButton" + action.getDisabledIcon()); setIcon(action.getDisabledIcon()); setTooltip(""); } } } /** * General definition of a modal button for the layer tree. * * @author Frank Wynants * @author Pieter De Graef */ private class LayerTreeModalButton extends IButton { private LayerTreeWithLegend tree; private LayerTreeModalAction modalAction; /** * Constructor * * @param tree * The currently selected layer * @param modalAction * The action coupled to this button */ public LayerTreeModalButton(final LayerTreeWithLegend tree, final LayerTreeModalAction modalAction) { this.tree = tree; this.modalAction = modalAction; setWidth(LAYERTREEBUTTON_SIZE); setHeight(LAYERTREEBUTTON_SIZE); setIconSize(LAYERTREEBUTTON_SIZE - 8); setIcon(modalAction.getDeselectedIcon()); setActionType(SelectionType.CHECKBOX); setTooltip(modalAction.getDeselectedTooltip()); setShowDisabledIcon(false); this.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { LayerTreeTreeNode selectedLayerNode = tree.rollOverLayerTreeNode; if (LayerTreeModalButton.this.isSelected()) { modalAction.onSelect(selectedLayerNode.getLayer()); } else { modalAction.onDeselect(selectedLayerNode.getLayer()); } selectedLayerNode.updateIcon(); update(); } }); } public void update() { LayerTreeTreeNode selected = tree.rollOverLayerTreeNode; if (selected != null && modalAction.isEnabled(selected.getLayer())) { setDisabled(false); } else { setSelected(false); setDisabled(true); GWT.log("LayerTreeModalButton" + modalAction.getDisabledIcon()); setIcon(modalAction.getDisabledIcon()); setTooltip(""); } if (selected != null && modalAction.isSelected(selected.getLayer())) { setIcon(modalAction.getSelectedIcon()); setTooltip(modalAction.getSelectedTooltip()); select(); } else if (selected != null) { setIcon(modalAction.getDeselectedIcon()); setTooltip(modalAction.getDeselectedTooltip()); deselect(); } } } // -- part of legend @Override protected void initialize() { super.initialize(); LayerTreeWithLegendInfo ltwli = WidgetInfoUtil.getClientWidgetInfo(LayerTreeWithLegendInfo.IDENTIFIER, mapWidget); setIconSize(ltwli == null ? DEFAULT_ICONSIZE : ltwli.getIconSize()); for (Layer<?> layer : mapModel.getLayers()) { registrations.add(layer.addLayerChangedHandler(new LayerChangedHandler() { public void onLabelChange(LayerLabeledEvent event) { GWT.log("Legend: onLabelChange() - " + event.getLayer().getLabel()); // find the node & update the icon for (TreeNode node : tree.getAllNodes()) { if (node.getName().equals(event.getLayer().getLabel())) { if (node instanceof LayerTreeTreeNode) { ((LayerTreeTreeNode) node).updateIcon(); } } } } public void onVisibleChange(LayerShownEvent event) { GWT.log("Legend: onVisibleChange() - " + event.getLayer().getLabel()); // find the node & update the icon for (TreeNode node : tree.getAllNodes()) { if (node.getName().equals(event.getLayer().getLabel())) { if (node instanceof LayerTreeTreeNode) { ((LayerTreeTreeNode) node).updateIcon(); } } } } })); registrations.add(layer.addLayerStyleChangedHandler(new LayerStyleChangedHandler() { public void onLayerStyleChange(LayerStyleChangeEvent event) { GWT.log("Legend: onLayerStyleChange()"); // TODO update layerstyles } })); if (layer instanceof VectorLayer) { VectorLayer vl = (VectorLayer) layer; registrations.add(vl.addLayerFilteredHandler(new LayerFilteredHandler() { public void onFilterChange(LayerFilteredEvent event) { GWT.log("Legend: onLayerFilterChange() - " + event.getLayer().getLabel()); // find the node & update the icon for (TreeNode node : tree.getAllNodes()) { if (node.getName().equals(event.getLayer().getLabel())) { if (node instanceof LayerTreeTreeNode) { ((LayerTreeTreeNode) node).updateIcon(); } } } } })); } } } /** Remove all handlers on unload. */ protected void onUnload() { if (registrations != null) { for (HandlerRegistration registration : registrations) { registration.removeHandler(); } } super.onUnload(); } }
package org.kaaproject.kaa.server.verifiers.facebook.verifier; import org.junit.BeforeClass; import org.junit.Test; import org.kaaproject.kaa.server.common.verifier.UserVerifierCallback; import org.kaaproject.kaa.server.verifiers.facebook.config.gen.FacebookAvroConfig; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import static org.mockito.Mockito.*; public class FacebookUserVerifierTest extends FacebookUserVerifier { private static FacebookUserVerifier verifier; private static String userId = "1557997434440423"; private static FacebookAvroConfig config; private static HttpURLConnection connection; @BeforeClass public static void setUp() { config = mock(FacebookAvroConfig.class); when(config.getMaxParallelConnections()).thenReturn(1); when(config.getAppId()).thenReturn("xxx"); when(config.getAppSecret()).thenReturn("xxx"); } @Test public void invalidUserAccessCodeTest() { verifier = new MyFacebookVerifier(200, "{\"data\":{\"error\":{\"code\":190,\"message\":\"" + "The access token could not be decrypte" + "d\"},\"is_valid\":false,\"scopes\":[]}}"); verifier.init(null, config); UserVerifierCallback callback = mock(UserVerifierCallback.class); verifier.checkAccessToken("invalidUserId", "falseUserAccessToken", callback); verify(callback, Mockito.timeout(1000).atLeastOnce()).onVerificationFailure(anyString()); } @Test public void incompatibleUserIds() { verifier = new MyFacebookVerifier(200, "{\"data\":{\"app_id\":\"1557997434440423\"," + "\"application\":\"testApp\",\"expires_at\":1422990000," + "\"is_valid\":true,\"scopes\":[\"public_profile\"],\"user_id\"" + ":\"800033850084728\"}}"); verifier.init(null, config); UserVerifierCallback callback = mock(UserVerifierCallback.class); verifier.checkAccessToken("invalidUserId", "falseUserAccessToken", callback); verify(callback, Mockito.timeout(1000).atLeastOnce()).onVerificationFailure(anyString()); } @Test public void badRequestTest() { verifier = new MyFacebookVerifier(400); verifier.init(null, config); UserVerifierCallback callback = mock(UserVerifierCallback.class); verifier.checkAccessToken("invalidUserId", "falseUserAccessToken", callback); // no exception is thrown, if onVerificationFailure(String) was called verify(callback, Mockito.timeout(1000).atLeastOnce()).onVerificationFailure(anyString()); } @Test public void successfulVerification() { String userId = "12456789123456"; verifier = new MyFacebookVerifier(200, "{\"data\":{\"app_id\":\"1557997434440423\"," + "\"application\":\"testApp\",\"expires_at\":1422990000," + "\"is_valid\":true,\"scopes\":[\"public_profile\"],\"user_id\"" + ":\"" + userId + "\"}}"); verifier.init(null, config); UserVerifierCallback callback = mock(UserVerifierCallback.class); verifier.checkAccessToken(userId, "someToken", callback); verify(callback, Mockito.timeout(1000).atLeastOnce()).onSuccess(); } private static class MyFacebookVerifier extends FacebookUserVerifier { int responseCode; String inputStreamString = ""; MyFacebookVerifier(int responseCode) { this.responseCode = responseCode; } MyFacebookVerifier(int responseCode, String intputStreamString) { this.responseCode = responseCode; this.inputStreamString = intputStreamString; } @Override protected HttpURLConnection establishConnection(String userAccessToken, String accessToken) { connection = mock(HttpURLConnection.class); try { when(connection.getResponseCode()).thenReturn(responseCode); when(connection.getInputStream()).thenReturn( new ByteArrayInputStream(inputStreamString.getBytes(StandardCharsets.UTF_8))); } catch (Exception e) { e.printStackTrace(); } return connection; } } }
package org.xwiki.container.servlet; import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.HttpServletResponse; import org.xwiki.container.RedirectResponse; import org.xwiki.container.Response; /** * This is the implementation of {@link Response} for {@link HttpServletResponse}. * * @since ??? * @since 10.0RC1 * @version $Id$ */ public class ServletResponse implements Response, RedirectResponse { private HttpServletResponse httpServletResponse; public ServletResponse(HttpServletResponse httpServletResponse) { this.httpServletResponse = httpServletResponse; } public HttpServletResponse getHttpServletResponse() { return this.httpServletResponse; } @Override public OutputStream getOutputStream() throws IOException { try { return this.httpServletResponse.getOutputStream(); } catch (IllegalStateException ex) { return null; } } @Override public void setContentLength(int length) { this.httpServletResponse.setContentLength(length); } @Override public void setContentType(String mimeType) { this.httpServletResponse.setContentType(mimeType); } @Override public void sendRedirect(String location) throws IOException { this.httpServletResponse.sendRedirect(location); } }
package eu.modelwriter.marker.ui.internal.views.visualizationview.commands; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import org.eclipse.core.resources.IMarker; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import edu.mit.csail.sdg.alloy4viz.AlloyAtom; import edu.mit.csail.sdg.alloy4viz.AlloyTuple; import eu.modelwriter.configuration.alloy.analysis.provider.AnalysisSourceProvider.ReasoningType; import eu.modelwriter.configuration.alloy.discovery.AlloyDiscovering; import eu.modelwriter.configuration.alloy.discovery.AlloyNextSolutionDiscovering; import eu.modelwriter.configuration.alloy.reasoning.AlloyNextSolutionReasoning; import eu.modelwriter.configuration.alloy.reasoning.AlloyReasoning; import eu.modelwriter.configuration.alloy.validation.AlloyValidator; import eu.modelwriter.configuration.internal.AlloyUtilities; import eu.modelwriter.marker.ui.Activator; import eu.modelwriter.marker.ui.internal.views.visualizationview.Visualization; import eu.modelwriter.marker.ui.internal.wizards.interpretationwizard.InterpretationWizard; public class VisualizationActionListenerFactory { private static VisualizationActionListenerFactory instance; private VisualizationActionListenerFactory() {} public VisualizationActionListenerFactory getInsance() { if (VisualizationActionListenerFactory.instance == null) { VisualizationActionListenerFactory.instance = new VisualizationActionListenerFactory(); } return VisualizationActionListenerFactory.instance; } public static ActionListener refreshActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { Visualization.showViz(); } }; } public static ActionListener addRemoveTypeActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { Display.getDefault().syncExec(new AddRemoveTypeCommand( Visualization.getMarker((AlloyAtom) Visualization.rightClickedAnnotation))); Visualization.showViz(); AlloyNextSolutionReasoning.getInstance().finishNext(); } }; } public static ActionListener createNewAtomActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { Display.getDefault().syncExec(new CreateNewAtomCommand()); Visualization.showViz(); AlloyNextSolutionReasoning.getInstance().finishNext(); } }; } public static ActionListener deleteAtomActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { Display.getDefault().syncExec(new DeleteAtomCommand( Visualization.getMarker((AlloyAtom) Visualization.rightClickedAnnotation))); Visualization.showViz(); AlloyNextSolutionReasoning.getInstance().finishNext(); } }; } public static ActionListener mappingActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { Display.getDefault().syncExec(new MappingCommand( Visualization.getMarker((AlloyAtom) Visualization.rightClickedAnnotation))); Visualization.showViz(); AlloyNextSolutionReasoning.getInstance().finishNext(); } }; } public static ActionListener removeRelationActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { Display.getDefault().syncExec(new RemoveRelationCommand( Visualization.getMarker(((AlloyTuple) Visualization.rightClickedAnnotation).getStart()), Visualization.getMarker(((AlloyTuple) Visualization.rightClickedAnnotation).getEnd()), Visualization.relation)); Visualization.showViz(); AlloyNextSolutionReasoning.getInstance().finishNext(); } }; } public static ActionListener resolveActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { Display.getDefault().syncExec(new ResolveCommand(Visualization.rightClickedAnnotation)); Visualization.showViz(); } }; } public static ActionListener validateActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (AlloyValidator.validate()) { JOptionPane.showMessageDialog(null, "Instance is consistent.", "Consistency Check", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Instance is inconsistent.", "Consistency Check", JOptionPane.WARNING_MESSAGE); } } }; } public static ActionListener discoverRelationActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { Activator.getDefault().getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { Visualization.sourceProvider.setActive(ReasoningType.DISCOVER_RELATION); } }); final AlloyReasoning alloyReasoning = new AlloyReasoning(); final boolean reasoning = alloyReasoning.reasoning(); if (!reasoning) { Visualization.sourceProvider.setPassive(); } Visualization.showViz(); } }; } public static ActionListener acceptReasonedRelationActionListener() { return new ActionListener() { IMarker selectedMarker; private void showWizard() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { final InterpretationWizard wizard = new InterpretationWizard(); final WizardDialog dialog = new WizardDialog( Activator.getDefault().getWorkbench().getWorkbenchWindows()[0].getShell(), wizard); dialog.open(); selectedMarker = wizard.getSelectedMarker(); } }); } private IMarker interpretAtom(final AlloyAtom atom) { this.showWizard(); if (this.selectedMarker == null) { return null; } final String sigTypeName = atom.getType().getName(); final String stringIndex = atom.toString().substring(sigTypeName.length()); int index = 0; if (!stringIndex.isEmpty()) { index = Integer.parseInt(stringIndex); } AlloyUtilities.bindAtomToMarker(sigTypeName, index, this.selectedMarker); Visualization.showViz(); return this.selectedMarker; } @Override public void actionPerformed(final ActionEvent e) { if (Visualization.container == null) { return; } final AlloyTuple tuple = (AlloyTuple) Visualization.rightClickedAnnotation; final AlloyAtom fromAtom = tuple.getStart(); final AlloyAtom toAtom = tuple.getEnd(); IMarker fromMarker = Visualization.getMarker(fromAtom); IMarker toMarker = Visualization.getMarker(toAtom); if (fromMarker == null) { fromMarker = this.interpretAtom(fromAtom); } else if (toMarker == null) { toMarker = this.interpretAtom(toAtom); } AlloyUtilities.resetReasoned(fromMarker, toMarker, Visualization.relation); Visualization.showViz(); } }; } public static ActionListener discoverAtomActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { Activator.getDefault().getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { Visualization.sourceProvider.setActive(ReasoningType.DISCOVER_ATOM); } }); final AlloyDiscovering alloyDiscovering = new AlloyDiscovering(); final boolean discovering = alloyDiscovering.discovering(); if (!discovering) { Visualization.sourceProvider.setPassive(); } Visualization.showViz(); } }; } public static ActionListener nextSolutionActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (Visualization.sourceProvider.getReasoningType() == ReasoningType.DISCOVER_RELATION) { final boolean next = AlloyNextSolutionReasoning.getInstance().next(); if (!next) { Visualization.sourceProvider.setPassive(); } } else if (Visualization.sourceProvider.getReasoningType() == ReasoningType.DISCOVER_ATOM) { final boolean next = AlloyNextSolutionDiscovering.getInstance().next(); if (!next) { Visualization.sourceProvider.setPassive(); } } Visualization.showViz(); } }; } public static ActionListener stopAnalysisActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { Activator.getDefault().getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { Visualization.sourceProvider.setPassive(); } }); AlloyNextSolutionReasoning.getInstance().finishNext(); Visualization.showViz(); } }; } public static ActionListener clearAllReasonedActionListener() { return new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { AlloyUtilities.clearAllReasonedTuplesAndAtoms(); Visualization.showViz(); AlloyNextSolutionReasoning.getInstance().finishNext(); Activator.getDefault().getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { Visualization.sourceProvider.setPassive(); } }); } }; } public static ActionListener interpretAtomMenuItemActionListener() { return new ActionListener() { IMarker selectedMarker; @Override public void actionPerformed(final ActionEvent e) { final AlloyAtom alloyAtom = (AlloyAtom) Visualization.rightClickedAnnotation; this.showWizard(); if (this.selectedMarker == null) { return; } final String sigTypeName = alloyAtom.getType().getName(); final String stringIndex = alloyAtom.toString().substring(sigTypeName.length()); int index = 0; if (!stringIndex.isEmpty()) { index = Integer.parseInt(stringIndex); } AlloyUtilities.bindAtomToMarker(sigTypeName, index, this.selectedMarker); Visualization.showViz(); } private void showWizard() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { final InterpretationWizard wizard = new InterpretationWizard(); final WizardDialog dialog = new WizardDialog( Activator.getDefault().getWorkbench().getWorkbenchWindows()[0].getShell(), wizard); dialog.open(); selectedMarker = wizard.getSelectedMarker(); } }); } }; } }
package org.eclipse.birt.report.designer.internal.ui.ide.propertyeditor; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.AlterPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.BookMarkExpressionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.BordersPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.CellPaddingPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.CellPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.CommentsPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.DataPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.DataSetPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.DataSourcePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.DescriptionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ExpressionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.FontPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.FormatDateTimeAttributePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.FormatNumberAttributePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.FormatStringAttributePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.GridPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.HyperLinkPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ImagePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ItemMarginPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.LabelI18nPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.LabelPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.LibraryPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ListPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ListingSectionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.NamedExpressionsPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ReferencePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.ReportPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.RowPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.SectionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.TOCExpressionPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.TablePage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.TextI18nPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.TextPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.UserPropertiesPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.VisibilityPage; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.CategoryProvider; import org.eclipse.birt.report.designer.ui.views.attributes.providers.CategoryProviderFactory; import org.eclipse.birt.report.designer.ui.views.attributes.providers.ICategoryProvider; import org.eclipse.birt.report.designer.ui.views.attributes.providers.ICategoryProviderFactory; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DataSourceHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; public class IDECategoryProviderFactory extends CategoryProviderFactory { private static ICategoryProviderFactory instance = new IDECategoryProviderFactory( ); protected IDECategoryProviderFactory( ) { } public static ICategoryProviderFactory getInstance( ) { return instance; } public ICategoryProvider getCategoryProvider( String elementName ) { if ( ReportDesignConstants.CELL_ELEMENT.equals( elementName ) ) { return new CategoryProvider( new String[]{ "CellPageGenerator.List.General", //$NON-NLS-1$ "CellPageGenerator.List.CellPadding", //$NON-NLS-1$ "CellPageGenerator.List.Font", //$NON-NLS-1$ "CellPageGenerator.List.Borders", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ CellPage.class, CellPaddingPage.class, FontPage.class, BordersPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class } ); } if ( ReportDesignConstants.DATA_ITEM.equals( elementName ) ) { return new CategoryProvider( new String[]{ "DataPageGenerator.List.General", //$NON-NLS-1$ "DataPageGenerator.List.Expression", //$NON-NLS-1$ "DataPageGenerator.List.Padding", //$NON-NLS-1$ "DataPageGenerator.List.Borders", //$NON-NLS-1$ "DataPageGenerator.List.Margin", //$NON-NLS-1$ "DataPageGenerator.List.formatNumber", //$NON-NLS-1$ "DataPageGenerator.List.formatDateTime", //$NON-NLS-1$ "DataPageGenerator.List.formatString", //$NON-NLS-1$ "DataPageGenerator.List.HyperLink", //$NON-NLS-1$ "DataPageGenerator.List.Section", //$NON-NLS-1$ "DataPageGenerator.List.Visibility",//$NON-NLS-1$ "DataPageGenerator.List.TOC",//$NON-NLS-1$ "DataPageGenerator.List.Bookmark", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler" //$NON-NLS-1$ }, new Class[]{ DataPage.class, ExpressionPage.class, CellPaddingPage.class, BordersPage.class, ItemMarginPage.class, FormatNumberAttributePage.class, FormatDateTimeAttributePage.class, FormatStringAttributePage.class, HyperLinkPage.class, SectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class } ); } if ( ReportDesignConstants.GRID_ITEM.equals( elementName ) ) { return new CategoryProvider( new String[]{ "GridPageGenerator.List.General", //$NON-NLS-1$ "GridPageGenerator.List.Margin", //$NON-NLS-1$ "GridPageGenerator.List.Font", //$NON-NLS-1$ "GridPageGenerator.List.Borders", //$NON-NLS-1$ "GridPageGenerator.List.Section", //$NON-NLS-1$ "GridPageGenerator.List.Visibility", //$NON-NLS-1$ "GridPageGenerator.List.TOC", //$NON-NLS-1$ "GridPageGenerator.List.Bookmark", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ GridPage.class, ItemMarginPage.class, FontPage.class, BordersPage.class, SectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class } ); } if ( ReportDesignConstants.IMAGE_ITEM.equals( elementName ) ) { return new CategoryProvider( new String[]{ "ImagePageGenerator.List.General", //$NON-NLS-1$ "ImagePageGenerator.List.Reference", //$NON-NLS-1$ "ImagePageGenerator.List.HyperLink", //$NON-NLS-1$ "ImagePageGenerator.List.AltText", //$NON-NLS-1$ "ImagePageGenerator.List.Borders", //$NON-NLS-1$ "ImagePageGenerator.List.Section", //$NON-NLS-1$ "ImagePageGenerator.List.Visibility", //$NON-NLS-1$ "ImagePageGenerator.List.TOC", //$NON-NLS-1$ "ImagePageGenerator.List.Bookmark", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ ImagePage.class, ReferencePage.class, HyperLinkPage.class, AlterPage.class, BordersPage.class, SectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class } ); } if ( ReportDesignConstants.LABEL_ITEM.equals( elementName ) ) { return new CategoryProvider( new String[]{ "LabelPageGenerator.List.General", //$NON-NLS-1$ "LabelPageGenerator.List.Padding", //$NON-NLS-1$ "LabelPageGenerator.List.Borders", //$NON-NLS-1$ "LabelPageGenerator.List.Margin", //$NON-NLS-1$ "LabelPageGenerator.List.HyperLink", //$NON-NLS-1$ "LabelPageGenerator.List.Section", //$NON-NLS-1$ "LabelPageGenerator.List.Visibility", //$NON-NLS-1$ "LabelPageGenerator.List.I18n", //$NON-NLS-1$ "LabelPageGenerator.List.TOC", //$NON-NLS-1$ "LabelPageGenerator.List.Bookmark", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ LabelPage.class, CellPaddingPage.class, BordersPage.class, ItemMarginPage.class, HyperLinkPage.class, SectionPage.class, VisibilityPage.class, LabelI18nPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class } ); } if ( ReportDesignConstants.LIBRARY_ELEMENT.equals( elementName ) ) { return new CategoryProvider( new String[]{ "ReportPageGenerator.List.General", //$NON-NLS-1$ "ReportPageGenerator.List.Description", //$NON-NLS-1$ "ReportPageGenerator.List.Comments", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ LibraryPage.class, DescriptionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class, } ); } if ( ReportDesignConstants.LIST_ITEM.equals( elementName ) ) { return new CategoryProvider( new String[]{ "ListPageGenerator.List.General", //$NON-NLS-1$ "ListPageGenerator.List.Font", //$NON-NLS-1$ "ListPageGenerator.List.Borders", //$NON-NLS-1$ "ListPageGenerator.List.Section", //$NON-NLS-1$ "ListPageGenerator.List.Visibility", //$NON-NLS-1$ "ListPageGenerator.List.TOC", //$NON-NLS-1$ "ListPageGenerator.List.Bookmark", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ ListPage.class, FontPage.class, BordersPage.class, ListingSectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class } ); } if ( ReportDesignConstants.REPORT_DESIGN_ELEMENT.equals( elementName ) ) { return new CategoryProvider( new String[]{ "ReportPageGenerator.List.General", //$NON-NLS-1$ "ReportPageGenerator.List.Description", //$NON-NLS-1$ "ReportPageGenerator.List.Comments", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ ReportPage.class, DescriptionPage.class, CommentsPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class, } ); } if ( ReportDesignConstants.ROW_ELEMENT.equals( elementName ) ) { return new CategoryProvider( new String[]{ "RowPageGenerator.List.General", //$NON-NLS-1$ // "RowPageGenerator.List.CellPadding" //$NON-NLS-1$ "RowPageGenerator.List.Font", //$NON-NLS-1$ // "RowPageGenerator.List.Borders", //$NON-NLS-1$ "RowPageGenerator.List.Bookmark", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ RowPage.class, // CellPaddingPage.class, FontPage.class, // BordersPage.class, BookMarkExpressionPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class } ); } if ( ReportDesignConstants.TABLE_ITEM.equals( elementName ) ) { return new CategoryProvider( new String[]{ "TablePageGenerator.List.General", //$NON-NLS-1$ "TablePageGenerator.List.Marign", //$NON-NLS-1$ "TablePageGenerator.List.Font", //$NON-NLS-1$ "TablePageGenerator.List.Borders", //$NON-NLS-1$ "TablePageGenerator.List.Section", //$NON-NLS-1$ "TablePageGenerator.List.Visibility", //$NON-NLS-1$ "TablePageGenerator.List.TOC", //$NON-NLS-1$ "TablePageGenerator.List.Bookmark",//$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ TablePage.class, ItemMarginPage.class, FontPage.class, BordersPage.class, ListingSectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class } ); } if ( ReportDesignConstants.TEXT_DATA_ITEM.equals( elementName ) ) { return new CategoryProvider( new String[]{ "TextPageGenerator.List.General", //$NON-NLS-1$ "DataPageGenerator.List.Expression", //$NON-NLS-1$ "TextPageGenerator.List.Padding", //$NON-NLS-1$ "TextPageGenerator.List.Borders", //$NON-NLS-1$ "TextPageGenerator.List.Margin", //$NON-NLS-1$ "TextPageGenerator.List.Section", //$NON-NLS-1$ "TextPageGenerator.List.Visibility", //$NON-NLS-1$ "TextPageGenerator.List.TOC", //$NON-NLS-1$ "TextPageGenerator.List.Bookmark", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ TextPage.class, ExpressionPage.class, CellPaddingPage.class, BordersPage.class, ItemMarginPage.class, SectionPage.class, VisibilityPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class } ); } if ( ReportDesignConstants.TEXT_ITEM.equals( elementName ) ) { return new CategoryProvider( new String[]{ "TextPageGenerator.List.General", //$NON-NLS-1$ "TextPageGenerator.List.Padding", //$NON-NLS-1$ "TextPageGenerator.List.Borders", //$NON-NLS-1$ "TextPageGenerator.List.Margin", //$NON-NLS-1$ "TextPageGenerator.List.Section", //$NON-NLS-1$ "TextPageGenerator.List.Visibility", //$NON-NLS-1$ "TextPageGenerator.List.I18n", //$NON-NLS-1$ "TextPageGenerator.List.TOC", //$NON-NLS-1$ "TextPageGenerator.List.Bookmark", //$NON-NLS-1$ "ReportPageGenerator.List.UserProperties", //$NON-NLS-1$ "ReportPageGenerator.List.NamedExpressions", //$NON-NLS-1$ "ReportPageGenerator.List.EventHandler", //$NON-NLS-1$ }, new Class[]{ TextPage.class, CellPaddingPage.class, BordersPage.class, ItemMarginPage.class, SectionPage.class, VisibilityPage.class, TextI18nPage.class, TOCExpressionPage.class, BookMarkExpressionPage.class, UserPropertiesPage.class, NamedExpressionsPage.class, HandlerPage.class } ); } return super.getCategoryProvider( elementName ); } public ICategoryProvider getCategoryProvider( DesignElementHandle handle ) { if ( handle instanceof DataSourceHandle ) { return new CategoryProvider( new String[]{ "DataSourcePageGenerator.List.General", "ReportPageGenerator.List.EventHandler"},//$NON-NLS-1$ new Class[]{ DataSourcePage.class, HandlerPage.class } ); } if ( handle instanceof DataSetHandle ) { return new CategoryProvider( new String[]{ "DataSetPageGenerator.List.General", "ReportPageGenerator.List.EventHandler"}, //$NON-NLS-1$ new Class[]{ DataSetPage.class, HandlerPage.class } ); } return super.getCategoryProvider( handle ); } }
package org.eclipse.birt.report.designer.internal.ui.views.attributes.page; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.ColorPropertyDescriptorProvider; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.ComboPropertyDescriptorProvider; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.TextPropertyDescriptorProvider; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.UnitPropertyDescriptorProvider; import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.ColorSection; import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.ComboSection; import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.SeperatorSection; import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.TextSection; import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.UnitSection; import org.eclipse.birt.report.model.api.MasterPageHandle; import org.eclipse.birt.report.model.api.SimpleMasterPageHandle; import org.eclipse.birt.report.model.api.StyleHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; /** * The general attribute page of MasterPage element. */ public class MasterPageGeneralPage extends AttributePage { private UnitSection heightSection; private ComboPropertyDescriptorProvider typeProvider; private UnitSection widthSection; public void buildUI( Composite parent ) { super.buildUI( parent ); container.setLayout( WidgetUtil.createGridLayout( 6, 15 ) ); TextPropertyDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( MasterPageHandle.NAME_PROP, ReportDesignConstants.MASTER_PAGE_ELEMENT ); TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setWidth( 200 ); nameSection.setGridPlaceholder( 4, true ); addSection( PageSectionId.MASTER_PAGE_NAME, nameSection ); SeperatorSection seperatorSection = new SeperatorSection( container, SWT.HORIZONTAL ); addSection( PageSectionId.MASTER_PAGE_SEPERATOR, seperatorSection ); UnitPropertyDescriptorProvider headHeightProvider = new UnitPropertyDescriptorProvider( SimpleMasterPageHandle.HEADER_HEIGHT_PROP, ReportDesignConstants.SIMPLE_MASTER_PAGE_ELEMENT ); UnitSection headHeightSection = new UnitSection( headHeightProvider.getDisplayName( ), container, true ); headHeightSection.setProvider( headHeightProvider ); headHeightSection.setWidth( 200 ); headHeightSection.setLayoutNum( 2 ); addSection( PageSectionId.MASTER_PAGE_HEAD_HEIGHT, headHeightSection ); ColorPropertyDescriptorProvider colorProvider = new ColorPropertyDescriptorProvider( StyleHandle.BACKGROUND_COLOR_PROP, ReportDesignConstants.STYLE_ELEMENT ); ColorSection colorSection = new ColorSection( colorProvider.getDisplayName( ), container, true ); colorSection.setProvider( colorProvider ); colorSection.setWidth( 200 ); colorSection.setLayoutNum( 4 ); colorSection.setGridPlaceholder( 2, true ); addSection( PageSectionId.MASTER_PAGE_COLOR, colorSection ); UnitPropertyDescriptorProvider footHeightProvider = new UnitPropertyDescriptorProvider( SimpleMasterPageHandle.FOOTER_HEIGHT_PROP, ReportDesignConstants.SIMPLE_MASTER_PAGE_ELEMENT ); UnitSection footHeightSection = new UnitSection( footHeightProvider.getDisplayName( ), container, true ); footHeightSection.setProvider( footHeightProvider ); footHeightSection.setWidth( 200 ); footHeightSection.setLayoutNum( 2 ); addSection( PageSectionId.MASTER_PAGE_FOOT_HEIGHT, footHeightSection ); ComboPropertyDescriptorProvider orientationProvider = new ComboPropertyDescriptorProvider( MasterPageHandle.ORIENTATION_PROP, ReportDesignConstants.MASTER_PAGE_ELEMENT ); ComboSection orientationSection = new ComboSection( orientationProvider.getDisplayName( ), container, true ); orientationSection.setProvider( orientationProvider ); orientationSection.setLayoutNum( 4 ); orientationSection.setGridPlaceholder( 2, true ); orientationSection.setWidth( 200 ); addSection( PageSectionId.MASTER_PAGE_ORIENTATION, orientationSection ); SeperatorSection seperatorSection1 = new SeperatorSection( container, SWT.HORIZONTAL ); addSection( PageSectionId.MASTER_PAGE_SEPERATOR_1, seperatorSection1 ); UnitPropertyDescriptorProvider widthProvider = new UnitPropertyDescriptorProvider( MasterPageHandle.WIDTH_PROP, ReportDesignConstants.MASTER_PAGE_ELEMENT ); widthSection = new UnitSection( widthProvider.getDisplayName( ), container, true ); widthSection.setProvider( widthProvider ); widthSection.setWidth( 200 ); widthSection.setLayoutNum( 2 ); addSection( PageSectionId.MASTER_PAGE_WIDTH, widthSection ); typeProvider = new ComboPropertyDescriptorProvider( MasterPageHandle.TYPE_PROP, ReportDesignConstants.MASTER_PAGE_ELEMENT ); ComboSection typeSection = new ComboSection( typeProvider.getDisplayName( ), container, true ); typeSection.setProvider( typeProvider ); typeSection.setGridPlaceholder( 2, true ); typeSection.setLayoutNum( 4 ); typeSection.setWidth( 200 ); addSection( PageSectionId.MASTER_PAGE_TYPE, typeSection ); UnitPropertyDescriptorProvider heightProvider = new UnitPropertyDescriptorProvider( MasterPageHandle.HEIGHT_PROP, ReportDesignConstants.MASTER_PAGE_ELEMENT ); heightSection = new UnitSection( heightProvider.getDisplayName( ), container, true ); heightSection.setProvider( heightProvider ); heightSection.setWidth( 200 ); heightSection.setGridPlaceholder( 4, true ); addSection( PageSectionId.MASTER_PAGE_HEIGHT, heightSection ); // WidgetUtil.buildGridControl( container, propertiesMap, // ReportDesignConstants.MASTER_PAGE_ELEMENT, // MasterPageHandle.NAME_PROP, 1, false ); // WidgetUtil.buildGridControl( container, propertiesMap, // ReportDesignConstants.STYLE_ELEMENT, // StyleHandle.BACKGROUND_COLOR_PROP, 1, false ); // WidgetUtil.createGridPlaceholder( container, 1, true ); /* * WidgetUtil.buildGridControl( container, propertiesMap, * ReportDesignConstants.MASTER_PAGE_ELEMENT, * MasterPageHandle.ORIENTATION_PROP, 1, false ); * * Label separator = new Label( container, SWT.SEPARATOR | * SWT.HORIZONTAL ); GridData data = new GridData( ); * data.horizontalSpan = 5; data.grabExcessHorizontalSpace = false; * data.horizontalAlignment = GridData.FILL; separator.setLayoutData( * data ); * * WidgetUtil.buildGridControl( container, propertiesMap, * ReportDesignConstants.MASTER_PAGE_ELEMENT, * MasterPageHandle.TYPE_PROP, 1, false ); pageSizeDescriptor = * (IPropertyDescriptor) propertiesMap.get( MasterPageHandle.TYPE_PROP ); * * WidgetUtil.createGridPlaceholder( container, 3, false ); * * widthPane = (Composite) WidgetUtil.buildGridControl( container, * propertiesMap, ReportDesignConstants.MASTER_PAGE_ELEMENT, * MasterPageHandle.WIDTH_PROP, 1, false ); * * heightPane = (Composite) WidgetUtil.buildGridControl( container, * propertiesMap, ReportDesignConstants.MASTER_PAGE_ELEMENT, * MasterPageHandle.HEIGHT_PROP, 1, false ); */ createSections( ); layoutSections( ); } public void refresh( ) { super.refresh( ); resetCustomStyle( ); } private void resetCustomStyle( ) { if ( typeProvider.load( ) .equals( DesignChoiceConstants.PAGE_SIZE_CUSTOM ) ) { widthSection.getUnitComboControl( ).setReadOnly( false ); heightSection.getUnitComboControl( ).setReadOnly( false ); } else { widthSection.getUnitComboControl( ).setReadOnly( true ); heightSection.getUnitComboControl( ).setReadOnly( true ); } } public void postElementEvent( ) { super.postElementEvent( ); resetCustomStyle( ); } }
package edu.ucdenver.ccp.nlp.wrapper.conceptmapper.typesystem; import java.util.ArrayList; import java.util.List; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.FSIterator; import org.apache.uima.conceptMapper.support.tokenizer.TokenAnnotation; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.metadata.TypeSystemDescription; import org.uimafit.component.JCasAnnotator_ImplBase; import org.uimafit.factory.AnalysisEngineFactory; import edu.ucdenver.ccp.nlp.core.uima.annotation.CCPTextAnnotation; import edu.ucdenver.ccp.nlp.wrapper.conceptmapper.OntologyTerm; /** * Converts ConceptMapper OntologyTerm annotations to a corresponding CCPTextAnnotation object. * * @author Bill Baumgartner * */ public class ConceptMapper2CCPTypeSystemConverter_AE extends JCasAnnotator_ImplBase { /** * Cycle through all OntologyTerms and TokenAnnotations and converts to CCPTextAnnotations. * OntologyTerm and TokenAnnotation annotations are removed from the CAS once converted. */ @Override public void process(JCas jcas) throws AnalysisEngineProcessException { /* Convert OntologyTerm annotations */ List<CCPTextAnnotation> annotations2add = new ArrayList<CCPTextAnnotation>(); List<Annotation> annotations2remove = new ArrayList<Annotation>(); for (FSIterator<Annotation> annotIter = jcas.getJFSIndexRepository().getAnnotationIndex(OntologyTerm.type) .iterator(); annotIter.hasNext();) { OntologyTerm ot = (OntologyTerm) annotIter.next(); CCPTextAnnotation ccpTA = CCPConceptMapperTypeSystemConverter_Util.convertOntologyTerm(ot, jcas); if (ccpTA != null) { annotations2add.add(ccpTA); annotations2remove.add(ot); } } /* Now convert token annotations */ for (FSIterator<Annotation> annotIter = jcas.getJFSIndexRepository().getAnnotationIndex(TokenAnnotation.type) .iterator(); annotIter.hasNext();) { int tokenNumber = 0; TokenAnnotation token = (TokenAnnotation) annotIter.next(); CCPTextAnnotation ccpToken = CCPConceptMapperTypeSystemConverter_Util .convertToken(token, jcas, tokenNumber); tokenNumber++; if (ccpToken != null) { annotations2add.add(ccpToken); annotations2remove.add(token); } } for (CCPTextAnnotation ccpTA : annotations2add) { ccpTA.addToIndexes(); } for (Annotation annot : annotations2remove) { annot.removeFromIndexes(); } } public static AnalysisEngineDescription createAnalysisEngineDescription(TypeSystemDescription tsd) throws ResourceInitializationException { return AnalysisEngineFactory.createPrimitiveDescription(ConceptMapper2CCPTypeSystemConverter_AE.class, tsd); } }
package com.nispok.snackbar; import android.app.Activity; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.support.annotation.ColorRes; import android.support.annotation.StringRes; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.TextView; import com.nispok.snackbar.enums.SnackbarType; import com.nispok.snackbar.layouts.SnackbarLayout; import com.nispok.snackbar.listeners.ActionClickListener; import com.nispok.snackbar.listeners.EventListener; import com.nispok.snackbar.listeners.SwipeDismissTouchListener; /** * View that provides quick feedback about an operation in a small popup at the base of the screen */ public class Snackbar extends SnackbarLayout { public enum SnackbarDuration { LENGTH_SHORT(2000), LENGTH_LONG(3500); private long duration; SnackbarDuration(long duration) { this.duration = duration; } public long getDuration() { return duration; } } private SnackbarType mType = SnackbarType.SINGLE_LINE; private SnackbarDuration mDuration = SnackbarDuration.LENGTH_LONG; private CharSequence mText; private int mColor = -1; private int mTextColor = -1; private int mOffset; private long mSnackbarStart; private long mSnackbarFinish; private long mTimeRemaining = -1; private CharSequence mActionLabel; private int mActionColor = -1; private boolean mAnimated = true; private long mCustomDuration = -1; private ActionClickListener mActionClickListener; private boolean mShouldDismissOnActionClicked = true; private EventListener mEventListener; private boolean mIsShowing = false; private boolean mCanSwipeToDismiss = true; private boolean mIsDismissing = false; private Runnable mDismissRunnable = new Runnable() { @Override public void run() { dismiss(); } }; private Snackbar(Context context) { super(context); } public static Snackbar with(Context context) { return new Snackbar(context); } /** * Sets the type of {@link Snackbar} to be displayed. * * @param type the {@link SnackbarType} of this instance * @return */ public Snackbar type(SnackbarType type) { mType = type; return this; } /** * Sets the text to be displayed in this {@link Snackbar} * * @param text * @return */ public Snackbar text(CharSequence text) { mText = text; return this; } /** * Sets the text to be displayed in this {@link Snackbar} * * @param resId * @return */ public Snackbar text(@StringRes int resId) { return text(getContext().getText(resId)); } /** * Sets the background color of this {@link Snackbar} * * @param color * @return */ public Snackbar color(int color) { mColor = color; return this; } /** * Sets the background color of this {@link Snackbar} * * @param resId * @return */ public Snackbar colorResource(@ColorRes int resId) { return color(getResources().getColor(resId)); } /** * Sets the text color of this {@link Snackbar} * * @param textColor * @return */ public Snackbar textColor(int textColor) { mTextColor = textColor; return this; } /** * Sets the text color of this {@link Snackbar} * * @param resId * @return */ public Snackbar textColorResource(@ColorRes int resId) { return textColor(getResources().getColor(resId)); } /** * Sets the action label to be displayed, if any. Note that if this is not set, the action * button will not be displayed * * @param actionButtonLabel * @return */ public Snackbar actionLabel(CharSequence actionButtonLabel) { mActionLabel = actionButtonLabel; return this; } /** * Sets the action label to be displayed, if any. Note that if this is not set, the action * button will not be displayed * * @param resId * @return */ public Snackbar actionLabel(@StringRes int resId) { return actionLabel(getContext().getString(resId)); } /** * Sets the color of the action button label. Note that you must set a button label with * {@link Snackbar#actionLabel(CharSequence)} for this button to be displayed * * @param actionColor * @return */ public Snackbar actionColor(int actionColor) { mActionColor = actionColor; return this; } /** * Sets the color of the action button label. Note that you must set a button label with * {@link Snackbar#actionLabel(CharSequence)} for this button to be displayed * * @param resId * @return */ public Snackbar actionColorResource(@ColorRes int resId) { return actionColor(getResources().getColor(resId)); } /** * Determines whether this {@link Snackbar} should dismiss when the action button is touched * * @param shouldDismiss * @return */ public Snackbar dismissOnActionClicked(boolean shouldDismiss) { mShouldDismissOnActionClicked = shouldDismiss; return this; } /** * Sets the listener to be called when the {@link Snackbar} action is * selected. Note that you must set a button label with * {@link Snackbar#actionLabel(CharSequence)} for this button to be displayed * * @param listener * @return */ public Snackbar actionListener(ActionClickListener listener) { mActionClickListener = listener; return this; } /** * Sets the listener to be called when the {@link Snackbar} is dismissed. * * @param listener * @return */ public Snackbar eventListener(EventListener listener) { mEventListener = listener; return this; } /** * Sets on/off animation for this {@link Snackbar} * * @param withAnimation * @return */ public Snackbar animation(boolean withAnimation) { mAnimated = withAnimation; return this; } /** * Determines whether this {@link com.nispok.snackbar.Snackbar} can be swiped off from the screen * * @param canSwipeToDismiss * @return */ public Snackbar swipeToDismiss(boolean canSwipeToDismiss) { mCanSwipeToDismiss = canSwipeToDismiss; return this; } /** * Sets the duration of this {@link Snackbar}. See * {@link Snackbar.SnackbarDuration} for available options * * @param duration * @return */ public Snackbar duration(SnackbarDuration duration) { mDuration = duration; return this; } /** * Sets a custom duration of this {@link Snackbar} * * @param duration * @return */ public Snackbar duration(long duration) { mCustomDuration = duration; return this; } /** * Attaches this {@link Snackbar} to an AbsListView (ListView, GridView, ExpandableListView) so * it dismisses when the list is scrolled * * @param absListView * @return */ public Snackbar attachToAbsListView(AbsListView absListView) { absListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { dismiss(); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); return this; } /** * Attaches this {@link Snackbar} to a RecyclerView so it dismisses when the list is scrolled * * @param recyclerView * @return */ public Snackbar attachToRecyclerView(RecyclerView recyclerView) { recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); dismiss(); } }); return this; } private FrameLayout.LayoutParams init(Activity parent) { SnackbarLayout layout = (SnackbarLayout) LayoutInflater.from(parent) .inflate(R.layout.sb__template, this, true); mColor = mColor != -1 ? mColor : getResources().getColor(R.color.sb__background); float scale = getResources().getDisplayMetrics().density; int offset = getResources().getDimensionPixelOffset(R.dimen.sb__offset); mOffset = (int) (offset / scale); FrameLayout.LayoutParams params; if (getResources().getBoolean(R.bool.is_phone)) { // Phone layout.setMinimumHeight(dpToPx(mType.getMinHeight(), scale)); layout.setMaxHeight(dpToPx(mType.getMaxHeight(), scale)); layout.setBackgroundColor(mColor); params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); } else { // Tablet/desktop mType = SnackbarType.SINGLE_LINE; // Force single-line layout.setMinimumWidth(getResources().getDimensionPixelSize(R.dimen.sb__min_width)); layout.setMaxWidth(getResources().getDimensionPixelSize(R.dimen.sb__max_width)); layout.setBackgroundResource(R.drawable.sb__bg); GradientDrawable bg = (GradientDrawable) layout.getBackground(); bg.setColor(mColor); params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, dpToPx(mType.getMaxHeight(), scale)); params.leftMargin = offset; params.bottomMargin = offset; } params.gravity = Gravity.BOTTOM; TextView snackbarText = (TextView) layout.findViewById(R.id.sb__text); snackbarText.setText(mText); if (mTextColor != -1) { snackbarText.setTextColor(mTextColor); } snackbarText.setMaxLines(mType.getMaxLines()); TextView snackbarAction = (TextView) layout.findViewById(R.id.sb__action); if (!TextUtils.isEmpty(mActionLabel)) { requestLayout(); snackbarAction.setText(mActionLabel); if (mActionColor != -1) { snackbarAction.setTextColor(mActionColor); } snackbarAction.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (mActionClickListener != null) { mActionClickListener.onActionClicked(); } if (mShouldDismissOnActionClicked) { dismiss(); } } }); snackbarAction.setMaxLines(mType.getMaxLines()); } else { snackbarAction.setVisibility(GONE); } setClickable(true); if (mCanSwipeToDismiss && getResources().getBoolean(R.bool.is_swipeable)) { setOnTouchListener(new SwipeDismissTouchListener(this, null, new SwipeDismissTouchListener.DismissCallbacks() { @Override public boolean canDismiss(Object token) { return true; } @Override public void onDismiss(View view, Object token) { if (view != null) { finish(); } } @Override public void pauseTimer(boolean shouldPause) { if (shouldPause) { removeCallbacks(mDismissRunnable); mSnackbarFinish = System.currentTimeMillis(); } else { mTimeRemaining -= (mSnackbarFinish - mSnackbarStart); startTimer(mTimeRemaining); } } })); } return params; } private static int dpToPx(int dp, float scale) { return (int) (dp * scale + 0.5f); } /** * Displays the {@link Snackbar} at the bottom of the * {@link android.app.Activity} provided. * * @param targetActivity */ public void show(Activity targetActivity) { FrameLayout.LayoutParams params = init(targetActivity); ViewGroup root = (ViewGroup) targetActivity.findViewById(android.R.id.content); root.addView(this, params); bringToFront(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { root.requestLayout(); root.invalidate(); } mIsShowing = true; if (mEventListener != null) { mEventListener.onShow(mType.getMaxHeight() + mOffset); } if (!mAnimated) { startTimer(); return; } Animation slideIn = AnimationUtils.loadAnimation(getContext(), R.anim.snackbar_in); slideIn.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { post(new Runnable() { @Override public void run() { mSnackbarStart = System.currentTimeMillis(); if (mTimeRemaining == -1) { mTimeRemaining = getDuration(); } startTimer(); } }); } @Override public void onAnimationRepeat(Animation animation) { } }); startAnimation(slideIn); } private void startTimer() { postDelayed(mDismissRunnable, getDuration()); } private void startTimer(long duration) { postDelayed(mDismissRunnable, duration); } public void dismiss() { if (!mAnimated) { finish(); return; } if (mIsDismissing) { return; } final Animation slideOut = AnimationUtils.loadAnimation(getContext(), R.anim.snackbar_out); slideOut.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { mIsDismissing = true; } @Override public void onAnimationEnd(Animation animation) { post(new Runnable() { @Override public void run() { finish(); } }); } @Override public void onAnimationRepeat(Animation animation) { } }); startAnimation(slideOut); } private void finish() { clearAnimation(); ViewGroup parent = (ViewGroup) getParent(); if (parent != null) { parent.removeView(this); } if (mEventListener != null && mIsShowing) { mEventListener.onDismiss(mType.getMaxHeight() + mOffset); } mIsShowing = false; } public int getActionColor() { return mActionColor; } public CharSequence getActionLabel() { return mActionLabel; } public int getTextColor() { return mTextColor; } public int getColor() { return mColor; } public CharSequence getText() { return mText; } public long getDuration() { return mCustomDuration == -1 ? mDuration.getDuration() : mCustomDuration; } public SnackbarType getType() { return mType; } public boolean isAnimated() { return mAnimated; } public boolean shouldDismissOnActionClicked() { return mShouldDismissOnActionClicked; } /** * Returns whether this {@link com.nispok.snackbar.Snackbar} is currently showing * * @return */ public boolean isShowing() { return mIsShowing; } /** * Returns whether this {@link com.nispok.snackbar.Snackbar} has been dismissed * * @return */ public boolean isDismissed() { return !mIsShowing; } }
package com.nispok.snackbar; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.support.annotation.AnimRes; import android.support.annotation.ColorRes; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import android.support.v4.view.accessibility.AccessibilityEventCompat; import android.text.TextUtils; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.nispok.snackbar.enums.SnackbarType; import com.nispok.snackbar.layouts.SnackbarLayout; import com.nispok.snackbar.listeners.ActionClickListener; import com.nispok.snackbar.listeners.ActionSwipeListener; import com.nispok.snackbar.listeners.EventListener; import com.nispok.snackbar.listeners.SwipeDismissTouchListener; /** * View that provides quick feedback about an operation in a small popup at the base of the screen */ public class Snackbar extends SnackbarLayout { public enum SnackbarDuration { LENGTH_SHORT(2000), LENGTH_LONG(3500), LENGTH_INDEFINITE(-1); private long duration; SnackbarDuration(long duration) { this.duration = duration; } public long getDuration() { return duration; } } public static enum SnackbarPosition { TOP(Gravity.TOP), BOTTOM(Gravity.BOTTOM), BOTTOM_CENTER(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); private int layoutGravity; SnackbarPosition(int layoutGravity) { this.layoutGravity = layoutGravity; } public int getLayoutGravity() { return layoutGravity; } } private int mUndefinedColor = -10000; private int mUndefinedDrawable = -10000; private SnackbarType mType = SnackbarType.SINGLE_LINE; private SnackbarDuration mDuration = SnackbarDuration.LENGTH_LONG; private CharSequence mText; private TextView snackbarText; private int mColor = mUndefinedColor; private int mTextColor = mUndefinedColor; private int mOffset; private Integer mLineColor; private SnackbarPosition mPhonePosition = SnackbarPosition.BOTTOM; private SnackbarPosition mWidePosition = SnackbarPosition.BOTTOM_CENTER; private int mDrawable = mUndefinedDrawable; private int mMarginTop = 0; private int mMarginBottom = 0; private int mMarginLeft = 0; private int mMarginRight = 0; private long mSnackbarStart; private long mSnackbarFinish; private long mTimeRemaining = -1; private CharSequence mActionLabel; private int mActionColor = mUndefinedColor; private boolean mShowAnimated = true; private boolean mDismissAnimated = true; private boolean mIsReplacePending = false; private boolean mIsShowingByReplace = false; private long mCustomDuration = -1; private ActionClickListener mActionClickListener; private ActionSwipeListener mActionSwipeListener; private boolean mShouldAllowMultipleActionClicks; private boolean mActionClicked; private boolean mShouldDismissOnActionClicked = true; private EventListener mEventListener; private Typeface mTextTypeface; private Typeface mActionTypeface; private boolean mIsShowing = false; private boolean mCanSwipeToDismiss = true; private boolean mIsDismissing = false; private Rect mWindowInsets = new Rect(); private Rect mDisplayFrame = new Rect(); private Point mDisplaySize = new Point(); private Point mRealDisplaySize = new Point(); private Activity mTargetActivity; private Float mMaxWidthPercentage = null; private boolean mUsePhoneLayout; private Runnable mDismissRunnable = new Runnable() { @Override public void run() { dismiss(); } }; private Runnable mRefreshLayoutParamsMarginsRunnable = new Runnable() { @Override public void run() { refreshLayoutParamsMargins(); } }; private Snackbar(Context context) { super(context); // inject helper view to use onWindowSystemUiVisibilityChangedCompat() event if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { addView(new SnackbarHelperChildViewJB(getContext())); } } public static Snackbar with(Context context) { return new Snackbar(context); } /** * Sets the type of {@link Snackbar} to be displayed. * * @param type the {@link SnackbarType} of this instance * @return */ public Snackbar type(SnackbarType type) { mType = type; return this; } /** * Sets the text to be displayed in this {@link Snackbar} * * @param text * @return */ public Snackbar text(CharSequence text) { mText = text; if (snackbarText != null) { snackbarText.setText(mText); } return this; } /** * Sets the text to be displayed in this {@link Snackbar} * * @param resId * @return */ public Snackbar text(@StringRes int resId) { return text(getContext().getText(resId)); } /** * Sets the background color of this {@link Snackbar} * * @param color * @return */ public Snackbar color(int color) { mColor = color; return this; } /** * Sets the background color of this {@link Snackbar} * * @param resId * @return */ public Snackbar colorResource(@ColorRes int resId) { return color(getResources().getColor(resId)); } /** * Sets the background drawable of this {@link Snackbar} * * @param resId * @return */ public Snackbar backgroundDrawable(@DrawableRes int resId) { mDrawable = resId; return this; } /** * Sets the text color of this {@link Snackbar} * * @param textColor * @return */ public Snackbar textColor(int textColor) { mTextColor = textColor; return this; } /** * Sets the text color of this {@link Snackbar} * * @param resId * @return */ public Snackbar textColorResource(@ColorRes int resId) { return textColor(getResources().getColor(resId)); } /** * Sets the text color of this {@link Snackbar}'s top line, or null for none * * @param lineColor * @return */ public Snackbar lineColor(Integer lineColor) { mLineColor = lineColor; return this; } /** * Sets the text color of this {@link Snackbar}'s top line * * @param resId * @return */ public Snackbar lineColorResource(@ColorRes int resId) { return lineColor(getResources().getColor(resId)); } /** * Sets the action label to be displayed, if any. Note that if this is not set, the action * button will not be displayed * * @param actionButtonLabel * @return */ public Snackbar actionLabel(CharSequence actionButtonLabel) { mActionLabel = actionButtonLabel; return this; } /** * Sets the action label to be displayed, if any. Note that if this is not set, the action * button will not be displayed * * @param resId * @return */ public Snackbar actionLabel(@StringRes int resId) { return actionLabel(getContext().getString(resId)); } /** * Set the position of the {@link Snackbar}. Note that if this is not set, the default is to * show the snackbar to the bottom of the screen. * * @param position * @return */ public Snackbar position(SnackbarPosition position) { mPhonePosition = position; return this; } /** * Set the position for wide screen (tablets | desktop) of the {@link Snackbar}. Note that if this is not set, the default is to * show the snackbar to the bottom | center of the screen. * * @param position A {@link com.nispok.snackbar.Snackbar.SnackbarPosition} * @return A {@link Snackbar} instance to make changing */ public Snackbar widePosition(SnackbarPosition position){ mWidePosition = position; return this; } /** * Sets all the margins of the {@link Snackbar} to the same value, in pixels * * @param margin * @return */ public Snackbar margin(int margin) { return margin(margin, margin, margin, margin); } /** * Sets the margins of the {@link Snackbar} in pixels such that the left and right are equal, and the top and bottom are equal * * @param marginLR * @param marginTB * @return */ public Snackbar margin(int marginLR, int marginTB) { return margin(marginLR, marginTB, marginLR, marginTB); } /** * Sets all the margin of the {@link Snackbar} individually, in pixels * * @param marginLeft * @param marginTop * @param marginRight * @param marginBottom * @return */ public Snackbar margin(int marginLeft, int marginTop, int marginRight, int marginBottom) { mMarginLeft = marginLeft; mMarginTop = marginTop; mMarginBottom = marginBottom; mMarginRight = marginRight; return this; } /** * Sets the color of the action button label. Note that you must set a button label with * {@link Snackbar#actionLabel(CharSequence)} for this button to be displayed * * @param actionColor * @return */ public Snackbar actionColor(int actionColor) { mActionColor = actionColor; return this; } /** * Sets the color of the action button label. Note that you must set a button label with * {@link Snackbar#actionLabel(CharSequence)} for this button to be displayed * * @param resId * @return */ public Snackbar actionColorResource(@ColorRes int resId) { return actionColor(getResources().getColor(resId)); } /** * Determines whether this {@link Snackbar} should dismiss when the action button is touched * * @param shouldDismiss * @return */ public Snackbar dismissOnActionClicked(boolean shouldDismiss) { mShouldDismissOnActionClicked = shouldDismiss; return this; } /** * Sets the listener to be called when the {@link Snackbar} action is * selected. Note that you must set a button label with * {@link Snackbar#actionLabel(CharSequence)} for this button to be displayed * * @param listener * @return */ public Snackbar actionListener(ActionClickListener listener) { mActionClickListener = listener; return this; } /** * Sets the listener to be called when the {@link Snackbar} is dismissed by swipe. * * @param listener * @return */ public Snackbar swipeListener(ActionSwipeListener listener) { mActionSwipeListener = listener; return this; } /** * Determines whether this {@link Snackbar} should allow the action button to be * clicked multiple times * * @param shouldAllow * @return */ public Snackbar allowMultipleActionClicks(boolean shouldAllow) { mShouldAllowMultipleActionClicks = shouldAllow; return this; } /** * Sets the listener to be called when the {@link Snackbar} is dismissed. * * @param listener * @return */ public Snackbar eventListener(EventListener listener) { mEventListener = listener; return this; } /** * Sets on/off both show and dismiss animations for this {@link Snackbar} * * @param withAnimation * @return */ public Snackbar animation(boolean withAnimation) { mShowAnimated = withAnimation; mDismissAnimated = withAnimation; return this; } /** * Sets on/off show animation for this {@link Snackbar} * * @param withAnimation * @return */ public Snackbar showAnimation(boolean withAnimation) { mShowAnimated = withAnimation; return this; } /** * Sets on/off dismiss animation for this {@link Snackbar} * * @param withAnimation * @return */ public Snackbar dismissAnimation(boolean withAnimation) { mDismissAnimated = withAnimation; return this; } /** * Determines whether this {@link com.nispok.snackbar.Snackbar} can be swiped off from the screen * * @param canSwipeToDismiss * @return */ public Snackbar swipeToDismiss(boolean canSwipeToDismiss) { mCanSwipeToDismiss = canSwipeToDismiss; return this; } /** * Sets the duration of this {@link Snackbar}. See * {@link Snackbar.SnackbarDuration} for available options * * @param duration * @return */ public Snackbar duration(SnackbarDuration duration) { mDuration = duration; return this; } /** * Sets a custom duration of this {@link Snackbar} * * @param duration custom duration. Value must be greater than 0 or it will be ignored * @return */ public Snackbar duration(long duration) { mCustomDuration = duration > 0 ? duration : mCustomDuration; return this; } /** * Attaches this {@link Snackbar} to an AbsListView (ListView, GridView, ExpandableListView) so * it dismisses when the list is scrolled * * @param absListView * @return */ public Snackbar attachToAbsListView(AbsListView absListView) { absListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { dismiss(); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); return this; } /** * Attaches this {@link Snackbar} to a RecyclerView so it dismisses when the list is scrolled * * @param recyclerView The RecyclerView instance to attach to. * @return */ public Snackbar attachToRecyclerView(View recyclerView) { try { Class.forName("android.support.v7.widget.RecyclerView"); // We got here, so now we can safely check RecyclerUtil.setScrollListener(this, recyclerView); } catch (ClassNotFoundException ignored) { throw new IllegalArgumentException("RecyclerView not found. Did you add it to your dependencies?"); } return this; } /** * Use a custom typeface for this Snackbar's text * * @param typeface * @return */ public Snackbar textTypeface(Typeface typeface) { mTextTypeface = typeface; return this; } /** * Use a custom typeface for this Snackbar's action label * * @param typeface * @return */ public Snackbar actionLabelTypeface(Typeface typeface) { mActionTypeface = typeface; return this; } private static MarginLayoutParams createMarginLayoutParams(ViewGroup viewGroup, int width, int height, SnackbarPosition position) { if (viewGroup instanceof FrameLayout) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height); params.gravity = position.getLayoutGravity(); return params; } else if (viewGroup instanceof RelativeLayout) { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height); if (position == SnackbarPosition.TOP) params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); else params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); return params; } else if (viewGroup instanceof LinearLayout) { LinearLayout.LayoutParams params = new LayoutParams(width, height); params.gravity = position.getLayoutGravity(); return params; } else { throw new IllegalStateException("Requires FrameLayout or RelativeLayout for the parent of Snackbar"); } } static boolean shouldUsePhoneLayout(Context context) { if (context == null) { return true; } else { return context.getResources().getBoolean(R.bool.sb__is_phone); } } private MarginLayoutParams init(Context context, Activity targetActivity, ViewGroup parent, boolean usePhoneLayout) { SnackbarLayout layout = (SnackbarLayout) LayoutInflater.from(context) .inflate(R.layout.sb__template, this, true); layout.setOrientation(LinearLayout.VERTICAL); Resources res = getResources(); mColor = mColor != mUndefinedColor ? mColor : res.getColor(R.color.sb__background); mOffset = res.getDimensionPixelOffset(R.dimen.sb__offset); mUsePhoneLayout = usePhoneLayout; float scale = res.getDisplayMetrics().density; MarginLayoutParams params; if (mUsePhoneLayout) { // Phone layout.setMinimumHeight(dpToPx(mType.getMinHeight(), scale)); layout.setMaxHeight(dpToPx(mType.getMaxHeight(), scale)); layout.setBackgroundColor(mColor); params = createMarginLayoutParams( parent, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT, mPhonePosition); } else { // Tablet/desktop mType = SnackbarType.SINGLE_LINE; // Force single-line layout.setMinimumWidth(res.getDimensionPixelSize(R.dimen.sb__min_width)); layout.setMaxWidth( mMaxWidthPercentage == null ? res.getDimensionPixelSize(R.dimen.sb__max_width) : DisplayCompat.getWidthFromPercentage(targetActivity, mMaxWidthPercentage)); layout.setBackgroundResource(R.drawable.sb__bg); GradientDrawable bg = (GradientDrawable) layout.getBackground(); bg.setColor(mColor); params = createMarginLayoutParams( parent, FrameLayout.LayoutParams.WRAP_CONTENT, dpToPx(mType.getMaxHeight(), scale), mWidePosition); } if (mDrawable != mUndefinedDrawable) setBackgroundDrawable(layout, res.getDrawable(mDrawable)); if (mLineColor != null) { layout.findViewById(R.id.sb__divider).setBackgroundColor(mLineColor); } else { layout.findViewById(R.id.sb__divider).setVisibility(View.GONE); } snackbarText = (TextView) layout.findViewById(R.id.sb__text); snackbarText.setText(mText); snackbarText.setTypeface(mTextTypeface); if (mTextColor != mUndefinedColor) { snackbarText.setTextColor(mTextColor); } snackbarText.setMaxLines(mType.getMaxLines()); TextView snackbarAction = (TextView) layout.findViewById(R.id.sb__action); if (!TextUtils.isEmpty(mActionLabel)) { requestLayout(); snackbarAction.setText(mActionLabel); snackbarAction.setTypeface(mActionTypeface); if (mActionColor != mUndefinedColor) { snackbarAction.setTextColor(mActionColor); } snackbarAction.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (mActionClickListener != null) { // Before calling the onActionClicked() callback, make sure: // 1) The snackbar is not dismissing // 2) If we aren't allowing multiple clicks, that this is the first click if (!mIsDismissing && (!mActionClicked || mShouldAllowMultipleActionClicks)) { mActionClickListener.onActionClicked(Snackbar.this); mActionClicked = true; } } if (mShouldDismissOnActionClicked) { dismiss(); } } }); snackbarAction.setMaxLines(mType.getMaxLines()); } else { snackbarAction.setVisibility(GONE); } setClickable(true); if (mCanSwipeToDismiss && res.getBoolean(R.bool.sb__is_swipeable)) { setOnTouchListener(new SwipeDismissTouchListener(this, null, new SwipeDismissTouchListener.DismissCallbacks() { @Override public boolean canDismiss(Object token) { return true; } @Override public void onDismiss(View view, Object token) { if (view != null) { if (mActionSwipeListener != null) { mActionSwipeListener.onSwipeToDismiss(); } dismiss(false); } } @Override public void pauseTimer(boolean shouldPause) { if (isIndefiniteDuration()) { return; } if (shouldPause) { removeCallbacks(mDismissRunnable); mSnackbarFinish = System.currentTimeMillis(); } else { mTimeRemaining -= (mSnackbarFinish - mSnackbarStart); startTimer(mTimeRemaining); } } })); } return params; } private void updateWindowInsets(Activity targetActivity, Rect outInsets) { outInsets.left = outInsets.top = outInsets.right = outInsets.bottom = 0; if (targetActivity == null) { return; } ViewGroup decorView = (ViewGroup) targetActivity.getWindow().getDecorView(); Display display = targetActivity.getWindowManager().getDefaultDisplay(); boolean isTranslucent = isNavigationBarTranslucent(targetActivity); boolean isHidden = isNavigationBarHidden(decorView); Rect dispFrame = mDisplayFrame; Point realDispSize = mRealDisplaySize; Point dispSize = mDisplaySize; decorView.getWindowVisibleDisplayFrame(dispFrame); DisplayCompat.getRealSize(display, realDispSize); DisplayCompat.getSize(display, dispSize); if (dispSize.x < realDispSize.x) { // navigation bar is placed on right side of the screen if (isTranslucent || isHidden) { int navBarWidth = realDispSize.x - dispSize.x; int overlapWidth = realDispSize.x - dispFrame.right; outInsets.right = Math.max(Math.min(navBarWidth, overlapWidth), 0); } } else if (dispSize.y < realDispSize.y) { // navigation bar is placed on bottom side of the screen if (isTranslucent || isHidden) { int navBarHeight = realDispSize.y - dispSize.y; int overlapHeight = realDispSize.y - dispFrame.bottom; outInsets.bottom = Math.max(Math.min(navBarHeight, overlapHeight), 0); } } } private static int dpToPx(int dp, float scale) { return (int) (dp * scale + 0.5f); } public void showByReplace(Activity targetActivity) { mIsShowingByReplace = true; show(targetActivity); } public void showByReplace(ViewGroup parent) { mIsShowingByReplace = true; show(parent, shouldUsePhoneLayout(parent.getContext())); } public void showByReplace(ViewGroup parent, boolean usePhoneLayout) { mIsShowingByReplace = true; show(parent, usePhoneLayout); } /** * Displays the {@link Snackbar} at the bottom of the * {@link android.app.Activity} provided. * * @param targetActivity */ public void show(Activity targetActivity) { ViewGroup root = (ViewGroup) targetActivity.findViewById(android.R.id.content); boolean usePhoneLayout = shouldUsePhoneLayout(targetActivity); MarginLayoutParams params = init(targetActivity, targetActivity, root, usePhoneLayout); updateLayoutParamsMargins(targetActivity, params); showInternal(targetActivity, params, root); } /** * Displays the {@link Snackbar} at the bottom of the * {@link android.view.ViewGroup} provided. * * @param parent */ public void show(ViewGroup parent) { show(parent, shouldUsePhoneLayout(parent.getContext())); } /** * Displays the {@link Snackbar} at the bottom of the * {@link android.view.ViewGroup} provided. * * @param parent * @param usePhoneLayout */ public void show(ViewGroup parent, boolean usePhoneLayout) { MarginLayoutParams params = init(parent.getContext(), null, parent, usePhoneLayout); updateLayoutParamsMargins(null, params); showInternal(null, params, parent); } public Snackbar maxWidthPercentage(float maxWidthPercentage) { mMaxWidthPercentage = maxWidthPercentage; return this; } private void showInternal(Activity targetActivity, MarginLayoutParams params, ViewGroup parent) { parent.removeView(this); // We need to make sure the Snackbar elevation is at least as high as // any other child views, or it will be displayed underneath them if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { for (int i = 0; i < parent.getChildCount(); i++) { View otherChild = parent.getChildAt(i); float elvation = otherChild.getElevation(); if (elvation > getElevation()) { setElevation(elvation); } } } parent.addView(this, params); bringToFront(); // As requested in the documentation for bringToFront() if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { parent.requestLayout(); parent.invalidate(); } mIsShowing = true; mTargetActivity = targetActivity; getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { getViewTreeObserver().removeOnPreDrawListener(this); if (mEventListener != null) { if (mIsShowingByReplace) { mEventListener.onShowByReplace(Snackbar.this); } else { mEventListener.onShow(Snackbar.this); } if (!mShowAnimated) { mEventListener.onShown(Snackbar.this); mIsShowingByReplace = false; // reset flag } } return true; } }); if (!mShowAnimated) { if (shouldStartTimer()) { startTimer(); } return; } Animation slideIn = AnimationUtils.loadAnimation(getContext(), getInAnimationResource(mPhonePosition)); slideIn.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (mEventListener != null) { mEventListener.onShown(Snackbar.this); mIsShowingByReplace = false; // reset flag } focusForAccessibility(snackbarText); post(new Runnable() { @Override public void run() { mSnackbarStart = System.currentTimeMillis(); if (mTimeRemaining == -1) { mTimeRemaining = getDuration(); } if (shouldStartTimer()) { startTimer(); } } }); } @Override public void onAnimationRepeat(Animation animation) { } }); startAnimation(slideIn); } private void focusForAccessibility(View view) { final AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_FOCUSED); AccessibilityEventCompat.asRecord(event).setSource(view); try { view.sendAccessibilityEventUnchecked(event); } catch (IllegalStateException e) { // accessibility is off. } } private boolean shouldStartTimer() { return !isIndefiniteDuration(); } private boolean isIndefiniteDuration() { return getDuration() == SnackbarDuration.LENGTH_INDEFINITE.getDuration(); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private boolean isNavigationBarHidden(ViewGroup root) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { return false; } int viewFlags = root.getWindowSystemUiVisibility(); return (viewFlags & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) == View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; } private boolean isNavigationBarTranslucent(Activity targetActivity) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return false; } int flags = targetActivity.getWindow().getAttributes().flags; return (flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) != 0; } private void startTimer() { postDelayed(mDismissRunnable, getDuration()); } private void startTimer(long duration) { postDelayed(mDismissRunnable, duration); } public void dismissByReplace() { mIsReplacePending = true; dismiss(); } public void dismiss() { dismiss(mDismissAnimated); } private void dismiss(boolean animate) { if (mIsDismissing) { return; } mIsDismissing = true; if (mEventListener != null && mIsShowing) { if (mIsReplacePending) { mEventListener.onDismissByReplace(Snackbar.this); } else { mEventListener.onDismiss(Snackbar.this); } } if (!animate) { finish(); return; } final Animation slideOut = AnimationUtils.loadAnimation(getContext(), getOutAnimationResource(mPhonePosition)); slideOut.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { post(new Runnable() { @Override public void run() { finish(); } }); } @Override public void onAnimationRepeat(Animation animation) { } }); startAnimation(slideOut); } private void finish() { clearAnimation(); ViewGroup parent = (ViewGroup) getParent(); if (parent != null) { parent.removeView(this); } if (mEventListener != null && mIsShowing) { mEventListener.onDismissed(this); } mIsShowing = false; mIsDismissing = false; mIsReplacePending = false; mTargetActivity = null; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mIsShowing = false; if (mDismissRunnable != null) { removeCallbacks(mDismissRunnable); } if (mRefreshLayoutParamsMarginsRunnable != null) { removeCallbacks(mRefreshLayoutParamsMarginsRunnable); } } void dispatchOnWindowSystemUiVisibilityChangedCompat(int visible) { onWindowSystemUiVisibilityChangedCompat(visible); } protected void onWindowSystemUiVisibilityChangedCompat(int visible) { if (mRefreshLayoutParamsMarginsRunnable != null) { post(mRefreshLayoutParamsMarginsRunnable); } } protected void refreshLayoutParamsMargins() { if (mIsDismissing) { return; } ViewGroup parent = (ViewGroup) getParent(); if (parent == null) { return; } MarginLayoutParams params = (MarginLayoutParams) getLayoutParams(); updateLayoutParamsMargins(mTargetActivity, params); setLayoutParams(params); } protected void updateLayoutParamsMargins(Activity targetActivity, MarginLayoutParams params) { if (mUsePhoneLayout) { // Phone params.topMargin = mMarginTop; params.rightMargin = mMarginRight; params.leftMargin = mMarginLeft; params.bottomMargin = mMarginBottom; } else { // Tablet/desktop params.topMargin = mMarginTop; params.rightMargin = mMarginRight; params.leftMargin = mMarginLeft + mOffset; params.bottomMargin = mMarginBottom + mOffset; } // Add bottom/right margin when navigation bar is hidden or translucent updateWindowInsets(targetActivity, mWindowInsets); params.rightMargin += mWindowInsets.right; params.bottomMargin += mWindowInsets.bottom; } public int getActionColor() { return mActionColor; } public CharSequence getActionLabel() { return mActionLabel; } public int getTextColor() { return mTextColor; } public int getColor() { return mColor; } public int getLineColor() { return mLineColor; } public CharSequence getText() { return mText; } public long getDuration() { return mCustomDuration == -1 ? mDuration.getDuration() : mCustomDuration; } public SnackbarType getType() { return mType; } /** * @return whether the action button has been clicked. In other words, this method will let * you know if {@link com.nispok.snackbar.listeners.ActionClickListener#onActionClicked(Snackbar)} * was called. This is useful, for instance, if you want to know during * {@link com.nispok.snackbar.listeners.EventListener#onDismiss(Snackbar)} if the * {@link com.nispok.snackbar.Snackbar} is being dismissed because of its action click */ public boolean isActionClicked() { return mActionClicked; } /** * @return the pixel offset of this {@link com.nispok.snackbar.Snackbar} from the left and * bottom of the {@link android.app.Activity}. */ public int getOffset() { return mOffset; } /** * @return true only if both dismiss and show animations are enabled */ public boolean isAnimated() { return mShowAnimated && mDismissAnimated; } public boolean isDismissAnimated() { return mDismissAnimated; } public boolean isShowAnimated() { return mShowAnimated; } public boolean shouldDismissOnActionClicked() { return mShouldDismissOnActionClicked; } /** * @return true if this {@link com.nispok.snackbar.Snackbar} is currently showing */ public boolean isShowing() { return mIsShowing; } /** * @return true if this {@link com.nispok.snackbar.Snackbar} is dismissing. */ public boolean isDimissing() { return mIsDismissing; } /** * @return false if this {@link com.nispok.snackbar.Snackbar} has been dismissed */ public boolean isDismissed() { return !mIsShowing; } /** * @param snackbarPosition * @return the animation resource used by this {@link com.nispok.snackbar.Snackbar} instance * to enter the view */ @AnimRes public static int getInAnimationResource(SnackbarPosition snackbarPosition) { return snackbarPosition == SnackbarPosition.TOP ? R.anim.sb__top_in : R.anim.sb__bottom_in; } /** * @param snackbarPosition * @return the animation resource used by this {@link com.nispok.snackbar.Snackbar} instance * to exit the view */ @AnimRes public static int getOutAnimationResource(SnackbarPosition snackbarPosition) { return snackbarPosition == SnackbarPosition.TOP ? R.anim.sb__top_out : R.anim.sb__bottom_out; } /** * Set a Background Drawable using the appropriate Android version api call * * @param view * @param drawable */ public static void setBackgroundDrawable(View view, Drawable drawable) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) { view.setBackgroundDrawable(drawable); } else { view.setBackground(drawable); } } }
package org.innovateuk.ifs.application.overview.populator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.innovateuk.ifs.applicant.resource.ApplicantQuestionResource; import org.innovateuk.ifs.applicant.resource.ApplicantSectionResource; import org.innovateuk.ifs.applicant.service.ApplicantRestService; import org.innovateuk.ifs.application.populator.AssignButtonsPopulator; import org.innovateuk.ifs.application.resource.*; import org.innovateuk.ifs.application.service.*; import org.innovateuk.ifs.application.overview.viewmodel.ApplicationOverviewViewModel; import org.innovateuk.ifs.application.viewmodel.AssignButtonsViewModel; import org.innovateuk.ifs.application.overview.viewmodel.ApplicationOverviewAssignableViewModel; import org.innovateuk.ifs.application.overview.viewmodel.ApplicationOverviewCompletedViewModel; import org.innovateuk.ifs.application.overview.viewmodel.ApplicationOverviewSectionViewModel; import org.innovateuk.ifs.application.overview.viewmodel.ApplicationOverviewUserViewModel; import org.innovateuk.ifs.category.resource.ResearchCategoryResource; import org.innovateuk.ifs.category.service.CategoryRestService; import org.innovateuk.ifs.commons.rest.RestResult; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.invite.constant.InviteStatus; import org.innovateuk.ifs.invite.resource.ApplicationInviteResource; import org.innovateuk.ifs.invite.resource.InviteOrganisationResource; import org.innovateuk.ifs.invite.service.InviteRestService; import org.innovateuk.ifs.project.ProjectService; import org.innovateuk.ifs.project.resource.ProjectResource; import org.innovateuk.ifs.user.resource.OrganisationResource; import org.innovateuk.ifs.user.resource.ProcessRoleResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.service.ProcessRoleService; import org.innovateuk.ifs.user.service.UserService; import org.innovateuk.ifs.util.CollectionFunctions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.*; import java.util.concurrent.Future; import java.util.function.Function; import java.util.stream.Collectors; import static org.innovateuk.ifs.application.resource.SectionType.FINANCE; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFilter; /** * view model for the application overview page */ @Component public class ApplicationOverviewModelPopulator { private static final Log LOG = LogFactory.getLog(ApplicationOverviewModelPopulator.class); @Autowired private AssignButtonsPopulator assignButtonsPopulator; @Autowired private CompetitionService competitionService; @Autowired private ProcessRoleService processRoleService; @Autowired private OrganisationService organisationService; @Autowired private UserService userService; @Autowired private QuestionService questionService; @Autowired private InviteRestService inviteRestService; @Autowired private SectionService sectionService; @Autowired private ProjectService projectService; @Autowired private CategoryRestService categoryRestService; @Autowired private ApplicantRestService applicantRestService; public ApplicationOverviewViewModel populateModel(ApplicationResource application, Long userId){ CompetitionResource competition = competitionService.getById(application.getCompetition()); List<ProcessRoleResource> userApplicationRoles = processRoleService.findProcessRolesByApplicationId(application.getId()); Optional<OrganisationResource> userOrganisation = organisationService.getOrganisationForUser(userId, userApplicationRoles); ProjectResource projectResource = projectService.getByApplicationId(application.getId()); ApplicationOverviewUserViewModel userViewModel = getUserDetails(application, userId); ApplicationOverviewAssignableViewModel assignableViewModel = getAssignableDetails(application, userOrganisation.orElse(null), userId); ApplicationOverviewCompletedViewModel completedViewModel = getCompletedDetails(application, userOrganisation); ApplicationOverviewSectionViewModel sectionViewModel = getSections(competition, application, userId); Long yourFinancesSectionId = getYourFinancesSectionId(application); int completedQuestionsPercentage = application.getCompletion() == null ? 0 : application.getCompletion().intValue(); List<ResearchCategoryResource> researchCategories = categoryRestService.getResearchCategories().getSuccessObjectOrThrowException(); return new ApplicationOverviewViewModel(application, projectResource, competition, userOrganisation.orElse(null), completedQuestionsPercentage, yourFinancesSectionId, userViewModel, assignableViewModel, completedViewModel, sectionViewModel, researchCategories); } private ApplicationOverviewSectionViewModel getSections(CompetitionResource competition, ApplicationResource application, Long userId) { final List<SectionResource> allSections = sectionService.getAllByCompetitionId(competition.getId()); final List<SectionResource> parentSections = sectionService.filterParentSections(allSections); final List<ApplicantSectionResource> parentApplicantSections = parentSections.stream().map(sectionResource -> applicantRestService.getSection(userId, application.getId(), sectionResource.getId())).collect(Collectors.toList()); final SortedMap<Long, SectionResource> sections = CollectionFunctions.toSortedMap(parentSections, SectionResource::getId, Function.identity()); final Map<Long, List<SectionResource>> subSections = parentSections.stream() .collect(Collectors.toMap( SectionResource::getId, s -> getSectionsFromListByIdList(s.getChildSections(), allSections) )); final Map<Long, List<QuestionResource>> sectionQuestions = parentApplicantSections.stream() .collect(Collectors.toMap( s -> s.getSection().getId(), s -> s.getApplicantQuestions().stream().map(ApplicantQuestionResource::getQuestion).collect(Collectors.toList())) ); final List<SectionResource> financeSections = getFinanceSectionIds(parentSections); boolean hasFinanceSection = false; Long financeSectionId = null; if (!financeSections.isEmpty()) { hasFinanceSection = true; financeSectionId = financeSections.get(0).getId(); } Map<Long, AssignButtonsViewModel> assignButtonViewModels = new HashMap<>(); parentApplicantSections.forEach(applicantSectionResource -> { applicantSectionResource.getApplicantQuestions().forEach(questionResource -> { assignButtonViewModels.put(questionResource.getQuestion().getId(), assignButtonsPopulator.populate(applicantSectionResource, questionResource, questionResource.isCompleteByApplicant(applicantSectionResource.getCurrentApplicant()))); }); }); return new ApplicationOverviewSectionViewModel(sections, subSections, sectionQuestions, financeSections, hasFinanceSection, financeSectionId, assignButtonViewModels); } private List<SectionResource> getFinanceSectionIds(List<SectionResource> sections){ return sections.stream() .filter(s -> SectionType.FINANCE.equals(s.getType())) .collect(Collectors.toList()); } private List<SectionResource> getSectionsFromListByIdList(final List<Long> childSections, List<SectionResource> allSections) { allSections.sort(Comparator.comparing(SectionResource::getPriority, Comparator.nullsLast(Comparator.naturalOrder()))); return simpleFilter(allSections, section -> childSections.contains(section.getId())); } private List<QuestionResource> getQuestionsBySection(final List<Long> questionIds, List<QuestionResource> questions) { questions.sort(Comparator.comparing(QuestionResource::getPriority, Comparator.nullsLast(Comparator.naturalOrder()))); return simpleFilter(questions, q -> questionIds.contains(q.getId())); } private ApplicationOverviewUserViewModel getUserDetails(ApplicationResource application, Long userId) { Boolean userIsLeadApplicant = userService.isLeadApplicant(userId, application); ProcessRoleResource leadApplicantProcessRole = userService.getLeadApplicantProcessRoleOrNull(application); UserResource leadApplicant = userService.findById(leadApplicantProcessRole.getUser()); return new ApplicationOverviewUserViewModel(userIsLeadApplicant, leadApplicant, userIsLeadApplicant && application.isSubmittable()); } private ApplicationOverviewAssignableViewModel getAssignableDetails(ApplicationResource application, OrganisationResource userOrganisation, Long userId) { if (isApplicationInViewMode(application, userOrganisation)) { return new ApplicationOverviewAssignableViewModel(); } Map<Long, QuestionStatusResource> questionAssignees = questionService.getQuestionStatusesForApplicationAndOrganisation(application.getId(), userOrganisation.getId()); List<QuestionStatusResource> notifications = questionService.getNotificationsForUser(questionAssignees.values(), userId); questionService.removeNotifications(notifications); List<ApplicationInviteResource> pendingAssignableUsers = pendingInvitations(application); Future<List<ProcessRoleResource>> assignableUsers = processRoleService.findAssignableProcessRoles(application.getId()); return new ApplicationOverviewAssignableViewModel(assignableUsers, pendingAssignableUsers, questionAssignees, notifications); } private boolean isApplicationInViewMode(ApplicationResource application, OrganisationResource userOrganisation) { return !application.isOpen() || userOrganisation == null; } private List<ApplicationInviteResource> pendingInvitations(ApplicationResource application) { RestResult<List<InviteOrganisationResource>> pendingAssignableUsersResult = inviteRestService.getInvitesByApplication(application.getId()); return pendingAssignableUsersResult.handleSuccessOrFailure( failure -> new ArrayList<>(0), success -> success.stream().flatMap(item -> item.getInviteResources().stream()) .filter(item -> !InviteStatus.OPENED.equals(item.getStatus())) .collect(Collectors.toList())); } private ApplicationOverviewCompletedViewModel getCompletedDetails(ApplicationResource application, Optional<OrganisationResource> userOrganisation) { Future<Set<Long>> markedAsComplete = getMarkedAsCompleteDetails(application, userOrganisation); // List of question ids Map<Long, Set<Long>> completedSectionsByOrganisation = sectionService.getCompletedSectionsByOrganisation(application.getId()); Set<Long> sectionsMarkedAsComplete = getCombinedMarkedAsCompleteSections(completedSectionsByOrganisation); boolean allQuestionsCompleted = sectionService.allSectionsMarkedAsComplete(application.getId()); boolean userFinanceSectionCompleted = isUserFinanceSectionCompleted(application, userOrganisation.get(), completedSectionsByOrganisation); ApplicationOverviewCompletedViewModel viewModel = new ApplicationOverviewCompletedViewModel(sectionsMarkedAsComplete, allQuestionsCompleted, markedAsComplete, userFinanceSectionCompleted); userOrganisation.ifPresent(org -> viewModel.setCompletedSections(completedSectionsByOrganisation.get(org.getId()))); return viewModel; } private Set<Long> getCombinedMarkedAsCompleteSections(Map<Long, Set<Long>> completedSectionsByOrganisation) { Set<Long> combinedMarkedAsComplete = new HashSet<>(); completedSectionsByOrganisation.forEach((organisationId, completedSections) -> combinedMarkedAsComplete.addAll(completedSections)); completedSectionsByOrganisation.forEach((key, values) -> combinedMarkedAsComplete.retainAll(values)); return combinedMarkedAsComplete; } private boolean isUserFinanceSectionCompleted(ApplicationResource application, OrganisationResource userOrganisation, Map<Long, Set<Long>> completedSectionsByOrganisation) { return sectionService.getAllByCompetitionId(application.getCompetition()) .stream() .filter(section -> section.getType().equals(FINANCE)) .map(SectionResource::getId) .anyMatch(id -> completedSectionsByOrganisation.get(userOrganisation.getId()).contains(id)); } private Long getYourFinancesSectionId(ApplicationResource application) { return sectionService.getAllByCompetitionId(application.getCompetition()) .stream() .filter(section -> section.getType().equals(FINANCE)) .findFirst() .map(SectionResource::getId) .orElse(null); } private Future<Set<Long>> getMarkedAsCompleteDetails(ApplicationResource application, Optional<OrganisationResource> userOrganisation) { Long organisationId = userOrganisation .map(OrganisationResource::getId) .orElse(0L); return questionService.getMarkedAsComplete(application.getId(), organisationId); } }
package io.subutai.core.environment.impl; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.security.auth.Subject; import javax.ws.rs.WebApplicationException; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import io.subutai.common.command.CommandException; import io.subutai.common.command.CommandResult; import io.subutai.common.command.CommandUtil; import io.subutai.common.command.RequestBuilder; import io.subutai.common.environment.ContainerHostNotFoundException; import io.subutai.common.environment.EnvConnectivityState; import io.subutai.common.environment.Environment; import io.subutai.common.environment.EnvironmentCreationRef; import io.subutai.common.environment.EnvironmentModificationException; import io.subutai.common.environment.EnvironmentNotFoundException; import io.subutai.common.environment.EnvironmentStatus; import io.subutai.common.environment.PeerConf; import io.subutai.common.environment.Topology; import io.subutai.common.host.ContainerHostState; import io.subutai.common.mdc.SubutaiExecutors; import io.subutai.common.metric.AlertValue; import io.subutai.common.network.ProxyLoadBalanceStrategy; import io.subutai.common.network.SshTunnel; import io.subutai.common.peer.AlertEvent; import io.subutai.common.peer.AlertHandler; import io.subutai.common.peer.AlertHandlerPriority; import io.subutai.common.peer.AlertListener; import io.subutai.common.peer.ContainerHost; import io.subutai.common.peer.ContainerId; import io.subutai.common.peer.ContainerSize; import io.subutai.common.peer.EnvironmentAlertHandler; import io.subutai.common.peer.EnvironmentAlertHandlers; import io.subutai.common.peer.EnvironmentContainerHost; import io.subutai.common.peer.EnvironmentId; import io.subutai.common.peer.Peer; import io.subutai.common.peer.PeerException; import io.subutai.common.protocol.ReverseProxyConfig; import io.subutai.common.security.SshEncryptionType; import io.subutai.common.security.SshKey; import io.subutai.common.security.SshKeys; import io.subutai.common.security.crypto.pgp.KeyPair; import io.subutai.common.security.crypto.pgp.PGPKeyUtil; import io.subutai.common.security.objects.SecurityKeyType; import io.subutai.common.security.relation.RelationManager; import io.subutai.common.settings.Common; import io.subutai.common.tracker.TrackerOperation; import io.subutai.common.util.CollectionUtil; import io.subutai.common.util.ExceptionUtil; import io.subutai.common.util.JsonUtil; import io.subutai.core.environment.api.CancellableWorkflow; import io.subutai.core.environment.api.EnvironmentEventListener; import io.subutai.core.environment.api.EnvironmentManager; import io.subutai.core.environment.api.exception.EnvironmentCreationException; import io.subutai.core.environment.api.exception.EnvironmentDestructionException; import io.subutai.core.environment.api.exception.EnvironmentManagerException; import io.subutai.core.environment.impl.adapter.EnvironmentAdapter; import io.subutai.core.environment.impl.adapter.ProxyEnvironment; import io.subutai.core.environment.impl.dao.EnvironmentService; import io.subutai.core.environment.impl.entity.EnvironmentAlertHandlerImpl; import io.subutai.core.environment.impl.entity.EnvironmentContainerImpl; import io.subutai.core.environment.impl.entity.EnvironmentImpl; import io.subutai.core.environment.impl.workflow.creation.EnvironmentCreationWorkflow; import io.subutai.core.environment.impl.workflow.destruction.ContainerDestructionWorkflow; import io.subutai.core.environment.impl.workflow.destruction.EnvironmentDestructionWorkflow; import io.subutai.core.environment.impl.workflow.modification.EnvironmentModifyWorkflow; import io.subutai.core.environment.impl.workflow.modification.HostnameModificationWorkflow; import io.subutai.core.environment.impl.workflow.modification.P2PSecretKeyModificationWorkflow; import io.subutai.core.environment.impl.workflow.modification.SshKeyAdditionWorkflow; import io.subutai.core.environment.impl.workflow.modification.SshKeyRemovalWorkflow; import io.subutai.core.identity.api.IdentityManager; import io.subutai.core.identity.api.model.Session; import io.subutai.core.identity.api.model.User; import io.subutai.core.identity.api.model.UserDelegate; import io.subutai.core.peer.api.PeerAction; import io.subutai.core.peer.api.PeerActionListener; import io.subutai.core.peer.api.PeerActionResponse; import io.subutai.core.peer.api.PeerManager; import io.subutai.core.security.api.SecurityManager; import io.subutai.core.security.api.crypto.KeyManager; import io.subutai.core.tracker.api.Tracker; import io.subutai.hub.share.common.HubAdapter; import io.subutai.hub.share.common.HubEventListener; import io.subutai.hub.share.dto.PeerProductDataDto; /** * TODO * * 1) add p2pSecret property to peerConf, set it only after successful p2p secret update on the associated peer (in * P2PSecretKeyResetStep) * * 2) add secret key TTL property to environment (user should be able to change it - add to EM API), update background * task to consider this TTL (make background task run frequently with short intervals) **/ @PermitAll public class EnvironmentManagerImpl implements EnvironmentManager, PeerActionListener, AlertListener, HubEventListener { private static final Logger LOG = LoggerFactory.getLogger( EnvironmentManagerImpl.class ); public static final String MODULE_NAME = "Environment Manager"; private final IdentityManager identityManager; private final RelationManager relationManager; private final PeerManager peerManager; private final Tracker tracker; protected Set<EnvironmentEventListener> listeners = Sets.newConcurrentHashSet(); protected ExecutorService executor = SubutaiExecutors.newCachedThreadPool(); protected ExceptionUtil exceptionUtil = new ExceptionUtil(); protected Map<String, AlertHandler> alertHandlers = new ConcurrentHashMap<>(); private SecurityManager securityManager; protected ScheduledExecutorService backgroundTasksExecutorService; private final Map<String, CancellableWorkflow> activeWorkflows = Maps.newConcurrentMap(); Subject systemUser = null; private EnvironmentAdapter environmentAdapter; private EnvironmentService environmentService; public EnvironmentManagerImpl( final PeerManager peerManager, SecurityManager securityManager, final IdentityManager identityManager, final Tracker tracker, final RelationManager relationManager, HubAdapter hubAdapter, final EnvironmentService environmentService ) { Preconditions.checkNotNull( peerManager ); Preconditions.checkNotNull( identityManager ); Preconditions.checkNotNull( relationManager ); Preconditions.checkNotNull( securityManager ); Preconditions.checkNotNull( tracker ); this.peerManager = peerManager; this.securityManager = securityManager; this.identityManager = identityManager; this.relationManager = relationManager; this.tracker = tracker;
package org.eclipse.emf.emfstore.server.model.versioning.operations.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.emfstore.common.model.IdEObjectCollection; import org.eclipse.emf.emfstore.server.model.versioning.operations.AbstractOperation; import org.eclipse.emf.emfstore.server.model.versioning.operations.MultiAttributeSetOperation; import org.eclipse.emf.emfstore.server.model.versioning.operations.OperationsFactory; import org.eclipse.emf.emfstore.server.model.versioning.operations.OperationsPackage; import org.eclipse.emf.emfstore.server.model.versioning.operations.UnkownFeatureException; /** * <!-- begin-user-doc --> An implementation of the model object ' <em><b>Multi Attribute Set Operation</b></em>'. <!-- * end-user-doc --> * <p> * The following features are implemented: * <ul> * <li> * {@link org.eclipse.emf.emfstore.server.model.versioning.operations.impl.MultiAttributeSetOperationImpl#getIndex * <em>Index</em>}</li> * <li> * {@link org.eclipse.emf.emfstore.server.model.versioning.operations.impl.MultiAttributeSetOperationImpl#getOldValue * <em>Old Value</em>}</li> * <li> * {@link org.eclipse.emf.emfstore.server.model.versioning.operations.impl.MultiAttributeSetOperationImpl#getNewValue * <em>New Value</em>}</li> * </ul> * </p> * * @generated */ public class MultiAttributeSetOperationImpl extends FeatureOperationImpl implements MultiAttributeSetOperation { /** * The default value of the '{@link #getIndex() <em>Index</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getIndex() * @generated * @ordered */ protected static final int INDEX_EDEFAULT = 0; /** * The cached value of the '{@link #getIndex() <em>Index</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getIndex() * @generated * @ordered */ protected int index = INDEX_EDEFAULT; /** * The default value of the '{@link #getOldValue() <em>Old Value</em>}' * attribute. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getOldValue() * @generated * @ordered */ protected static final Object OLD_VALUE_EDEFAULT = null; /** * The cached value of the '{@link #getOldValue() <em>Old Value</em>}' * attribute. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getOldValue() * @generated * @ordered */ protected Object oldValue = OLD_VALUE_EDEFAULT; /** * The default value of the '{@link #getNewValue() <em>New Value</em>}' * attribute. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getNewValue() * @generated * @ordered */ protected static final Object NEW_VALUE_EDEFAULT = null; /** * The cached value of the '{@link #getNewValue() <em>New Value</em>}' * attribute. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getNewValue() * @generated * @ordered */ protected Object newValue = NEW_VALUE_EDEFAULT; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ protected MultiAttributeSetOperationImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return OperationsPackage.Literals.MULTI_ATTRIBUTE_SET_OPERATION; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public int getIndex() { return index; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setIndex(int newIndex) { int oldIndex = index; index = newIndex; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__INDEX, oldIndex, index)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public Object getOldValue() { return oldValue; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setOldValue(Object newOldValue) { Object oldOldValue = oldValue; oldValue = newOldValue; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__OLD_VALUE, oldOldValue, oldValue)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public Object getNewValue() { return newValue; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setNewValue(Object newNewValue) { Object oldNewValue = newValue; newValue = newNewValue; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__NEW_VALUE, oldNewValue, newValue)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__INDEX: return getIndex(); case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__OLD_VALUE: return getOldValue(); case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__NEW_VALUE: return getNewValue(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__INDEX: setIndex((Integer) newValue); return; case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__OLD_VALUE: setOldValue(newValue); return; case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__NEW_VALUE: setNewValue(newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__INDEX: setIndex(INDEX_EDEFAULT); return; case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__OLD_VALUE: setOldValue(OLD_VALUE_EDEFAULT); return; case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__NEW_VALUE: setNewValue(NEW_VALUE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__INDEX: return index != INDEX_EDEFAULT; case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__OLD_VALUE: return OLD_VALUE_EDEFAULT == null ? oldValue != null : !OLD_VALUE_EDEFAULT.equals(oldValue); case OperationsPackage.MULTI_ATTRIBUTE_SET_OPERATION__NEW_VALUE: return NEW_VALUE_EDEFAULT == null ? newValue != null : !NEW_VALUE_EDEFAULT.equals(newValue); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (index: "); result.append(index); result.append(", oldValue: "); result.append(oldValue); result.append(", newValue: "); result.append(newValue); result.append(')'); return result.toString(); } /** * {@inheritDoc} * * @see org.eclipse.emf.emfstore.server.model.versioning.operations.AbstractOperation#apply(org.eclipse.emf.emfstore.common.model.Project) */ @SuppressWarnings("unchecked") public void apply(IdEObjectCollection project) { EObject modelElement = project.getModelElement(getModelElementId()); if (modelElement == null) { return; } EAttribute feature; try { feature = (EAttribute) getFeature(modelElement); EList<Object> list = (EList<Object>) modelElement.eGet(feature); if (feature.isUnique() && list.contains(getNewValue())) { // silently skip setting value since it is already contained, but should be unique return; } int i = getIndex(); if ((i >= 0 && i < list.size())) { list.set(i, getNewValue()); } } catch (UnkownFeatureException e) { } } @Override public AbstractOperation reverse() { MultiAttributeSetOperation attributeOperation = OperationsFactory.eINSTANCE.createMultiAttributeSetOperation(); super.reverse(attributeOperation); attributeOperation.setIndex(getIndex()); // swap old and new value attributeOperation.setNewValue(getOldValue()); attributeOperation.setOldValue(getNewValue()); return attributeOperation; } } // MultiAttributeSetOperationImpl
package org.isoblue.isobus; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * Represents a Socket style connection to a {@link Bus} on an ISOBUS Network. * <p> * This class is used to send and receive {@link Message}s using * {@link #write(Message)} and {@link #read()} respectively. * * @see ISOBUSNetwork * @see Bus * @see Message * @author Alex Layton <alex@layton.in> */ public class ISOBUSSocket implements Closeable { /** * ISOBUS Bus to which this {@link ISOBUSSocket} is connected. */ private Bus mBus; /** * ISOBUS NAME used to identify the user of this {@link ISOBUSSocket} on the * network. */ // TODO: Implement using this private NAME mName; /** * Used to filter what is received on this {@link ISOBUSSocket}. * <p> * If it is empty, no filtering is done. * * @see Message */ private Set<PGN> mPgns; /** * Buffer for what has been received but not yet read. */ private BlockingQueue<Message> mInMessages; /** * Construct a new {@link ISOBUSSocket} connected to the given {@link Bus}, * using the given {@link NAME}, and receiving {@link Message}s with with * one of the given {@link PGN}s. * <p> * If no {@link PGN}s are given, all {@link Message}s are received. * * @param bus * {@link Bus} to which to create a connection * @param name * not yet used * @param pgns * {@link PGN}s to receive, null treated as empty * @throws IOException * when connecting to {@code bus} fails */ public ISOBUSSocket(Bus bus, NAME name, Collection<PGN> pgns) throws IOException { mBus = bus; mName = name; mPgns = pgns == null ? new HashSet<PGN>() : new HashSet<PGN>(pgns); mInMessages = new LinkedBlockingQueue<Message>(); if (!connect()) { throw new IOException("Could not connect to bus: " + mBus); } } protected boolean connect() { return mBus.attach(this); } /** * Writes (sends) the given {@link Message} using this {@link ISOBUSSocket}. * This method may block if there is not room in corresponding the out * buffer. * * @param message * {@link Message} to write * @throws InterruptedException * if interrupted while waiting for buffer space */ public void write(Message message) throws InterruptedException { mBus.passMessageOut(message); } /** * Reads (receives) a {@link Message} that came to this {@link ISOBUSSOcket} * . This method blocks if the in buffer is empty. * * @return a received {@link Message} * @throws InterruptedException * if interrupted while waiting for a {@link Message} * * @see #ISOBUSSocket(Bus, NAME, Collection) */ public Message read() throws InterruptedException, IOException { return mInMessages.take(); } /** * Reads (receives) a {@link Message} that came to this {@link ISOBUSSOcket} * , or {@code null} if the specified waiting time elapses before a * {@link Message} is available * * @param timeout * how long to wait before giving up, in units of {@code unit} * @param unit * a {@link TimeUnit} determining how to interpret the * {@code timeout} parameter * @return a received {link Message} * @throws InterruptedException * if interrupted while waiting for a {@link Message} * * @see #ISOBUSSocket(Bus, NAME, Collection) */ public Message read(long timeout, TimeUnit unit) throws InterruptedException, IOException { return mInMessages.poll(timeout, unit); } protected boolean receive(Message message) { return mInMessages.offer(message); } /* * (non-Javadoc) * * @see java.io.Closeable#close() */ public void close() throws IOException { mBus.detach(this); } /** * Get the {@link Bus} to which this {@link ISOBUSSocket} is connected. * * @return the {@link Bus} */ public Bus getBus() { return mBus; } /** * Get the {@link NAME} used by this {@link ISOBUSSocket}. * * @return the {@link NAME} */ public NAME getName() { return mName; } /** * Get the {@link Set} of {@link PGN}s which this {@link ISOBUSSocket}'s * received {@link Message}s can have. * * @return the {@link Set} of {@link PGN}s */ public Set<PGN> getPgns() { return mPgns; } }
package edu.northwestern.bioinformatics.studycalendar.restlets.representations; import edu.northwestern.bioinformatics.studycalendar.domain.*; import edu.northwestern.bioinformatics.studycalendar.security.authorization.AuthorizationObjectFactory; import edu.northwestern.bioinformatics.studycalendar.security.authorization.PscRole; import edu.northwestern.bioinformatics.studycalendar.security.authorization.PscUser; import edu.northwestern.bioinformatics.studycalendar.service.TemplateService; import edu.northwestern.bioinformatics.studycalendar.service.TestingTemplateService; import edu.northwestern.bioinformatics.studycalendar.service.presenter.UserStudySubjectAssignmentRelationship; import edu.nwu.bioinformatics.commons.DateUtils; import gov.nih.nci.cabig.ctms.lang.DateTools; import gov.nih.nci.cabig.ctms.lang.NowFactory; import gov.nih.nci.cabig.ctms.lang.StaticNowFactory; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import static edu.northwestern.bioinformatics.studycalendar.domain.Fixtures.*; import static edu.northwestern.bioinformatics.studycalendar.security.authorization.AuthorizationScopeMappings.createSuiteRoleMembership; import static gov.nih.nci.cabig.ctms.lang.DateTools.createDate; /** * @author Jalpa Patel */ public class MultipleAssignmentScheduleJsonRepresentationTest extends JsonRepresentationTestCase{ private ScheduledActivity sa; private ScheduledActivityState state; private Activity activity; private List<ActivityProperty> properties; private List<ScheduledActivity> scheduledActivities; private ScheduledCalendar scheduledCalendar = new ScheduledCalendar(); private StringWriter out; private Epoch epoch; private PlannedCalendar calendar; private ScheduledStudySegment scheduledSegment; private Subject subject; private MultipleAssignmentScheduleJsonRepresentation representation; private TemplateService templateService; private JsonGenerator generator; private final Logger log = LoggerFactory.getLogger(getClass()); private PscUser user; private UserStudySubjectAssignmentRelationship rel; private StudySubjectAssignment ssa; private Notification notification; private Population p1; @Override public void setUp() throws Exception { super.setUp(); NowFactory nowFactory = new StaticNowFactory(); templateService = new TestingTemplateService(); Study study = createSingleEpochStudy("S", "Treatment"); Site site = createSite("site"); subject = setGridId("s1", createSubject("First", "Last")); calendar = new PlannedCalendar(); epoch = Epoch.create("Treatment", "A", "B", "C"); epoch.setGridId("E"); calendar.addEpoch(epoch); calendar.setGridId("calendarGridId"); calendar.setId(15); study.setPlannedCalendar(calendar); StudySegment studySegment = createNamedInstance("Screening", StudySegment.class); studySegment.setGridId("S"); studySegment.setId(100); studySegment.setEpoch(epoch); Period p = createPeriod(3, 7, 1); studySegment.addPeriod(p); PlannedActivity pa = createPlannedActivity(activity, 4); p.addPlannedActivity(pa); ssa = createAssignment(study,site,subject); ssa.setStudySubjectId("Study Subject Id"); ssa.setStudySubjectCalendarManager(AuthorizationObjectFactory.createCsmUser(14L, "SammyC")); state = ScheduledActivityMode.SCHEDULED.createStateInstance(); state.setDate(DateTools.createDate(2009, Calendar.APRIL, 3)); state.setReason("Just moved by 4 days"); sa = createScheduledActivity(pa, 2009, Calendar.APRIL, 7, state); sa.setGridId("1111"); sa.setIdealDate(DateTools.createDate(2009, Calendar.APRIL, 7)); sa.setScheduledStudySegment(scheduledSegment); out = new StringWriter(); generator = new JsonFactory().createJsonGenerator(out); ActivityType activityType = createActivityType("Type1"); activity = createActivity("activity1", activityType); properties = new ArrayList<ActivityProperty>(); ActivityProperty prop1 = createActivityProperty("URI", "text", "activity defination"); properties.add(prop1); properties.add(createActivityProperty("URI", "template", "activity uri")); SortedSet<String> labels = new TreeSet<String>(); labels.add("label1"); labels.add("label2"); sa.setLabels(labels); sa.setActivity(activity); scheduledActivities = new ArrayList<ScheduledActivity>(); scheduledActivities.add(sa); scheduledSegment = createScheduledStudySegment(studySegment, DateTools.createDate(2009, Calendar.APRIL, 3)); scheduledSegment.setGridId("GRID-SEG"); scheduledCalendar.addStudySegment(scheduledSegment); scheduledCalendar.setAssignment(setGridId("GRID-ASSIGN", ssa)); sa.setScheduledStudySegment(scheduledSegment); ssa.getScheduledCalendar().addStudySegment(createScheduledStudySegment(createDate(2006, Calendar.APRIL, 1), 365)); user = AuthorizationObjectFactory.createPscUser("jo", createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forAllStudies().forAllSites()); user.getCsmUser().setUserId(11l); ssa.setStudySubjectCalendarManager(user.getCsmUser()); notification = setGridId("n11", new Notification(sa)); ssa.addNotification(notification); p1 = createPopulation("P", "Population"); ssa.addPopulation(p1); ssa.addPopulation(createPopulation("T", "Test")); rel = new UserStudySubjectAssignmentRelationship(user, ssa); representation = new MultipleAssignmentScheduleJsonRepresentation(Arrays.asList(rel), nowFactory, templateService, request.getRootRef()); } public void testStateInfoInJson() throws Exception { MultipleAssignmentScheduleJsonRepresentation.createJSONStateInfo(generator, state); JSONObject stateInfo = outputAsObject(); assertEquals("State mode is different", "scheduled", stateInfo.get("name")); assertEquals("State date is different", "2009-04-03", stateInfo.get("date")); assertEquals("State reason is different", state.getReason(), stateInfo.get("reason")); } public void testStateContainsNoDate() throws Exception { ScheduledActivityState saState = ScheduledActivityMode.CANCELED.createStateInstance(); MultipleAssignmentScheduleJsonRepresentation.createJSONStateInfo(generator, saState); JSONObject stateInfo = outputAsObject(); assertEquals("State mode is different", "canceled", stateInfo.get("name")); assertFalse("State date should not be present", stateInfo.has("date")); } public void testActivityPropertyInJson() throws Exception { ActivityProperty ap = createActivityProperty("URI","text","activity defination"); MultipleAssignmentScheduleJsonRepresentation.createJSONActivityProperty(generator, ap); JSONObject apJson = outputAsObject(); assertEquals("Namespace is different", ap.getNamespace(), apJson.get("namespace")); assertEquals("Name is different", ap.getName(), apJson.get("name")); assertEquals("Value is different", ap.getValue(), apJson.get("value")); } public void testActivityInJson() throws Exception { activity.setProperties(properties); MultipleAssignmentScheduleJsonRepresentation.createJSONActivity(generator, activity); JSONObject activityJson = outputAsObject(); assertEquals("No of elements are different", 3, activityJson.length()); assertEquals("Activity name is different", activity.getName(), activityJson.get("name")); assertEquals("Activity Type is different", activity.getType().getName(), activityJson.get("type")); assertEquals("no of elements is different", 2,((JSONArray)activityJson.get("properties")).length()); } public void testActivityWhenPropertiesAreEmpty() throws Exception { MultipleAssignmentScheduleJsonRepresentation.createJSONActivity(generator, activity); JSONObject activityJson = outputAsObject(); assertEquals("No of elements are different", 2, activityJson.length()); assertTrue(activityJson.isNull("properties")); } public void testScheduledActivityInJson() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject jsonSA = outputAsObject(); assertEquals("Grid Id is different", sa.getGridId(), jsonSA.get("id")); assertEquals("Study is different", sa.getScheduledStudySegment().getStudySegment(). getEpoch().getPlannedCalendar().getStudy().getAssignedIdentifier(), jsonSA.get("study")); assertEquals("Study Segment is different", sa.getScheduledStudySegment().getName(), jsonSA.get("study_segment")); assertEquals("Ideal Date is different", "2009-04-07", jsonSA.get("ideal_date")); assertEquals("Planned day is different", "6", jsonSA.get("plan_day")); } public void testScheduledActivityIncludesAssignmentName() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject jsonSA = outputAsObject(); assertEquals("Missing assignment name", "S" , jsonSA.getJSONObject("assignment").get("name")); } public void testScheduledActivityIncludesAssignmentId() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject jsonSA = outputAsObject(); assertEquals("Missing assignment name", "GRID-ASSIGN", ((JSONObject) jsonSA.get("assignment")).get("id")); } public void testScheduledActivityHasUpdatePrivilege() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject jsonSA = outputAsObject(); assertEquals("Missing update privilege", "update", jsonSA.getJSONObject("assignment").getJSONArray("privileges").get(0)); } public void testScheduledActivityWithoutUpdatePrivilege() throws Exception { user.getMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).notForAllSites().notForAllStudies(); representation.createJSONScheduledActivity(generator, sa); JSONObject jsonSA = outputAsObject(); assertEquals("Should not include update privilege", 0, jsonSA.getJSONObject("assignment").getJSONArray("privileges").length()); } public void testScheduledActivityCurrentState() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject jsonSA = outputAsObject(); JSONObject currentState = (JSONObject) jsonSA.get("current_state"); assertNotNull("current state is missing", currentState); assertEquals("current state reason incorrect", "Just moved by 4 days", currentState.get("reason")); assertEquals("current state date incorrect", "2009-04-03", currentState.get("date")); assertEquals("current state name incorrect", "scheduled", currentState.get("name")); } public void testScheduledActivityStateHistoryContainsAllStates() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject actual = outputAsObject(); JSONArray history = actual.getJSONArray("state_history"); assertEquals(2, history.length()); } public void testScheduledActivityStateHistoryStartsWithInitial() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject actual = outputAsObject(); JSONArray history = actual.getJSONArray("state_history"); JSONObject first = (JSONObject) history.get(0); assertEquals("Incorrect date", "2009-04-07", first.get("date")); } public void testScheduledActivityStateHistoryEndsWithCurrent() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject actual = outputAsObject(); JSONArray history = actual.getJSONArray("state_history"); JSONObject first = (JSONObject) history.get(1); assertEquals("Incorrect date", "2009-04-03", first.get("date")); } public void testWithHiddenActivities() throws Exception { representation.createJSONScheduledActivities(generator, true, scheduledActivities); JSONObject jsonScheduleActivities = outputAsObject(); assertTrue("has no hidden activities", Boolean.valueOf(jsonScheduleActivities.getString("hidden_activities"))); } public void testWhenHiddenActivitiesIsNull() throws Exception { representation.createJSONScheduledActivities(generator, null, scheduledActivities); JSONObject jsonScheduleActivities = outputAsObject(); assertTrue(jsonScheduleActivities.isNull("hidden_activities")); assertEquals("no of elements is different", 1, jsonScheduleActivities.length()); } public void testScheduledStudySegmentsInJson() throws Exception { representation.createJSONStudySegment(generator, scheduledSegment); JSONObject jsonSegment = outputAsObject(); assertEquals("has different name", scheduledSegment.getName(), jsonSegment.get("name")); assertEquals("missing ID", scheduledSegment.getGridId(), jsonSegment.get("id")); JSONObject jsonRange = (JSONObject)(jsonSegment.get("range")); assertEquals("different start date", "2009-04-03", jsonRange.get("start_date")); assertEquals("different stop date", "2009-04-09", jsonRange.get("stop_date")); JSONObject jsonPlannedSegmentInfo = (JSONObject)(jsonSegment.get("planned")); JSONObject jsonPlannedSegment = (JSONObject)(jsonPlannedSegmentInfo.get("segment")); assertEquals("segment has different name", scheduledSegment.getStudySegment().getName(), jsonPlannedSegment.get("name")); assertEquals("segment has different id", "S", jsonPlannedSegment.get("id")); JSONObject jsonEpoch = (JSONObject)(jsonPlannedSegmentInfo.get("epoch")); assertEquals("Epoch has different name", scheduledSegment.getStudySegment().getEpoch().getName(), jsonEpoch.get("name")); assertEquals("Epoch has different id", "E", jsonEpoch.get("id")); JSONObject jsonStudy = (JSONObject)(jsonPlannedSegmentInfo.get("study")); assertEquals("Study doesn't match", scheduledSegment.getStudySegment().getEpoch().getPlannedCalendar() .getStudy().getAssignedIdentifier(), jsonStudy.get("assigned_identifier")); } public void testScheduledSegmentIncludesAssignmentName() throws Exception { representation.createJSONStudySegment(generator, scheduledSegment); JSONObject actual = outputAsObject(); assertEquals("Missing assignment name", "Treatment: Screening", actual.get("name")); } public void testCreateJSONStudySegment() throws Exception { representation.createJSONStudySegment(generator, scheduledSegment); JSONObject actual = outputAsObject(); assertTrue("Missing properties", actual.has("id")); assertTrue("Missing properties", actual.has("name")); } public void testScheduledSegmentIncludesAssignmentId() throws Exception { representation.createJSONStudySegment(generator, scheduledSegment); JSONObject actual = outputAsObject(); assertEquals("Missing assignment id", "GRID-ASSIGN", ((JSONObject) actual.get("assignment")).get("id")); } public void testDetailsInJson() throws Exception { sa.setDetails("Detail"); representation.createJSONScheduledActivity(generator, sa); JSONObject actual = outputAsObject(); assertEquals("Missing details", "Detail", actual.get("details")); } public void testMissingDetailsInJson() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject actual = outputAsObject(); assertTrue(actual.isNull("details")); } public void testStudySubjectIdInJson() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject actual = outputAsObject(); assertEquals("Missing study subject id", "Study Subject Id", actual.get("study_subject_id")); } public void testConditionalInJson() throws Exception { sa.getPlannedActivity().setCondition("Conditional Details"); representation.createJSONScheduledActivity(generator, sa); JSONObject actual = outputAsObject(); assertEquals("Missing conditions", "Conditional Details", actual.get("condition")); } public void testLabelsInJson() throws Exception { representation.createJSONScheduledActivity(generator, sa); JSONObject actual = outputAsObject(); assertEquals("Missing labels", "label1 label2", actual.get("labels")); } public void testSubjectInfoInJson() throws Exception { subject.setDateOfBirth(DateUtils.createDate(1978, Calendar.MARCH, 15)); subject.setGender(Gender.FEMALE); representation.createJSONSubject(generator, subject); JSONObject actual = outputAsObject(); assertEquals("Missing first", subject.getFirstName(), actual.get("first_name")); assertEquals("Missing last", subject.getLastName(), actual.get("last_name")); assertEquals("Missing full", subject.getFullName(), actual.get("full_name")); assertEquals("Missing last-first", subject.getLastFirst(), actual.get("last_first")); assertEquals("Missing DOB", "1978-03-15", actual.get("birth_date")); assertEquals("Missing gender", "Female", actual.get("gender")); } public void testSubjectInfoStillGeneratedIfSubjectHasNoGender() throws Exception { subject.setGender(null); representation.createJSONSubject(generator, subject); JSONObject jsonSubj = outputAsObject(); // expect no error, plus: assertFalse("Should have no gender", jsonSubj.has("gender")); } public void testSubjectPropertiesIncludedInJson() throws Exception { subject.getProperties().add(new SubjectProperty("Cube root", "9")); representation.createJSONSubject(generator, subject); JSONObject actual = outputAsObject(); assertTrue("No properties", actual.has("properties")); assertEquals("Wrong number of properties", 1, actual.getJSONArray("properties").length()); } public void testStudySubjectAssignmentInJson() throws Exception { representation.createJSONStudySubjectAssignment(generator, rel); JSONObject actual = outputAsObject(); assertEquals("Missing id", ssa.getGridId(), actual.get("id")); assertEquals("Missing name", ssa.getName(), actual.get("name")); assertTrue("No privileges", actual.has("privileges")); JSONArray privileges = actual.getJSONArray("privileges"); assertEquals("Wrong number of privilege", 3, actual.getJSONArray("privileges").length()); assertEquals("Missing first priv", "visible", privileges.get(0)); assertEquals("Missing second priv", "update-schedule", privileges.get(1)); assertEquals("Missing third priv", "calendar-manager", privileges.get(2)); assertTrue("No notifications", actual.has("notifications")); assertEquals("Wrong number of notifications", 1, actual.getJSONArray("notifications").length()); assertTrue("No populations", actual.has("populations")); assertEquals("Wrong number of populations", 2, actual.getJSONArray("populations").length()); JSONObject actualPopulation = (JSONObject) actual.getJSONArray("populations").get(0); assertTrue("Missing name", actualPopulation.has("name")); assertTrue("Missing abbreviation", actualPopulation.has("abbreviation")); } public void testAssignmentNotification() throws Exception { representation.createJSONNotification(generator, notification); JSONObject actual = outputAsObject(); assertEquals("Missing message", notification.getMessage(), actual.get("message")); assertEquals("Missing title", notification.getTitle(), actual.get("title")); assertEquals("Missing href", "http://trials.etc.edu/studycalendar/api/v1/subjects/s1/assignments/GRID-ASSIGN/notifications/n11" , actual.get("href")); } private JSONObject outputAsObject() throws IOException { generator.close(); try { return new JSONObject(out.toString()); } catch (JSONException e) { log.info("Generated JSON: {}", out.toString()); fail("Generated JSON is not valid: " + e.getMessage()); return null; // Unreachable } } }
package org.xwiki.test.docker.junit5.servletengine; /** * The Servlet Engine to use for the UI tests. * * @version $Id$ * @since 10.9 */ public enum ServletEngine { /** * Represents the Tomcat Servlet engine. */ TOMCAT("tomcat"), /** * Represents the Jetty Servlet engine (running inside Docker). */ JETTY("jetty"), /** * Represents the Jetty Servlet engine but running outside of Docker. */ JETTY_STANDALONE, /** * Represents the JBoss Wildfly engine. */ WILDFLY("jboss/wildfly"), /** * Represents an external Servlet Engine already configured and running (we won't start or stop it). */ EXTERNAL; private static final String LOCALHOST = "localhost"; private static final String HOST_INTERNAL = "host.testcontainers.internal"; private boolean isOutsideDocker; private String ip; private int port; private String dockerImageName; /** * Constructor for a Servlet Engine using a Docker image. This image must be available on DockerHub. * @param dockerImageName the name of the docker image to use. */ ServletEngine(String dockerImageName) { this.dockerImageName = dockerImageName; } /** * Constructor for an external ServletEngine: in that case, it is running outside docker. */ ServletEngine() { this.isOutsideDocker = true; } /** * @return true if the Servlet engine is meant to be running on the host and not in a Docker container */ public boolean isOutsideDocker() { return this.isOutsideDocker; } /** * @param ip see {@link #getIP()} * @since 10.11RC1 */ public void setIP(String ip) { this.ip = ip; } /** * @return the IP address to use to connect to the Servlet Engine from the outside (it is different if it runs * locally or in a Docker container). * @since 10.11RC1 */ public String getIP() { return this.ip; } /** * @param port see {@link #getPort()} * @since 10.11RC1 */ public void setPort(int port) { this.port = port; } /** * @return the port to use to connect to the Servlet Engine from the outside (it is different if it runs locally or * in a Docker container) * @since 10.11RC1 */ public int getPort() { return this.port; } /** * @return the IP to the host from inside the Servlet Engine * @since 10.11RC1 */ public String getHostIP() { return isOutsideDocker() ? LOCALHOST : HOST_INTERNAL; } /** * @return the IP of the container from inside itself (it is different if it runs locally or in a Docker container) * @since 10.11RC1 */ public String getInternalIP() { return isOutsideDocker ? HOST_INTERNAL : "xwikiweb"; } /** * @return the port of the container from inside itself (it is different if it runs locally or in a Docker * container) * @since 10.11RC1 */ public int getInternalPort() { return 8080; } /** * @return the location of the XWiki permanent directory inside the Docker container for the Servlet Engine. * @since 10.11RC1 */ public String getPermanentDirectory() { if (name().equals("JETTY")) { return "/var/lib/jetty/xwiki-data"; } else if (name().equals("TOMCAT")) { return "/usr/local/tomcat/xwiki-data"; } else if (name().equals("WILDFLY")){ return "/opt/jboss/xwiki-data"; } else { throw new RuntimeException(String.format("Permanent directory not supported for [%s]", name())); } } /** * @return the Docker image name for this Servlet Engine. This image must be available on DockerHub. * @since 10.11RC1 */ public String getDockerImageName() { return dockerImageName; } }
// modification, are permitted provided that the following conditions are met: // and/or other materials provided with the distribution. // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. package br.com.carlosrafaelgn.fplay.ui; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.UiModeManager; import android.content.Context; import android.content.DialogInterface; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.InputType; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Display; import android.view.Gravity; import android.view.KeyEvent; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewParent; import android.view.Window; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Interpolator; import android.widget.AbsListView; import android.widget.BgEdgeEffect; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.DecimalFormatSymbols; import java.util.Locale; import br.com.carlosrafaelgn.fplay.ActivityBrowserView; import br.com.carlosrafaelgn.fplay.ActivityItemView; import br.com.carlosrafaelgn.fplay.R; import br.com.carlosrafaelgn.fplay.activity.ActivityHost; import br.com.carlosrafaelgn.fplay.playback.Player; import br.com.carlosrafaelgn.fplay.ui.drawable.BorderDrawable; import br.com.carlosrafaelgn.fplay.ui.drawable.ColorDrawable; import br.com.carlosrafaelgn.fplay.ui.drawable.ScrollBarThumbDrawable; import br.com.carlosrafaelgn.fplay.util.ColorUtils; import br.com.carlosrafaelgn.fplay.util.SerializableMap; //Unit conversions are based on: public final class UI implements DialogInterface.OnShowListener, Animation.AnimationListener, Interpolator { //VERSION_CODE must be kept in sync with AndroidManifest.xml public static final int VERSION_CODE = 87; //VERSION_NAME must be kept in sync with AndroidManifest.xml public static final String VERSION_NAME = "v1.52"; public static final int STATE_PRESSED = 1; public static final int STATE_FOCUSED = 2; public static final int STATE_CURRENT = 4; public static final int STATE_SELECTED = 8; public static final int STATE_MULTISELECTED = 16; public static final int LOCALE_NONE = 0; public static final int LOCALE_US = 1; public static final int LOCALE_PTBR = 2; public static final int LOCALE_RU = 3; public static final int LOCALE_UK = 4; public static final int LOCALE_ES = 5; public static final int LOCALE_DE = 6; public static final int LOCALE_FR = 7; public static final int LOCALE_MAX = 7; public static final int THEME_CUSTOM = -1; public static final int THEME_BLUE_ORANGE = 0; public static final int THEME_BLUE = 1; public static final int THEME_ORANGE = 2; public static final int THEME_LIGHT = 4; public static final int THEME_DARK_LIGHT = 5; public static final int THEME_CREAMY = 6; public static final int THEME_FPLAY = 7; //present the new FPlay Dark theme to all those using FPlay theme ;) public static final int THEME_FPLAY_DARK = 3; public static final int TRANSITION_NONE = 0; public static final int TRANSITION_FADE = 1; public static final int TRANSITION_ZOOM = 2; public static final int TRANSITION_DISSOLVE = 3; public static final int TRANSITION_SLIDE = 4; public static final int TRANSITION_SLIDE_SMOOTH = 5; public static final int TRANSITION_DURATION_FOR_ACTIVITIES_SLOW = 300; public static final int TRANSITION_DURATION_FOR_ACTIVITIES = 200; //used to be 300 public static final int TRANSITION_DURATION_FOR_VIEWS = 200; //used to be 300 public static final int MSG_ADD = 0x0001; public static final int MSG_PLAY = 0x0002; public static final String ICON_PREV = "<"; public static final String ICON_PLAY = "P"; public static final String ICON_PAUSE = "|"; public static final String ICON_NEXT = ">"; public static final String ICON_MENU = "N"; public static final String ICON_LIST = "l"; public static final String ICON_MOVE = "M"; public static final String ICON_REMOVE = "R"; public static final String ICON_UP = "^"; public static final String ICON_GOBACK = "_"; public static final String ICON_SAVE = "S"; public static final String ICON_LOAD = "L"; public static final String ICON_FAVORITE_ON = " public static final String ICON_FAVORITE_OFF = "*"; public static final String ICON_ADD = "A"; public static final String ICON_HOME = "H"; public static final String ICON_LINK = "U"; public static final String ICON_EQUALIZER = "E"; public static final String ICON_SETTINGS = "s"; public static final String ICON_VISUALIZER = "V"; public static final String ICON_EXIT = "X"; public static final String ICON_VOLUME0 = "0"; public static final String ICON_VOLUME1 = "1"; public static final String ICON_VOLUME2 = "2"; public static final String ICON_VOLUME3 = "3"; public static final String ICON_VOLUME4 = "4"; public static final String ICON_DECREASE_VOLUME = "-"; public static final String ICON_INCREASE_VOLUME = "+"; public static final String ICON_SEARCH = "F"; public static final String ICON_INFORMATION = "I"; public static final String ICON_QUESTION = "?"; public static final String ICON_EXCLAMATION = "!"; public static final String ICON_SHUFFLE = "h"; public static final String ICON_REPEAT = "t"; public static final String ICON_DELETE = "D"; public static final String ICON_RADIOCHK = "x"; public static final String ICON_RADIOUNCHK = "o"; public static final String ICON_OPTCHK = "q"; public static final String ICON_OPTUNCHK = "Q"; public static final String ICON_GRIP = "G"; public static final String ICON_FPLAY = "7"; public static final String ICON_SLIDERTOP = "\""; public static final String ICON_SLIDERBOTTOM = "\'"; public static final String ICON_RIGHT = "6"; public static final String ICON_FADE = ";"; public static final String ICON_DIAL = ":"; public static final String ICON_HEADSET = "{"; public static final String ICON_TRANSPARENT = "}"; public static final String ICON_FLAT = "/"; public static final String ICON_PALETTE = "["; public static final String ICON_LANGUAGE = "]"; public static final String ICON_THEME = "\\"; public static final String ICON_SPACELIST = "="; public static final String ICON_SPACEHEADER = "~"; public static final String ICON_ORIENTATION = "@"; public static final String ICON_DYSLEXIA = "$"; public static final String ICON_SCREEN = "`"; public static final String ICON_CLOCK = "."; public static final String ICON_DIVIDER = ","; public static final String ICON_MIC = "m"; public static final String ICON_ALBUMART = "B"; public static final String ICON_ALBUMART_OFF = "b"; public static final String ICON_BLUETOOTH = "W"; public static final String ICON_RADIO = "w"; public static final String ICON_HAND = "a"; public static final String ICON_SCROLLBAR = "c"; public static final String ICON_SD = "d"; public static final String ICON_FOLDER = "f"; public static final String ICON_USB = "u"; public static final String ICON_SEEKBAR = "5"; public static final String ICON_TRANSITION = "%"; public static final String ICON_REPEATONE = "y"; public static final String ICON_ROOT = "("; public static final String ICON_3DPAN = ")"; public static final String ICON_REPEATNONE = "Y"; public static final String ICON_HEADSETHOOK1 = "i"; public static final String ICON_HEADSETHOOK2 = "j"; public static final String ICON_HEADSETHOOK3 = "k"; public static final String ICON_ICECAST = "K"; public static final String ICON_ICECASTTEXT = "O"; //height = 3.587 / 16 public static final String ICON_SHOUTCAST = "J"; public static final String ICON_SHOUTCASTTEXT = "T"; //height = 2.279 / 16 public static final int KEY_UP = KeyEvent.KEYCODE_DPAD_UP; public static final int KEY_DOWN = KeyEvent.KEYCODE_DPAD_DOWN; public static final int KEY_LEFT = KeyEvent.KEYCODE_DPAD_LEFT; public static final int KEY_RIGHT = KeyEvent.KEYCODE_DPAD_RIGHT; public static final int KEY_ENTER = KeyEvent.KEYCODE_DPAD_CENTER; public static final int KEY_DEL = KeyEvent.KEYCODE_FORWARD_DEL; public static final int KEY_EXTRA = KeyEvent.KEYCODE_SPACE; public static final int KEY_HOME = KeyEvent.KEYCODE_MOVE_HOME; public static final int KEY_END = KeyEvent.KEYCODE_MOVE_END; public static final int KEY_PAGE_UP = KeyEvent.KEYCODE_PAGE_UP; public static final int KEY_PAGE_DOWN = KeyEvent.KEYCODE_PAGE_DOWN; public static final int IDX_COLOR_WINDOW = 0; public static final int IDX_COLOR_CONTROL_MODE = 1; public static final int IDX_COLOR_VISUALIZER = 2; public static final int IDX_COLOR_LIST = 3; public static final int IDX_COLOR_MENU = 4; public static final int IDX_COLOR_MENU_ICON = 5; public static final int IDX_COLOR_MENU_BORDER = 6; public static final int IDX_COLOR_DIVIDER = 7; public static final int IDX_COLOR_HIGHLIGHT = 8; public static final int IDX_COLOR_TEXT_HIGHLIGHT = 9; public static final int IDX_COLOR_TEXT = 10; public static final int IDX_COLOR_TEXT_DISABLED = 11; public static final int IDX_COLOR_TEXT_LISTITEM = 12; public static final int IDX_COLOR_TEXT_LISTITEM_SECONDARY = 13; public static final int IDX_COLOR_TEXT_SELECTED = 14; public static final int IDX_COLOR_TEXT_MENU = 15; public static final int IDX_COLOR_SELECTED_GRAD_LT = 16; public static final int IDX_COLOR_SELECTED_GRAD_DK = 17; public static final int IDX_COLOR_SELECTED_BORDER = 18; public static final int IDX_COLOR_SELECTED_PRESSED = 19; public static final int IDX_COLOR_FOCUSED_GRAD_LT = 20; public static final int IDX_COLOR_FOCUSED_GRAD_DK = 21; public static final int IDX_COLOR_FOCUSED_BORDER = 22; public static final int IDX_COLOR_FOCUSED_PRESSED = 23; public static final int PLACEMENT_WINDOW = 0; public static final int PLACEMENT_MENU = 1; public static final int PLACEMENT_ALERT = 2; //keep in sync with v21/styles.xml public static final int color_dialog_fplay_dk = 0xff444abf; public static final int color_dialog_fplay_lt = 0xff9ea6ff; public static final int color_dialog_text_dk = 0xff1f1f1f; public static final int color_dialog_text_lt = 0xffffffff; public static final int color_dialog_normal_dk = 0xff6d6d6d; public static final int color_dialog_normal_lt = 0xffc7c7c7; public static int color_window; public static int color_control_mode; public static int color_visualizer, color_visualizer565; public static int color_list; public static int color_list_bg; public static int color_list_original; public static int color_list_shadow; public static int color_menu; public static int color_menu_icon; public static int color_menu_border; public static int color_divider; public static int color_divider_pressed; public static int color_highlight; public static int color_text_highlight; public static int color_text; public static int color_text_disabled; public static int color_text_listitem; public static int color_text_listitem_secondary; public static int color_text_selected; public static int color_text_menu; public static int color_text_title; public static int color_selected; public static int color_selected_multi; public static int color_selected_grad_lt; public static int color_selected_grad_dk; public static int color_selected_border; public static int color_selected_pressed; public static int color_selected_pressed_border; public static int color_focused; public static int color_focused_grad_lt; public static int color_focused_grad_dk; public static int color_focused_border; public static int color_focused_pressed; public static int color_focused_pressed_border; public static int color_glow; public static BgColorStateList colorState_text_white_reactive; public static BgColorStateList colorState_text_menu_reactive; public static BgColorStateList colorState_text_reactive; public static BgColorStateList colorState_text_static; public static BgColorStateList colorState_text_listitem_static; public static BgColorStateList colorState_text_listitem_reactive; public static BgColorStateList colorState_text_listitem_secondary_static; public static BgColorStateList colorState_text_selected_static; public static BgColorStateList colorState_text_title_static; public static BgColorStateList colorState_highlight_static; public static BgColorStateList colorState_text_highlight_static; public static BgColorStateList colorState_text_highlight_reactive; public static BgColorStateList colorState_text_control_mode_reactive; public static BgColorStateList colorState_text_visualizer_static; public static BgColorStateList colorState_text_visualizer_reactive; public static Typeface iconsTypeface, defaultTypeface; public static final class DisplayInfo { public int usableScreenWidth, usableScreenHeight, screenWidth, screenHeight; public boolean isLandscape, isLargeScreen, isLowDpiScreen; public DisplayMetrics displayMetrics; private void initializeScreenDimensions(Display display, DisplayMetrics outDisplayMetrics) { display.getMetrics(outDisplayMetrics); screenWidth = outDisplayMetrics.widthPixels; screenHeight = outDisplayMetrics.heightPixels; usableScreenWidth = screenWidth; usableScreenHeight = screenHeight; } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void initializeScreenDimensions14(Display display, DisplayMetrics outDisplayMetrics) { try { screenWidth = (Integer)Display.class.getMethod("getRawWidth").invoke(display); screenHeight = (Integer)Display.class.getMethod("getRawHeight").invoke(display); } catch (Throwable ex) { initializeScreenDimensions(display, outDisplayMetrics); return; } display.getMetrics(outDisplayMetrics); usableScreenWidth = outDisplayMetrics.widthPixels; usableScreenHeight = outDisplayMetrics.heightPixels; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private void initializeScreenDimensions17(Display display, DisplayMetrics outDisplayMetrics) { display.getMetrics(outDisplayMetrics); usableScreenWidth = outDisplayMetrics.widthPixels; usableScreenHeight = outDisplayMetrics.heightPixels; display.getRealMetrics(outDisplayMetrics); screenWidth = outDisplayMetrics.widthPixels; screenHeight = outDisplayMetrics.heightPixels; } public void getInfo() { final Display display = ((WindowManager)Player.theApplication.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); displayMetrics = new DisplayMetrics(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) initializeScreenDimensions17(display, displayMetrics); else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) initializeScreenDimensions14(display, displayMetrics); else initializeScreenDimensions(display, displayMetrics); //improved detection for tablets, based on: //http://developer.android.com/guide/practices/screens_support.html#DeclaringTabletLayouts //but the former link says it is deprecated...) /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { edgeEffect = (EdgeEffect)mEdgeGlow.get(view); if (edgeEffect == null) { edgeEffect = new EdgeEffect(context); mEdgeGlow.set(view, edgeEffect); } edgeEffect.setColor(color); } else*/ { mEdgeGlow.set(view, new BgEdgeEffect(Player.theApplication, color)); } } mEdgeGlow = clazz.getDeclaredField("mEdgeGlowBottom"); if (mEdgeGlow != null) { ok = true; mEdgeGlow.setAccessible(true); /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { edgeEffect = (EdgeEffect)mEdgeGlow.get(view); if (edgeEffect == null) { edgeEffect = new EdgeEffect(context); mEdgeGlow.set(view, edgeEffect); } edgeEffect.setColor(color); } else*/ { mEdgeGlow.set(view, new BgEdgeEffect(Player.theApplication, color)); } } if (ok || Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) return; } } catch (Throwable ex) { ex.printStackTrace(); } } try { //if everything else fails, fall back to the old method! final int color = (placement == PLACEMENT_ALERT ? (isAndroidThemeLight() ? 0xff000000 : 0xffffffff) : (placement == PLACEMENT_MENU ? color_menu_icon : color_glow)); if (glowFilter == null || glowFilterColor != color) { glowFilterColor = color; glowFilter = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN); } //:D amazing hack/workaround, as explained here: Drawable drawable = Player.theApplication.getResources().getDrawable(Player.theApplication.getResources().getIdentifier("overscroll_glow", "drawable", "android")); if (drawable != null) //the color is treated as SRC, and the bitmap is treated as DST drawable.setColorFilter(glowFilter); drawable = Player.theApplication.getResources().getDrawable(Player.theApplication.getResources().getIdentifier("overscroll_edge", "drawable", "android")); if (drawable != null) //hide the edge!!! ;) drawable.setColorFilter(glowFilter);//edgeFilter); } catch (Throwable ex) { ex.printStackTrace(); } } @SuppressWarnings("deprecation") public static void offsetTopEdgeEffect(View view) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { try { if (glowFilter == null) { final Field mEdgeGlow = ((view instanceof ScrollView) ? ScrollView.class : AbsListView.class).getDeclaredField("mEdgeGlowTop"); if (mEdgeGlow != null) { mEdgeGlow.setAccessible(true); final BgEdgeEffect edgeEffect = (BgEdgeEffect)mEdgeGlow.get(view); if (edgeEffect != null) edgeEffect.mOffsetY = thickDividerSize; } } } catch (Throwable ex) { ex.printStackTrace(); } } } @SuppressWarnings("deprecation") public static void disableEdgeEffect() { if (glowFilter == null) return; try { Drawable drawable = Player.theApplication.getResources().getDrawable(Player.theApplication.getResources().getIdentifier("overscroll_glow", "drawable", "android")); if (drawable != null) drawable.setColorFilter(null); drawable = Player.theApplication.getResources().getDrawable(Player.theApplication.getResources().getIdentifier("overscroll_edge", "drawable", "android")); if (drawable != null) drawable.setColorFilter(null); } catch (Throwable ex) { ex.printStackTrace(); } } @SuppressWarnings("deprecation") public static void reenableEdgeEffect(Context context) { if (glowFilter == null) return; try { Drawable drawable = context.getResources().getDrawable(context.getResources().getIdentifier("overscroll_glow", "drawable", "android")); if (drawable != null) drawable.setColorFilter(glowFilter); drawable = context.getResources().getDrawable(context.getResources().getIdentifier("overscroll_edge", "drawable", "android")); if (drawable != null) drawable.setColorFilter(glowFilter);//edgeFilter); } catch (Throwable ex) { ex.printStackTrace(); } } @SuppressWarnings("deprecation") public static void prepareControlContainer(View view, boolean topBorder, boolean bottomBorder) { final int t = (topBorder ? thickDividerSize : 0); final int b = (bottomBorder ? thickDividerSize : 0); view.setBackgroundDrawable(new BorderDrawable(color_highlight, color_window, 0, t, 0, b)); if (extraSpacing) view.setPadding(controlMargin, controlMargin + t, controlMargin, controlMargin + b); else view.setPadding(0, t, 0, b); } @SuppressWarnings("deprecation") public static void prepareControlContainerWithoutRightPadding(View view, boolean topBorder, boolean bottomBorder) { final int t = (topBorder ? thickDividerSize : 0); final int b = (bottomBorder ? thickDividerSize : 0); view.setBackgroundDrawable(new BorderDrawable(color_highlight, color_window, 0, t, 0, b)); if (extraSpacing) view.setPadding(controlMargin, controlMargin + t, 0, controlMargin + b); else view.setPadding(0, t, 0, b); } public static void tryToChangeScrollBarThumb(View view, int color) { //this is not a simple workaround... it could be the mother of all workarounds out there! :) try { final Field mScrollCacheField = View.class.getDeclaredField("mScrollCache"); mScrollCacheField.setAccessible(true); final Object mScrollCache = mScrollCacheField.get(view); final Field scrollBarField = mScrollCache.getClass().getDeclaredField("scrollBar"); scrollBarField.setAccessible(true); final Object scrollBar = scrollBarField.get(mScrollCache); final Method method = scrollBar.getClass().getDeclaredMethod("setVerticalThumbDrawable", Drawable.class); method.setAccessible(true); //finally!!! method.invoke(scrollBar, new ScrollBarThumbDrawable(color)); } catch (Throwable ex) { //well... apparently it did not work out as expected } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static void removeSplitTouch(ViewGroup viewGroup) { viewGroup.setMotionEventSplittingEnabled(false); } public static void announceAccessibilityText(CharSequence text) { if (accessibilityManager != null && accessibilityManager.isEnabled()) { final AccessibilityEvent e = AccessibilityEvent.obtain(); //I couldn't make AccessibilityEvent.TYPE_ANNOUNCEMENT work... even on Android 16+ e.setEventType(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); e.setClassName("br.com.carlosrafaelgn.fplay.activity.ActivityHost"); e.setPackageName("br.com.carlosrafaelgn.fplay"); e.getText().add(text); accessibilityManager.sendAccessibilityEvent(e); } } private static final int ANIMATION_STATE_NONE = 0; private static final int ANIMATION_STATE_HIDING = 1; private static final int ANIMATION_STATE_SHOWING = 2; public static boolean animationEnabled; private static View animationFocusView; private static int animationHideCount, animationShowCount, animationState; private static View animationViewToShowFirst; private static View[] animationViewsToHideAndShow; private static FastAnimator animationAnimatorShowFirst, animationAnimatorHide, animationAnimatorShow; private static Animation animationShowFirst, animationHide, animationShow; public static Runnable animationFinishedObserver; @Override public float getInterpolation(float input) { //making UI implement Interpolator saves us one class and one instance ;) //faster version of AccelerateDecelerateInterpolator using this sine approximation: //we use the result of sin in the range -PI/2 to PI/2 //input = (input * 3.14159265f) - 1.57079632f; //return 0.5f + (0.5f * ((1.27323954f * input) - (0.40528473f * input * (input < 0.0f ? -input : input)))); //even faster version! using the Hermite interpolation (GLSL's smoothstep) return (input * input * (3.0f - (2.0f * input))); } public static Animation animationCreateAlpha(float fromAlpha, float toAlpha) { final Animation animation = new AlphaAnimation(fromAlpha, toAlpha); animation.setDuration(TRANSITION_DURATION_FOR_VIEWS); animation.setInterpolator(Player.theUI); animation.setRepeatCount(0); animation.setFillAfter(false); return animation; } private static void animationFinished(boolean abortAll) { boolean finished = (abortAll || (animationState == ANIMATION_STATE_SHOWING) || (animationShow == null && animationAnimatorShow == null)); if (animationHideCount > 0 || animationShowCount > 0 || animationViewToShowFirst != null) { if (abortAll) { animationState = ANIMATION_STATE_NONE; if (animationShowFirst != null) animationShowFirst.cancel(); if (animationAnimatorShowFirst != null) animationAnimatorShowFirst.end(); if (animationHide != null) animationHide.cancel(); if (animationAnimatorHide != null) animationAnimatorHide.end(); if (animationShow != null) animationShow.cancel(); if (animationAnimatorShow != null) animationAnimatorShow.end(); } if (abortAll || animationState == ANIMATION_STATE_HIDING) { for (int i = 0; i < animationHideCount; i++) { final View view = animationViewsToHideAndShow[i]; if (view != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) view.setAnimation(null); view.setVisibility(View.GONE); animationViewsToHideAndShow[i] = null; } } animationHideCount = 0; if (animationViewToShowFirst != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) animationViewToShowFirst.setAnimation(null); animationViewToShowFirst = null; } } if (!finished) { finished = true; animationState = ANIMATION_STATE_SHOWING; for (int i = 0; i < animationShowCount; i++) { final View view = animationViewsToHideAndShow[16 + i]; if (view != null) { if (view.getVisibility() != View.VISIBLE) { finished = false; final Object tag; if ((tag = view.getTag()) != null && tag instanceof CharSequence && view instanceof TextView) { view.setTag(null); ((TextView)view).setText((CharSequence)tag); } view.setVisibility(View.VISIBLE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) view.startAnimation(animationShow); else view.setAlpha(0.0f); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { animationViewsToHideAndShow[16 + i] = null; view.setAlpha(1.0f); } } } if (!finished && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) animationAnimatorShow.start(); } if (finished) { animationState = ANIMATION_STATE_NONE; for (int i = 0; i < animationShowCount; i++) { final View view = animationViewsToHideAndShow[16 + i]; if (view != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) view.setAnimation(null); else view.setAlpha(1.0f); if (abortAll && view.getVisibility() != View.VISIBLE) { final Object tag; if ((tag = view.getTag()) != null && tag instanceof CharSequence && view instanceof TextView) { view.setTag(null); ((TextView)view).setText((CharSequence)tag); } view.setVisibility(View.VISIBLE); } animationViewsToHideAndShow[i] = null; } } animationShowCount = 0; } } if (animationFocusView != null && finished) { if (animationFocusView.isInTouchMode()) animationFocusView.requestFocus(); animationFocusView = null; } if (animationFinishedObserver != null) { animationFinishedObserver.run(); animationFinishedObserver = null; } } public static void animationAddViewToHide(View view) { if (animationViewsToHideAndShow == null) animationViewsToHideAndShow = new View[32]; else if (animationHideCount >= 16 && view != null && view.getVisibility() != View.GONE) return; animationViewsToHideAndShow[animationHideCount] = view; animationHideCount++; } public static void animationAddViewToShow(View view) { if (animationViewsToHideAndShow == null) animationViewsToHideAndShow = new View[32]; else if (animationShowCount >= 16 && view != null && view.getVisibility() != View.VISIBLE) return; animationViewsToHideAndShow[16 + animationShowCount] = view; animationShowCount++; } public static void animationSetViewToShowFirst(View view) { animationViewToShowFirst = view; } public static void animationReset() { animationFinished(true); } //DO NOT CALL THIS WITH forceSkipAnimation = false IF ANY VIEWS ARE NOT YET ATTACHED TO A WINDOW!!! public static void animationCommit(boolean forceSkipAnimation, View focusView) { if (!animationEnabled || forceSkipAnimation) { for (int i = 0; i < animationHideCount; i++) { final View view = animationViewsToHideAndShow[i]; if (view != null) { view.setVisibility(View.GONE); animationViewsToHideAndShow[i] = null; } } for (int i = 0; i < animationShowCount; i++) { final View view = animationViewsToHideAndShow[16 + i]; if (view != null) { final Object tag; if ((tag = view.getTag()) != null && tag instanceof CharSequence && view instanceof TextView) { view.setTag(null); ((TextView)view).setText((CharSequence)tag); } view.setVisibility(View.VISIBLE); animationViewsToHideAndShow[16 + i] = null; } } if (focusView != null && focusView.isInTouchMode()) focusView.requestFocus(); animationState = ANIMATION_STATE_NONE; animationHideCount = 0; animationShowCount = 0; animationViewToShowFirst = null; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { animationCommit11(focusView); } else { if (animationShowFirst == null) { (animationShowFirst = animationCreateAlpha(0.0f, 1.0f)).setAnimationListener(Player.theUI); (animationHide = animationCreateAlpha(1.0f, 0.0f)).setAnimationListener(Player.theUI); (animationShow = animationCreateAlpha(0.0f, 1.0f)).setAnimationListener(Player.theUI); } else { animationShowFirst.reset(); animationHide.reset(); animationShow.reset(); } if (animationHideCount > 0 || animationShowCount > 0 || animationViewToShowFirst != null) { animationState = ANIMATION_STATE_HIDING; animationFocusView = focusView; boolean ok = false; if (animationViewToShowFirst != null) { ok = true; animationViewToShowFirst.startAnimation(animationShowFirst); } for (int i = 0; i < animationHideCount; i++) { final View view = animationViewsToHideAndShow[i]; if (view != null && view.getVisibility() != View.GONE) { ok = true; view.startAnimation(animationHide); } } if (!ok) animationFinished(false); } else { animationState = ANIMATION_STATE_NONE; animationHideCount = 0; animationShowCount = 0; animationViewToShowFirst = null; } } } @Override public void onAnimationEnd(Animation animation) { if (((animation == animationShowFirst || animation == animationHide) && animationState == ANIMATION_STATE_HIDING) || (animation == animationShow && animationState == ANIMATION_STATE_SHOWING)) animationFinished(false); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private static void animationCommit11(View focusView) { if (animationAnimatorShowFirst == null) { animationAnimatorShowFirst = new FastAnimator(new FastAnimator.Observer() { @Override public void onUpdate(FastAnimator animator, float value) { if (animationViewToShowFirst != null) animationViewToShowFirst.setAlpha(value); } @Override public void onEnd(FastAnimator animator) { if (animationState == ANIMATION_STATE_HIDING) animationFinished(false); } }, 0); animationAnimatorHide = new FastAnimator(new FastAnimator.Observer() { @Override public void onUpdate(FastAnimator animator, float value) { value = 1.0f - value; for (int i = 0; i < animationHideCount; i++) { final View view = animationViewsToHideAndShow[i]; if (view != null && view.getVisibility() != View.GONE) view.setAlpha(value); } } @Override public void onEnd(FastAnimator animator) { if (animationState == ANIMATION_STATE_HIDING) animationFinished(false); } }, 0); animationAnimatorShow = new FastAnimator(new FastAnimator.Observer() { @Override public void onUpdate(FastAnimator animator, float value) { for (int i = 0; i < animationShowCount; i++) { final View view = animationViewsToHideAndShow[16 + i]; if (view != null) view.setAlpha(value); } } @Override public void onEnd(FastAnimator animator) { if (animationState == ANIMATION_STATE_SHOWING) animationFinished(false); } }, 0); } else { animationAnimatorShowFirst.end(); animationAnimatorHide.end(); animationAnimatorShow.end(); } if (animationHideCount > 0 || animationShowCount > 0 || animationViewToShowFirst != null) { animationState = ANIMATION_STATE_HIDING; animationFocusView = focusView; boolean ok = false; if (animationViewToShowFirst != null) { ok = true; animationAnimatorShowFirst.start(); } for (int i = 0; i < animationHideCount; i++) { final View view = animationViewsToHideAndShow[i]; if (view != null && view.getVisibility() != View.GONE) { ok = true; animationAnimatorHide.start(); break; } } if (!ok) animationFinished(false); } else { animationState = ANIMATION_STATE_NONE; animationHideCount = 0; animationShowCount = 0; animationViewToShowFirst = null; } } }
package org.ovirt.engine.ui.webadmin.section.main.view.tab.datacenter; import javax.inject.Inject; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.storage_domains; import org.ovirt.engine.core.common.businessentities.storage_pool; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.models.datacenters.DataCenterListModel; import org.ovirt.engine.ui.uicommonweb.models.datacenters.DataCenterStorageListModel; import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.datacenter.SubTabDataCenterStoragePresenter; import org.ovirt.engine.ui.webadmin.section.main.view.AbstractSubTabTableView; import org.ovirt.engine.ui.webadmin.uicommon.model.SearchableDetailModelProvider; import org.ovirt.engine.ui.webadmin.widget.action.UiCommandButtonDefinition; import org.ovirt.engine.ui.webadmin.widget.table.column.EnumColumn; import org.ovirt.engine.ui.webadmin.widget.table.column.StorageDomainStatusColumn; import com.google.gwt.user.cellview.client.TextColumn; public class SubTabDataCenterStorageView extends AbstractSubTabTableView<storage_pool, storage_domains, DataCenterListModel, DataCenterStorageListModel> implements SubTabDataCenterStoragePresenter.ViewDef { @Inject public SubTabDataCenterStorageView(SearchableDetailModelProvider<storage_domains, DataCenterListModel, DataCenterStorageListModel> modelProvider) { super(modelProvider); initTable(); initWidget(getTable()); } void initTable() { getTable().addColumn(new StorageDomainStatusColumn(), "", "30px"); TextColumn<storage_domains> nameColumn = new TextColumn<storage_domains>() { @Override public String getValue(storage_domains object) { return object.getstorage_name(); } }; getTable().addColumn(nameColumn, "Domain Name"); TextColumn<storage_domains> typeColumn = new EnumColumn<storage_domains, StorageDomainType>() { @Override public StorageDomainType getRawValue(storage_domains object) { return object.getstorage_domain_type(); } }; getTable().addColumn(typeColumn, "Domain Type"); TextColumn<storage_domains> statusColumn = new EnumColumn<storage_domains, StorageDomainStatus>() { @Override public StorageDomainStatus getRawValue(storage_domains object) { return object.getstatus(); } }; getTable().addColumn(statusColumn, "Status"); TextColumn<storage_domains> freeColumn = new TextColumn<storage_domains>() { @Override public String getValue(storage_domains object) { return object.getTotalDiskSize() - object.getused_disk_size() + " GB"; } }; getTable().addColumn(freeColumn, "Free Space"); TextColumn<storage_domains> usedColumn = new TextColumn<storage_domains>() { @Override public String getValue(storage_domains object) { return object.getused_disk_size() + " GB"; } }; getTable().addColumn(usedColumn, "Used Space"); TextColumn<storage_domains> totalColumn = new TextColumn<storage_domains>() { @Override public String getValue(storage_domains object) { return object.getTotalDiskSize() + " GB"; } }; getTable().addColumn(totalColumn, "Total Space"); getTable().addActionButton(new UiCommandButtonDefinition<storage_domains>("Attach Data") { @Override protected UICommand resolveCommand() { return getDetailModel().getAttachStorageCommand(); } }); getTable().addActionButton(new UiCommandButtonDefinition<storage_domains>("Attach ISO") { @Override protected UICommand resolveCommand() { return getDetailModel().getAttachISOCommand(); } }); getTable().addActionButton(new UiCommandButtonDefinition<storage_domains>("Attach Export") { @Override protected UICommand resolveCommand() { return getDetailModel().getAttachBackupCommand(); } }); // TODO: Separator getTable().addActionButton(new UiCommandButtonDefinition<storage_domains>("Detach") { @Override protected UICommand resolveCommand() { return getDetailModel().getDetachCommand(); } }); // TODO: Separator getTable().addActionButton(new UiCommandButtonDefinition<storage_domains>("Activate") { @Override protected UICommand resolveCommand() { return getDetailModel().getActivateCommand(); } }); getTable().addActionButton(new UiCommandButtonDefinition<storage_domains>("Maintenance") { @Override protected UICommand resolveCommand() { return getDetailModel().getMaintenanceCommand(); } }); } }
package org.innovateuk.ifs.competitionsetup.service; import org.apache.commons.collections4.map.LinkedMap; import org.innovateuk.ifs.application.service.MilestoneService; import org.innovateuk.ifs.commons.error.Error; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.resource.MilestoneResource; import org.innovateuk.ifs.competition.resource.MilestoneType; import org.innovateuk.ifs.competitionsetup.form.MilestoneRowForm; import org.innovateuk.ifs.competitionsetup.form.MilestoneTime; import org.innovateuk.ifs.competitionsetup.form.MilestonesForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import java.time.DateTimeException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; @Service public class CompetitionSetupMilestoneServiceImpl implements CompetitionSetupMilestoneService { @Autowired private MilestoneService milestoneService; @Override public ServiceResult<List<MilestoneResource>> createMilestonesForCompetition(Long competitionId) { List<MilestoneResource> newMilestones = new ArrayList<>(); Stream.of(MilestoneType.presetValues()).forEach(type -> newMilestones.add(milestoneService.create(type, competitionId).getSuccessObjectOrThrowException()) ); return serviceSuccess(newMilestones); } @Override public ServiceResult<Void> updateMilestonesForCompetition(List<MilestoneResource> milestones, Map<String, MilestoneRowForm> milestoneEntries, Long competitionId) { List<MilestoneResource> updatedMilestones = new ArrayList(); milestones.forEach(milestoneResource -> { MilestoneRowForm milestoneWithUpdate = milestoneEntries.getOrDefault(milestoneResource.getType().name(), null); if(milestoneWithUpdate != null) { LocalDateTime temp = milestoneWithUpdate.getMilestoneAsDateTime(); if (temp != null) { milestoneResource.setDate(temp); updatedMilestones.add(milestoneResource); } } }); return milestoneService.updateMilestones(updatedMilestones); } @Override public List<Error> validateMilestoneDates(Map<String, MilestoneRowForm> milestonesFormEntries) { List<Error> errors = new ArrayList<>(); milestonesFormEntries.values().forEach(milestone -> { Integer day = milestone.getDay(); Integer month = milestone.getMonth(); Integer year = milestone.getYear(); if(!validTimeOfMiddayMilestone(milestone)) { if(errors.isEmpty()) { errors.add(new Error("error.milestone.invalid", HttpStatus.BAD_REQUEST)); } } if(day == null || month == null || year == null || !isMilestoneDateValid(day, month, year)) { if(errors.isEmpty()) { errors.add(new Error("error.milestone.invalid", HttpStatus.BAD_REQUEST)); } } }); return errors; } private boolean validTimeOfMiddayMilestone(MilestoneRowForm milestone) { if(milestone.isMiddayTime()) { return MilestoneTime.TWELVE_PM.equals(milestone.getTime()); } return true; } @Override public Boolean isMilestoneDateValid(Integer day, Integer month, Integer year) { try{ LocalDateTime.of(year, month, day, 0,0); if (year > 9999) { return false; } return true; } catch(DateTimeException dte){ return false; } } public void sortMilestones(MilestonesForm milestoneForm) { LinkedMap<String, MilestoneRowForm> milestoneEntries = milestoneForm.getMilestoneEntries(); milestoneForm.setMilestoneEntries(sortMilestoneEntries(milestoneEntries.values())); } private LinkedMap<String, MilestoneRowForm> sortMilestoneEntries(Collection<MilestoneRowForm> milestones) { List<MilestoneRowForm> sortedMilestones = milestones.stream() .sorted((o1, o2) -> o1.getMilestoneType().ordinal() - o2.getMilestoneType().ordinal()) .collect(Collectors.toList()); LinkedMap<String, MilestoneRowForm> milestoneFormEntries = new LinkedMap<>(); sortedMilestones.stream().forEachOrdered(milestone -> milestoneFormEntries.put(milestone.getMilestoneType().name(), milestone) ); return milestoneFormEntries; } }
package org.csstudio.display.builder.representation.javafx.widgets; import java.io.InputStream; import org.csstudio.display.builder.model.DirtyFlag; import org.csstudio.display.builder.model.WidgetProperty; import org.csstudio.display.builder.model.widgets.WebBrowserWidget; import org.csstudio.display.builder.util.ResourceUtil; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.geometry.HPos; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ButtonBase; import javafx.scene.control.ComboBox; import javafx.scene.control.Control; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; import javafx.scene.web.WebEngine; import javafx.scene.web.WebHistory; import javafx.scene.web.WebView; /** Creates JavaFX item for model widget * @author Amanda Carpenter */ @SuppressWarnings("nls") public class WebBrowserRepresentation extends RegionBaseRepresentation<Region, WebBrowserWidget> { private final DirtyFlag dirty_size = new DirtyFlag(); private final DirtyFlag dirty_url = new DirtyFlag(); private volatile double width; private volatile double height; class Browser extends Region { //--fields final WebView browser = new WebView(); final WebEngine webEngine = browser.getEngine(); //--constructors public Browser(String url) { getStyleClass().add("browser"); getChildren().add(browser); goToURL(url); } //--private methods private Node createSpacer() { Region spacer = new Region(); HBox.setHgrow(spacer, Priority.ALWAYS); return spacer; } //--protected methods protected void goToURL(String url) { if (!url.startsWith("http: if (url.equals("")) url = "about:blank"; else url = "http://" + url; webEngine.load(url); } @Override protected void layoutChildren() { double w = getWidth(); double h = getHeight(); layoutInArea(browser, 0,0, w,h, 0, HPos.CENTER, VPos.CENTER); } @Override protected double computePrefWidth(double height) { return width; } @Override protected double computePrefHeight(double width) { return height; } } class BrowserWithToolbar extends Browser { //--fields //--toolbar controls //TODO: remove button text when icons work HBox toolbar; final Button backButton = new Button(); final Button foreButton = new Button(); final Button stop = new Button(); final Button refresh = new Button(); final ComboBox<String> addressBar = new ComboBox<String>(); final Button go = new Button(); Control [] controls = new Control [] {backButton, foreButton, stop, refresh, addressBar, go}; String [] iconFiles = new String [] {"arrow_left.png", "arrow_right.png", "Player_stop.png", "refresh.png", null, "green_chevron.png"}; String [] iconSubstitutes = new String [] {"<", ">", "X", "R", null, "->"}; //--toolbar handlers and listeners void handleBackButton(ActionEvent event) { try { webEngine.getHistory().go(-1); } catch (IndexOutOfBoundsException e) {} } void handleForeButton(ActionEvent event) { try { webEngine.getHistory().go(1); } catch (IndexOutOfBoundsException e) {} } void handleStop(ActionEvent event) { webEngine.getLoadWorker().cancel(); } void handleRefresh(ActionEvent event) { goToURL(webEngine.getLocation()); } void handleGo(ActionEvent event) { goToURL(addressBar.getValue()); } void locationChanged(ObservableValue<? extends String> observable, String oldval, String newval) { addressBar.getEditor().setText(newval); int index = addressBar.getItems().indexOf(newval); foreButton.setDisable(index <= 0); backButton.setDisable(index == addressBar.getItems().size()-1); } void handleShowing(Event event) { WebHistory history = webEngine.getHistory(); int size = history.getEntries().size(); if (history.getCurrentIndex() == size-1) { addressBar.getItems().clear(); for (int i = 0; i < size; i++) { addressBar.getItems().add(0, history.getEntries().get(i).getUrl()); } } } //--constructor public BrowserWithToolbar(String url) { super(url); locationChanged(null, null, webEngine.getLocation()); //assemble toolbar controls backButton.setOnAction(this::handleBackButton); foreButton.setOnAction(this::handleForeButton); stop.setOnAction(this::handleStop); refresh.setOnAction(this::handleRefresh); addressBar.setOnAction(this::handleGo); go.setOnAction(this::handleGo); addressBar.setEditable(true); addressBar.setOnShowing(this::handleShowing); webEngine.locationProperty().addListener(this::locationChanged); final String imageDirectory = "platform:/plugin/org.csstudio.display.builder.model/icons/browser/"; for (int i = 0; i < controls.length; i++) { Control control = controls[i]; if (control instanceof ButtonBase) { HBox.setHgrow(control, Priority.NEVER); InputStream stream = null; try { stream = ResourceUtil.openPlatformResource(imageDirectory+iconFiles[i]); ((ButtonBase)control).setGraphic(new ImageView(new Image(stream))); } catch (Exception e) { ((ButtonBase)control).setText(iconSubstitutes[i]); } } else //grow address bar HBox.setHgrow(control, Priority.ALWAYS); } //add toolbar component toolbar = new HBox(controls); toolbar.getStyleClass().add("browser-toolbar"); getChildren().add(toolbar); } //--protected methods @Override protected void layoutChildren() { double w = getWidth(); double h = getHeight(); double tbHeight = toolbar.prefHeight(w); addressBar.setPrefWidth( addressBar.prefWidth(tbHeight) + (w - toolbar.prefWidth(h)) ); layoutInArea(browser, 0,tbHeight, w,h-tbHeight, 0, HPos.CENTER, VPos.CENTER); layoutInArea(toolbar, 0,0, w,tbHeight, 0, HPos.CENTER,VPos.CENTER); } } @Override public Region createJFXNode() throws Exception { return model_widget.displayShowToolbar().getValue() ? new BrowserWithToolbar(model_widget.widgetURL().getValue()) : new Browser(model_widget.widgetURL().getValue()); } @Override protected void registerListeners() { super.registerListeners(); model_widget.positionWidth().addUntypedPropertyListener(this::sizeChanged); model_widget.positionHeight().addUntypedPropertyListener(this::sizeChanged); model_widget.widgetURL().addPropertyListener(this::urlChanged); //the showToolbar property cannot be changed at runtime } private void sizeChanged(final WidgetProperty<?> property, final Object old_value, final Object new_value) { dirty_size.mark(); toolkit.scheduleUpdate(this); } private void urlChanged(final WidgetProperty<String> property, final String old_value, final String new_value) { dirty_url.mark(); toolkit.scheduleUpdate(this); } @Override public void updateChanges() { super.updateChanges(); if (dirty_size.checkAndClear()) { width = model_widget.positionWidth().getValue(); height = model_widget.positionHeight().getValue(); jfx_node.requestLayout(); } if (dirty_url.checkAndClear()) { ((Browser)jfx_node).goToURL(model_widget.widgetURL().getValue()); } } }
package com.matthewtamlin.spyglass.processor.annotation_utils.value_handler_annotation_util; import com.google.testing.compile.JavaFileObjects; import com.matthewtamlin.avatar.element_supplier.IdBasedElementSupplier; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.BooleanHandler; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.ColorHandler; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.ColorStateListHandler; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.DimensionHandler; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.DrawableHandler; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.EnumConstantHandler; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.EnumOrdinalHandler; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.FloatHandler; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.FractionHandler; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.IntegerHandler; import com.matthewtamlin.spyglass.common.annotations.value_handler_annotations.StringHandler; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.File; import java.net.MalformedURLException; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.tools.JavaFileObject; import static com.matthewtamlin.spyglass.processor.annotation_utils.ValueHandlerAnnotationUtil.getValueHandlerAnnotationMirror; import static com.matthewtamlin.spyglass.processor.annotation_utils.ValueHandlerAnnotationUtil.hasValueHandlerAnnotation; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; @RunWith(JUnit4.class) public class TestValueHandlerAnnotationUtil { private static final File DATA_FILE = new File("processor/src/test/java/com/matthewtamlin/spyglass/processor" + "/annotation_utils/value_handler_annotation_util/Data.java"); private IdBasedElementSupplier elementSupplier; @Before public void setup() throws MalformedURLException { assertThat("Data file does not exist.", DATA_FILE.exists(), is(true)); final JavaFileObject dataFileObject = JavaFileObjects.forResource(DATA_FILE.toURI().toURL()); elementSupplier = new IdBasedElementSupplier(dataFileObject); } @Test(expected = IllegalArgumentException.class) public void testGetValueHandlerAnnotationMirror_nullSupplied() { getValueHandlerAnnotationMirror(null); } @Test public void testGetValueHandlerAnnotationMirror_booleanHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("boolean"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(BooleanHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_colorHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("color"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(ColorHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_colorStateListHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("color state list"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(ColorStateListHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_dimensionHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("dimension"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DimensionHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_drawableHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("drawable"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DrawableHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_enumConstantHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("enum constant"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(EnumConstantHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_enumOrdinalHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("enum ordinal"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(EnumOrdinalHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_floatHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("float"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(FloatHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_fractionHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("fraction"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(FractionHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_integerHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("integer"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(IntegerHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_stringHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("string"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(StringHandler.class.getName())); } @Test public void testGetValueHandlerAnnotationMirror_noValueHandlerAnnotationPresent() { final ExecutableElement element = getExecutableElementWithId("no value handler annotation"); final AnnotationMirror mirror = getValueHandlerAnnotationMirror(element); assertThat(mirror, is(nullValue())); } @Test(expected = IllegalArgumentException.class) public void testHasValueHandlerAnnotation_nullSupplied() { hasValueHandlerAnnotation(null); } @Test public void testHasValueHandlerAnnotation_booleanHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("boolean", true); } @Test public void testHasValueHandlerAnnotation_colorHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("color", true); } @Test public void testGetValueHandlerAnnotation_colorStateListHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("color state list", true); } @Test public void testGetValueHandlerAnnotation_dimensionHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("dimension", true); } @Test public void testGetValueHandlerAnnotation_drawableHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("drawable", true); } @Test public void testGetValueHandlerAnnotation_enumConstantHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("enum constant", true); } @Test public void testGetValueHandlerAnnotation_enumOrdinalHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("enum ordinal", true); } @Test public void testGetValueHandlerAnnotation_floatHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("float", true); } @Test public void testGetValueHandlerAnnotation_fractionHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("fraction", true); } @Test public void testGetValueHandlerAnnotation_integerHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("integer", true); } @Test public void testGetValueHandlerAnnotation_stringHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("string", true); } @Test public void testGetValueHandlerAnnotation_noValueHandlerAnnotationPresent() { doHasAnnotationTestForElementWithId("no value handler annotation", false); } private ExecutableElement getExecutableElementWithId(final String id) { try { return (ExecutableElement) elementSupplier.getUniqueElementWithId(id); } catch (final ClassCastException e) { throw new RuntimeException("Found element with ID " + id + ", but it wasn't an ExecutableElement."); } } private void doHasAnnotationTestForElementWithId(final String id, final boolean shouldHaveAnnotation) { final ExecutableElement element = getExecutableElementWithId(id); final boolean hasAnnotation = hasValueHandlerAnnotation(element); assertThat(hasAnnotation, is(shouldHaveAnnotation)); } private enum PlaceholderEnum {} }
package nu.studer.teamcity.buildscan.agent.servicemessage; import com.gradle.maven.extension.api.scan.BuildScanApi; import org.apache.maven.AbstractMavenLifecycleParticipant; import org.apache.maven.MavenExecutionException; import org.apache.maven.execution.MavenSession; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.logging.Logger; import javax.inject.Inject; @Component(role = AbstractMavenLifecycleParticipant.class, hint = "build-scan-service-message") public final class BuildScanServiceMessageMavenExtension extends AbstractMavenLifecycleParticipant { private final PlexusContainer container; private final Logger logger; @Inject public BuildScanServiceMessageMavenExtension(PlexusContainer container, Logger logger) { this.container = container; this.logger = logger; } @Override public void afterProjectsRead(MavenSession session) throws MavenExecutionException { logger.debug("Executing extension: " + getClass().getSimpleName()); BuildScanApi buildScan = BuildScanApiAccessor.lookup(container, getClass()); if (buildScan != null) { logger.debug("Registering listener capturing build scan link"); BuildScanServiceMessageSender.register(buildScan); logger.debug("Finished registering listener capturing build scan link"); } } }
package org.openhealthtools.mdht.uml.cda.cdt.operations; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.List; import java.util.Map; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.ecore.EObject; import org.junit.Test; import org.openhealthtools.mdht.uml.cda.ccd.operations.CCDValidationTest.CodeCCDValidationTest; import org.openhealthtools.mdht.uml.cda.cdt.CDTFactory; import org.openhealthtools.mdht.uml.cda.cdt.ChiefComplaintSection; import org.openhealthtools.mdht.uml.cda.operations.SectionOperationsTest; /** * This class is a JUnit 4 test case. */ @SuppressWarnings("nls") public class ChiefComplaintSectionOperationsTest extends SectionOperationsTest { protected static final String TEMPLATE_ID = "2.16.840.1.113883.10.20.2.8"; protected static final String CODE = "10154-3"; protected static final String CODE_SYSTEM = "2.16.840.1.113883.6.1"; private static final CDATestCase TEST_CASE_ARRAY[] = { // Template ID new TemplateIDValidationTest(TEMPLATE_ID) { @Override protected boolean validate(final EObject objectToTest, final BasicDiagnostic diagnostician, final Map<Object, Object> map) { return ChiefComplaintSectionOperations .validateChiefComplaintSectionTemplateId( (ChiefComplaintSection) objectToTest, diagnostician, map); } }, // Code new CodeCCDValidationTest(CODE, CODE_SYSTEM) { @Override protected boolean validate(final EObject objectToTest, final BasicDiagnostic diagnostician, final Map<Object, Object> map) { return ChiefComplaintSectionOperations .validateChiefComplaintSectionCode( (ChiefComplaintSection) objectToTest, diagnostician, map); } } }; // TEST_CASE_ARRAY @Override protected List<CDATestCase> getTestCases() { // Return a new List because the one returned by Arrays.asList is // unmodifiable so a sub-class can't append their test cases. final List<CDATestCase> retValue = super.getTestCases(); retValue.addAll(Arrays.asList(TEST_CASE_ARRAY)); return retValue; } /** * @see org.openhealthtools.mdht.uml.cda.operations.MutualExclusionValidationTest#getObjectToTest() */ @Override protected EObject getObjectToTest() { return CDTFactory.eINSTANCE.createChiefComplaintSection(); } } // ChiefComplaintSectionOperationsTest
package com.litesuits.http.request; import com.litesuits.http.LiteHttpClient; import com.litesuits.http.data.Consts; import com.litesuits.http.data.NameValuePair; import com.litesuits.http.exception.HttpClientException; import com.litesuits.http.exception.HttpClientException.ClientException; import com.litesuits.http.listener.HttpListener; import com.litesuits.http.parser.DataParser; import com.litesuits.http.parser.StringParser; import com.litesuits.http.request.content.HttpBody; import com.litesuits.http.request.param.HttpMethod; import com.litesuits.http.request.param.HttpParam; import com.litesuits.http.request.query.AbstractQueryBuilder; import com.litesuits.http.request.query.JsonQueryBuilder; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.net.URLEncoder; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; /** * Base request for {@link LiteHttpClient} method * * @author MaTianyu * 2014-1-19:51:59 */ public class Request { private static final String TAG = Request.class.getSimpleName(); /** * you can give an id to a request */ private long id; /** * custom tag of request */ private Object tag; /** * request abort */ protected Abortable abort; /** * url of http request */ private String url; /** * add custom header to request. */ private LinkedHashMap<String, String> headers; /** * key value parameters */ private LinkedHashMap<String, String> paramMap; /** * intelligently translate java object into mapping(k=v) parameters */ private HttpParam paramModel; /** * when parameter's value is complex, u can chose one buider, default mode * is build value into json string. */ private AbstractQueryBuilder queryBuilder; /** * defaul method is get(GET). */ private HttpMethod method; /** * charset of request */ private String charSet = Consts.DEFAULT_CHARSET; /** * max number of retry.. */ private int retryMaxTimes = LiteHttpClient.DEFAULT_MAX_RETRY_TIMES; /** * http inputsream parser */ private DataParser<?> dataParser; /** * body of post,put.. */ private HttpBody httpBody; /** * a callback of start,retry,redirect,loading,end,etc. */ private HttpListener httpListener; public Request(String url) { this(url, null); } public Request(String url, HttpParam paramModel) { this(url, paramModel, new StringParser(), null, null); } public Request(String url, HttpParam paramModel, DataParser<?> parser, HttpBody httpBody, HttpMethod method) { if (url == null) throw new RuntimeException("Url Cannot be Null."); this.url = url; this.paramModel = paramModel; this.queryBuilder = new JsonQueryBuilder(); setMethod(method); setDataParser(parser); setHttpBody(httpBody); } public long getId() { return id; } public void setId(long id) { this.id = id; } public Object getTag() { return tag; } public void setTag(Object tag) { this.tag = tag; } public Request addHeader(List<NameValuePair> nps) { if (nps != null) { if (headers == null) { headers = new LinkedHashMap<String, String>(); } for (NameValuePair np : nps) { headers.put(np.getName(), np.getValue()); } } return this; } public Request addHeader(String key, String value) { if (value != null) { if (headers == null) { headers = new LinkedHashMap<String, String>(); } headers.put(key, value); } return this; } public HttpBody getHttpBody() { return httpBody; } /** * POST */ public Request setHttpBody(HttpBody httpBody) { if (httpBody != null) { return setHttpBody(httpBody, HttpMethod.Post); } else { return this; } } public Request setHttpBody(HttpBody httpBody, HttpMethod method) { setMethod(method); this.httpBody = httpBody; return this; } public Request addUrlParam(String key, String value) { if (value != null) { if (paramMap == null) { paramMap = new LinkedHashMap<String, String>(); } paramMap.put(key, value); } return this; } public Request addUrlPrifix(String prifix) { setUrl(prifix + url); return this; } public Request addUrlSuffix(String suffix) { setUrl(url + suffix); return this; } public String getRawUrl() { return url; } public String getUrl() throws HttpClientException { // check raw url if (url == null) throw new HttpClientException(ClientException.UrlIsNull); if (paramMap == null && paramModel == null) { return url; } try { StringBuilder sb = new StringBuilder(url); sb.append(url.contains("?") ? "&" : "?"); LinkedHashMap<String, String> map = getBasicParams(); int i = 0, size = map.size(); for (Entry<String, String> v : map.entrySet()) { sb.append(URLEncoder.encode(v.getKey(), charSet)).append("=").append(URLEncoder.encode(v.getValue(), charSet)).append(++i == size ? "" : "&"); } //if (Log.isPrint) Log.v(TAG, "lite request url: " + sb.toString()); return sb.toString(); } catch (Exception e) { throw new HttpClientException(e); } } public Request setUrl(String url) { this.url = url; return this; } /** * hashmapjavamodelstring . */ public LinkedHashMap<String, String> getBasicParams() throws IllegalArgumentException, UnsupportedEncodingException, IllegalAccessException, InvocationTargetException { LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); if (paramMap != null) map.putAll(paramMap); LinkedHashMap<String, String> modelMap = queryBuilder.buildPrimaryMap(paramModel); if (modelMap != null) map.putAll(modelMap); return map; } public LinkedHashMap<String, String> getHeaders() { return headers; } public Request setHeaders(LinkedHashMap<String, String> headers) { this.headers = headers; return this; } public LinkedHashMap<String, String> getParamMap() { return paramMap; } public Request setParamMap(LinkedHashMap<String, String> paramMap) { this.paramMap = paramMap; return this; } public HttpParam getParamModel() { return paramModel; } public Request setParamModel(HttpParam paramModel) { this.paramModel = paramModel; return this; } public AbstractQueryBuilder getQueryBuilder() { return queryBuilder; } public Request setQueryBuilder(AbstractQueryBuilder queryBuilder) { this.queryBuilder = queryBuilder; return this; } public HttpMethod getMethod() { return method; } public Request setMethod(HttpMethod method) { if (method != null) { this.method = method; } else { this.method = HttpMethod.Get; } return this; } public String getCharSet() { return charSet; } public Request setCharSet(String charSet) { this.charSet = charSet; return this; } public int getRetryMaxTimes() { return retryMaxTimes; } public Request setRetryMaxTimes(int retryTimes) { this.retryMaxTimes = retryTimes; return this; } public DataParser<?> getDataParser() { return dataParser; } public Request setDataParser(DataParser<?> dataParser) { if (dataParser != null) { this.dataParser = dataParser; } else { this.dataParser = new StringParser(); } return this; } public void setAbort(Abortable abort) { this.abort = abort; } public void abort() { if (abort != null) abort.abort(); } public HttpListener getHttpListener() { return httpListener; } public void setHttpListener(HttpListener httpListener) { this.httpListener = httpListener; if (dataParser != null) dataParser.setHttpReadingListener(httpListener); } @Override public String toString() { return "\turl = " + url + "\n\tmethod = " + method + "\n\theaders = " + headers + "\n\tcharSet = " + charSet + "\n\tretryMaxTimes = " + retryMaxTimes + "\n\tparamModel = " + paramModel + "\n\tdataParser = " + (dataParser != null ? dataParser.getClass().getSimpleName() : "null") + "\n\tqueryBuilder = " + (queryBuilder != null ? queryBuilder.getClass().getSimpleName() : "null") + "\n\tparamMap = " + paramMap + "\n\thttpBody = " + httpBody; } public static interface Abortable { public void abort(); } }
package com.progressoft.brix.domino.apt.client.processors.module.client.presenters; import com.progressoft.brix.domino.api.client.annotations.Command; import com.progressoft.brix.domino.api.client.request.PresenterCommand; import com.progressoft.brix.domino.apt.commons.DominoTypeBuilder; import com.progressoft.brix.domino.apt.commons.JavaSourceWriter; import com.progressoft.brix.domino.apt.commons.ProcessorElement; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.io.IOException; public class PresenterCommandSourceWriter extends JavaSourceWriter { private final String targetPackage; private final String className; private final ClassName presenterType; public PresenterCommandSourceWriter(ProcessorElement processorElement, String targetPackage, String className, String presenterName) { super(processorElement); this.targetPackage = targetPackage; this.className = className; this.presenterType = ClassName.bestGuess(presenterName); } @Override public String write() throws IOException { TypeSpec contributionRequest = DominoTypeBuilder.build(className, PresenterCommandProcessor.class) .addAnnotation(Command.class) .superclass(ParameterizedTypeName.get(ClassName.get(PresenterCommand.class), presenterType)) .build(); StringBuilder asString = new StringBuilder(); JavaFile.builder(targetPackage, contributionRequest).skipJavaLangImports(true).build().writeTo(asString); return asString.toString(); } }
package sqlancer.tidb.gen; import java.sql.SQLException; import java.util.function.Function; import sqlancer.Query; import sqlancer.QueryAdapter; import sqlancer.Randomly; import sqlancer.tidb.TiDBProvider.TiDBGlobalState; public class TiDBSetGenerator { private enum Action { // SQL_MODE("sql_mode", (r) -> Randomly.fromOptions("TRADITIONAL", "ANSI", "POSTGRESQL", "ORACLE")), TIDB_OPT_AGG_PUSH_DOWN("tidb_opt_agg_push_down", (r) -> Randomly.fromOptions(0, 1)), TIDB_BUILD_STATS_CONCURRENCY("tidb_build_stats_concurrency", (r) -> Randomly.getNotCachedInteger(0, 500)), TIDB_CHECKSUM_TABLE_CONCURRENCY("tidb_checksum_table_concurrency", (r) -> Randomly.getNotCachedInteger(0, 500)), TIDB_DISTSQL_SCAN_CONCURRENCY("tidb_distsql_scan_concurrency", (r) -> Randomly.getNotCachedInteger(1, 500)), TIDB_INDEX_LOOKUP_SIZE("tidb_index_lookup_size", (r) -> Randomly.getNotCachedInteger(1, 100000)), TIDB_INDEX_LOOKUP_CONCURRENCY("tidb_index_lookup_concurrency", (r) -> Randomly.getNotCachedInteger(1, 100)), TIDB_INDEX_LOOKUP_JOIN_CONCURRENCY("tidb_index_lookup_join_concurrency", (r) -> Randomly.getNotCachedInteger(1, 100)), TIDB_HASH_JOIN_CONCURRENCY("tidb_hash_join_concurrency", (r) -> Randomly.getNotCachedInteger(1, 100)), TIDB_INDEX_SERIAL_SCAN_CONCURRENCY("tidb_index_serial_scan_concurrency", (r) -> Randomly.getNotCachedInteger(1, 100)), TIDB_PROJECTION_CONCURRENCY("tidb_projection_concurrency", (r) -> Randomly.getNotCachedInteger(1, 100)), TIDB_HASHAGG_PARTIAL_CONCURRENCY("tidb_hashagg_partial_concurrency", (r) -> Randomly.getNotCachedInteger(1, 100)), TIDB_HASHAGG_FINAL_CONCURRENCY("tidb_hashagg_final_concurrency", (r) -> Randomly.getNotCachedInteger(1, 100)), TIDB_INDEX_JOIN_BATCH_SIZE("tidb_index_join_batch_size", (r) -> Randomly.getNotCachedInteger(1, 5000)), TIDB_INDEX_SKIP_UTF8_CHECK("tidb_skip_utf8_check", (r) -> Randomly.fromOptions(0, 1)), TIDB_INIT_CHUNK_SIZE("tidb_init_chunk_size", (r) -> Randomly.getNotCachedInteger(1, 32)), TIDB_MAX_CHUNK_SIZE("tidb_max_chunk_size", (r) -> Randomly.getNotCachedInteger(32, 50000)), TIDB_CONSTRAINT_CHECK_IN_PLACE("tidb_constraint_check_in_place", (r) -> Randomly.fromOptions(0, 1)), TIDB_OPT_INSUBQ_TO_JOIN_AND_AGG("tidb_opt_insubq_to_join_and_agg", (r) -> Randomly.fromOptions(0, 1)), TIDB_OPT_CORRELATION_THRESHOLD("tidb_opt_correlation_threshold", (r) -> Randomly.fromOptions(0, 0.0001, 0.1, 0.25, 0.50, 0.75, 0.9, 0.9999999, 1)), TIDB_OPT_CORRELATION_EXP_FACTOR("tidb_opt_correlation_exp_factor", (r) -> Randomly.getNotCachedInteger(0, 10000)), TIDB_ENABLE_WINDOW_FUNCTION("tidb_enable_window_function", (r) -> Randomly.fromOptions(0, 1)), // TIDB_ENABLE_FAST_ANALYZE("tidb_enable_fast_analyze", (r) -> Randomly.fromOptions(0, 1)); TIDB_WAIT_SPLIT_REGION_FINISH("tidb_wait_split_region_finish", (r) -> Randomly.fromOptions(0, 1)), // TODO: global // TIDB_SCATTER_REGION("tidb_scatter_region", (r) -> Randomly.fromOptions(0, 1)); TIDB_ENABLE_CHUNK_RPC("tidb_enable_chunk_rpc", (r) -> Randomly.fromOptions(0, 1)); private String name; private Function<Randomly, Object> prod; Action(String name, Function<Randomly, Object> prod) { this.name = name; this.prod = prod; } } public static Query getQuery(TiDBGlobalState globalState) throws SQLException { StringBuilder sb = new StringBuilder(); Action option = Randomly.fromOptions(Action.values()); sb.append("set @@"); sb.append(option.name); sb.append("="); sb.append(option.prod.apply(globalState.getRandomly())); return new QueryAdapter(sb.toString()); } }
package net.sf.jaer.graphics; import java.awt.Color; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.logging.Logger; import javax.swing.JButton; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.orientation.OrientationEventInterface; import net.sf.jaer.eventio.AEInputStream; import net.sf.jaer.util.SpikeSound; /** * Superclass for classes that render AEs to a memory buffer so that they can be * painted on the screen. Note these classes do not actually render to the * graphics device; They take AEPacket's and render them to a pixmap memory * buffer that later gets painted by a ChipCanvas. The method chosen (by user * cycling method from GUI) chooses how the events are painted. In effect the * events are histogrammed for most rendering methods except for "color-time", * and even there they are histogrammed or averaged. For methods that render * polarized events (such as ON-OFF) then ON events increase the rendered value * while OFF events decreases it. Thus the rendered image fr can be drawn in 3-d * if desired and it will represent a histogram, although the default method * using for drawing the rendered frame is to paint the cell brightness. * * @author tobi * @see ChipRendererDisplayMethod */ public class AEChipRenderer extends Chip2DRenderer implements PropertyChangeListener { private boolean addedPropertyChangeListener = false; public boolean externalRenderer = false; /** * PropertyChange events */ public static final String EVENT_COLOR_SCALE_CHANGE = "colorScale"; /** * PropertyChange events */ public static final String EVENT_COLOR_MODE_CHANGE = "colorMode"; /** * @return the specialCount */ public int getSpecialCount() { return specialCount; } /** * @param specialCount * the specialCount to set */ public void setSpecialCount(int specialCount) { this.specialCount = specialCount; } public void incrementSpecialCount(int specialCountInc) { this.specialCount += specialCountInc; } public enum ColorMode { GrayLevel("Each event causes linear change in brightness"), Contrast("Each event causes multiplicative change in brightness to produce logarithmic scale"), RedGreen("ON events are green; OFF events are red"), ColorTime("Events are colored according to time within displayed slice, with red coding old events and green coding new events"), GrayTime("Events are colored according to time within displayed slice, with white coding old events and black coding new events"); public String description; ColorMode(String description) { this.description = description; } @Override public String toString() { return super.toString() + ": " + description; } }; protected ColorMode[] colorModes = ColorMode.values(); // array of mode enums protected ColorMode colorMode; { ColorMode oldMode; try { oldMode = ColorMode.valueOf(prefs.get("ChipRenderer.colorMode", ColorMode.GrayLevel.name())); } catch (IllegalArgumentException e) { oldMode = ColorMode.GrayLevel; } for (ColorMode c : colorModes) { if (c == oldMode) { colorMode = c; } } } /** * perceptually separated hues - as estimated quickly by tobi */ protected static final int[] HUES = { 0, 36, 45, 61, 70, 100, 169, 188, 205, 229, 298, 318, }; /** * the number of rendering methods implemented */ public static int NUM_METHODS = 4; /** * number of colors used to represent time of event */ public static final int NUM_TIME_COLORS = 255; /** * chip shadows Chip2D's chip to declare it as AEChip */ protected AEChip chip; // protected AEPacket2D ae = null; protected EventPacket packet = null; /** * the chip rendered for */ protected boolean ignorePolarityEnabled = false; protected Logger log = Logger.getLogger("net.sf.jaer.graphics"); /** * The Colors that different cell types are painted. checkTypeColors should * populate this array. */ protected Color[] typeColors; /** * Used for rendering multiple cell types in different RGB colors. * checkTypeColors should populate this array of [numTypes][3] size. Each * 3-vector are the RGB color components for that cell type. */ protected float[][] typeColorRGBComponents; protected SpikeSound spikeSound; protected float step; // this is last step of RGB value used in rendering protected boolean stereoEnabled = false; protected int subsampleThresholdEventCount = prefs.getInt("ChipRenderer.subsampleThresholdEventCount", 50000); /** * determines subSampling of rendered events (for speed) */ protected boolean subsamplingEnabled = prefs.getBoolean("ChipRenderer.subsamplingEnabled", false); protected float[][] timeColors; protected int specialCount = 0; public AEChipRenderer(AEChip chip) { super(chip); if (chip == null) { throw new Error("tried to build ChipRenderer with null chip"); } setChip(chip); spikeSound = new SpikeSound(); timeColors = new float[NUM_TIME_COLORS][3]; float s = 1f / NUM_TIME_COLORS; for (int i = 0; i < NUM_TIME_COLORS; i++) { int rgb = Color.HSBtoRGB((0.66f * (NUM_TIME_COLORS - i)) / NUM_TIME_COLORS, 1f, 1f); Color c = new Color(rgb); float[] comp = c.getRGBColorComponents(null); timeColors[i][0] = comp[0]; timeColors[i][2] = comp[2]; timeColors[i][1] = comp[1]; // System.out.println(String.format("%.2f %.2f %.2f",comp[0],comp[1],comp[2])); } } /** * Overrides color scale setting to update the stored accumulated pixmap * when the color scale is changed. * * */ @Override synchronized public void setColorScale(int colorScale) { int old = this.colorScale; super.setColorScale(colorScale); if (old == this.colorScale) { return; } float r = (float) old / colorScale; // e.g. r=0.5 when scale changed from 1 to 2 if (pixmap == null) { return; } float[] f = getPixmapArray(); switch (colorMode) { case GrayLevel: case Contrast: // colorScale=1,2,3; step = 1, 1/2, 1/3, 1/4, ; // later type-grayValue gives -.5 or .5 for spike value, when // multipled gives steps of 1/2, 1/3, 1/4 to end up with 0 or 1 when colorScale=1 and you have one event for (int i = 0; i < f.length; i += 3) { final float g = 0.5f; float d = f[i] - g; d = d * r; f[i] = d + g; f[i + 1] = d + g; f[i + 2] = d + g; } break; case RedGreen: for (int i = 0; i < f.length; i += 3) { f[i] = f[i] * r; f[i + 1] = f[i + 1] * r; } break; default: // rendering method unknown, reset to default value log.warning("colorMode " + colorMode + " unknown, reset to default value 0"); setColorMode(ColorMode.GrayLevel); } getSupport().firePropertyChange(EVENT_COLOR_SCALE_CHANGE, old, colorScale); } /** * Does the rendering using selected method. * * @param packet * a packet of events (already extracted from raw events) * @see #setColorMode */ public synchronized void render(EventPacket packet) { if (!addedPropertyChangeListener) { if (chip instanceof AEChip) { AEChip aeChip = chip; if (aeChip.getAeViewer() != null) { aeChip.getAeViewer().addPropertyChangeListener(this); addedPropertyChangeListener = true; } } } if (packet == null) { return; } this.packet = packet; int numEvents = packet.getSize(); int skipBy = 1; if (isSubsamplingEnabled()) { while ((numEvents / skipBy) > getSubsampleThresholdEventCount()) { skipBy++; } } checkPixmapAllocation(); float[] f = getPixmapArray(); float a; resetSelectedPixelEventCount(); // init it for this packet boolean ignorePolarity = isIgnorePolarityEnabled(); setSpecialCount(0); try { if (packet.getNumCellTypes() > 2) { checkTypeColors(packet.getNumCellTypes()); if (!accumulateEnabled && !externalRenderer) { resetFrame(0); } step = 1f / (colorScale); for (Object obj : packet) { BasicEvent e = (BasicEvent) obj; if (e.isSpecial()) { setSpecialCount(specialCount + 1); // TODO optimize special count increment continue; } int type = e.getType(); if ((e.x == xsel) && (e.y == ysel)) { playSpike(type); } int ind = getPixMapIndex(e.x, e.y); // float[] f = fr[e.y][e.x]; // setPixmapPosition(e.x, e.y); float[] c = typeColorRGBComponents[type]; if ((obj instanceof OrientationEventInterface) && (((OrientationEventInterface) obj).isHasOrientation() == false)) { // if event is orientation event but orientation was not set, just draw as gray level f[ind] += step; // if(f[0]>1f) f[0]=1f; f[ind + 1] += step; // if(f[1]>1f) f[1]=1f; f[ind + 2] += step; // if(f[2]>1f) f[2]=1f; } else if (colorScale > 1) { f[ind] += c[0] * step; // if(f[0]>1f) f[0]=1f; f[ind + 1] += c[1] * step; // if(f[1]>1f) f[1]=1f; f[ind + 2] += c[2] * step; // if(f[2]>1f) f[2]=1f; } else { // if color scale is 1, then last value is used as the pixel value, which quantizes the color to // full scale. f[ind] = c[0]; // if(f[0]>1f) f[0]=1f; f[ind + 1] = c[1]; // if(f[1]>1f) f[1]=1f; f[ind + 2] = c[2]; // if(f[2]>1f) f[2]=1f; } } } else { switch (colorMode) { case GrayLevel: if (!accumulateEnabled && !externalRenderer) { resetFrame(.5f); // also sets grayValue } step = 2f / (colorScale + 1); // colorScale=1,2,3; step = 1, 1/2, 1/3, 1/4, ; // later type-grayValue gives -.5 or .5 for spike value, when // multipled gives steps of 1/2, 1/3, 1/4 to end up with 0 or 1 when colorScale=1 and you have // one event for (Object obj : packet) { BasicEvent e = (BasicEvent) obj; int type = e.getType(); if (e.isSpecial()) { setSpecialCount(specialCount + 1); // TODO optimate special count increment continue; } if ((e.x == xsel) && (e.y == ysel)) { playSpike(type); } int ind = getPixMapIndex(e.x, e.y); a = f[ind]; if (!ignorePolarity) { a += step * (type - grayValue); // type-.5 = -.5 or .5; step*type= -.5, .5, (cs=1) or // -.25, .25 (cs=2) etc. } else { a += step * (1 - grayValue); // type-.5 = -.5 or .5; step*type= -.5, .5, (cs=1) or -.25, // .25 (cs=2) etc. } f[ind] = a; f[ind + 1] = a; f[ind + 2] = a; } break; case Contrast: if (!accumulateEnabled && !externalRenderer) { resetFrame(.5f); } float eventContrastRecip = 1 / eventContrast; for (Object obj : packet) { BasicEvent e = (BasicEvent) obj; int type = e.getType(); if (e.isSpecial()) { setSpecialCount(specialCount + 1); // TODO optimate special count increment continue; } if ((e.x == xsel) && (e.y == ysel)) { playSpike(type); } int ind = getPixMapIndex(e.x, e.y); a = f[ind]; switch (type) { case 0: a *= eventContrastRecip; // off cell divides gray break; case 1: a *= eventContrast; // on multiplies gray } f[ind] = a; f[ind + 1] = a; f[ind + 2] = a; } break; case RedGreen: if (!accumulateEnabled && !externalRenderer) { resetFrame(0); } step = 1f / (colorScale); // cs=1, step=1, cs=2, step=.5 for (Object obj : packet) { BasicEvent e = (BasicEvent) obj; int type = e.getType(); if (e.isSpecial()) { setSpecialCount(specialCount + 1); // TODO optimate special count increment continue; } // System.out.println("x: " + e.x + " y:" + e.y); if ((e.x == xsel) && (e.y == ysel)) { playSpike(type); } int ind = getPixMapIndex(e.x, e.y); f[ind + type] += step; } break; case ColorTime: if (!accumulateEnabled && !externalRenderer) { resetFrame(0); } if (numEvents == 0) { return; } int ts0 = packet.getFirstTimestamp(); float dt = packet.getDurationUs(); step = 1f / (colorScale); // cs=1, step=1, cs=2, step=.5 for (Object obj : packet) { BasicEvent e = (BasicEvent) obj; int type = e.getType(); if (e.isSpecial()) { setSpecialCount(getSpecialCount() + 1); // TODO optimate special count increment continue; } if ((e.x == xsel) && (e.y == ysel)) { playSpike(type); } int index = getPixMapIndex(e.x, e.y); int ind = (int) Math.floor(((NUM_TIME_COLORS - 1) * (e.timestamp - ts0)) / dt); if (ind < 0) { ind = 0; } else if (ind >= timeColors.length) { ind = timeColors.length - 1; } if (colorScale > 1) { for (int c = 0; c < 3; c++) { f[index + c] += timeColors[ind][c] * step; } } else { f[index] = timeColors[ind][0]; f[index + 1] = timeColors[ind][1]; f[index + 2] = timeColors[ind][2]; } } break; default: // rendering method unknown, reset to default value log.warning("colorMode " + colorMode + " unknown, reset to default value 0"); setColorMode(ColorMode.GrayLevel); } } autoScaleFrame(f); } catch (ArrayIndexOutOfBoundsException e) { if ((chip.getFilterChain() != null) && (chip.getFilterChain().getProcessingMode() != net.sf.jaer.eventprocessing.FilterChain.ProcessingMode.ACQUISITION)) { // only // print // real-time // mode // has // not // invalidated // the // packet // are // trying // render e.printStackTrace(); log.warning(e.toString() + ": ChipRenderer.render(), some event out of bounds for this chip type?"); } } pixmap.rewind(); } /** * Autoscales frame data so that max value is 1. If autoscale is disabled, * then values are just clipped to 0-1 range. If autoscale is enabled, then * gray is mapped back to gray and following occurs: * <p> * Global normalizer is tricky because we want to map max value to 1 OR min * value to 0, whichever is greater magnitude, max or min. ALSO, max and min * are distances from gray level in positive and negative directions. After * global normalizer is computed, all values are divided by normalizer in * order to keep gray level constant. * * @param fr * the frame rgb data [y][x][rgb] * @param gray * the gray level */ protected void autoScaleFrame(float[][][] fr, float gray) { if (!autoscaleEnabled) { return; } { // compute min and max values and divide to keep gray level constant // float[] mx={Float.MIN_VALUE,Float.MIN_VALUE,Float.MIN_VALUE}, // mn={Float.MAX_VALUE,Float.MAX_VALUE,Float.MAX_VALUE}; float max = Float.NEGATIVE_INFINITY, min = Float.POSITIVE_INFINITY; // max=max-.5f; // distance of max from gray // min=.5f-min; // distance of min from gray for (float[][] element : fr) { for (float[] element2 : element) { for (int k = 0; k < 3; k++) { float f = element2[k] - gray; if (f > max) { max = f; } else if (f < min) { min = f; } } } } // global normalizer here // this is tricky because we want to map max value to 1 OR min value to 0, whichever is greater magnitude, // max or min // ALSO, max and min are distances from gray level in positive and negative directions float m, b = gray; // slope/intercept of mapping function if (max == min) { return; // if max==min then no need to normalize or do anything, just paint gray } if (max > -min) { // map max to 1, gray to gray m = (1 - gray) / (max); b = gray - (gray * m); } else { // map min to 0, gray to gray m = gray / (-min); b = gray - (gray * m); } // float norm=(float)Math.max(Math.abs(max),Math.abs(min)); // norm is max distance from gray level // System.out.println("norm="+norm); if (colorMode != ColorMode.Contrast) { autoScaleValue = Math.round(Math.max(max, -min) / step); // this is value shown to user, step was // computed during rendering to be (usually) // 1/colorScale } else { if (max > -min) { autoScaleValue = 1; // this is value shown to user, step was computed during rendering to be // (usually) 1/colorScale } else { autoScaleValue = -1; // this is value shown to user, step was computed during rendering to be // (usually) 1/colorScale } } // normalize all channels for (int i = 0; i < fr.length; i++) { for (int j = 0; j < fr[i].length; j++) { for (int k = 0; k < 3; k++) { float f = fr[i][j][k]; float f2 = (m * f) + b; if (f2 < 0) { f2 = 0; } else if (f2 > 1) { f2 = 1; // shouldn't need this } fr[i][j][k] = f2; } } } } } /** * autoscales frame data so that max value is 1. If autoscale is disabled, * then values are just clipped to 0-1 range. If autoscale is enabled, then * gray is mapped back to gray and following occurs: * <p> * Global normalizer is tricky because we want to map max value to 1 OR min * value to 0, whichever is greater magnitude, max or min. ALSO, max and min * are distances from gray level in positive and negative directions. After * global normalizer is computed, all values are divided by normalizer in * order to keep gray level constant. * * @param fr * the frame rgb data pixmap */ protected void autoScaleFrame(float[] fr) { if (!autoscaleEnabled) { return; } // compute min and max values and divide to keep gray level constant // float[] mx={Float.MIN_VALUE,Float.MIN_VALUE,Float.MIN_VALUE}, // mn={Float.MAX_VALUE,Float.MAX_VALUE,Float.MAX_VALUE}; float max = Float.NEGATIVE_INFINITY, min = Float.POSITIVE_INFINITY; // max=max-.5f; // distance of max from gray // min=.5f-min; // distance of min from gray for (float element : fr) { float f = element - grayValue; if (f > max) { max = f; } else if (f < min) { min = f; } } // global normalizer here // this is tricky because we want to map max value to 1 OR min value to 0, whichever is greater magnitude, max // or min // ALSO, max and min are distances from gray level in positive and negative directions float m, b = grayValue; // slope/intercept of mapping function if (max == min) { return; // if max==min then no need to normalize or do anything, just paint gray } if (max > -min) { // map max to 1, gray to gray m = (1 - grayValue) / (max); b = grayValue - (grayValue * m); } else { // map min to 0, gray to gray m = grayValue / (-min); b = grayValue - (grayValue * m); } if (colorMode != ColorMode.Contrast) { autoScaleValue = Math.round(Math.max(max, -min) / step); // this is value shown to user, step was computed // during rendering to be (usually) 1/colorScale } else { if (max > -min) { autoScaleValue = 1; // this is value shown to user, step was computed during rendering to be (usually) // 1/colorScale } else { autoScaleValue = -1; // this is value shown to user, step was computed during rendering to be (usually) // 1/colorScale } } // normalize all channels for (int i = 0; i < fr.length; i++) { fr[i] = (m * fr[i]) + b; } } private HashMap<Integer, float[][]> typeColorsMap = new HashMap<Integer, float[][]>(); /** * Creates colors for each cell type (e.g. orientation) so that they are * spread over hue space in a manner to attempt to be maximally different in * hue. * * <p> * Subclasses can override this method to customize the colors drawn but the * subclasses should check if the color have been created since * checkTypeColors is called on every rendering cycle. This method should * first check if typeColorRGBComponents already exists and has the correct * number of elements. If not, allocate and populate typeColorRGBComponents * so that type t corresponds to typeColorRGBComponents[t][0] for red, * typeColorRGBComponents[t][1] for green, and typeColorRGBComponents[t][3] * for blue. It should also populate the Color[] typeColors. * * new code should use the #makeTypeColors method which caches the colors in a HashMap by numbers of cell types * * @param numCellTypes the number of colors to generate * @see #typeColors * @see #typeColorRGBComponents */ protected void checkTypeColors(int numCellTypes) { if ((typeColorRGBComponents == null) || (typeColorRGBComponents.length != numCellTypes)) { typeColorRGBComponents = new float[numCellTypes][3]; setTypeColors(new Color[numCellTypes]); StringBuffer b = new StringBuffer("cell type rendering colors (type: rgb):\n"); for (int i = 0; i < typeColorRGBComponents.length; i++) { int hueIndex = (int) Math.floor(((float) i / typeColorRGBComponents.length) * HUES.length); // float hue=(float)(numCellTypes-i)/(numCellTypes); float hue = HUES[hueIndex] / 255f; // hue=hue*hue; // Color c=space.fromCIEXYZ(comp); Color c = Color.getHSBColor(hue, 1, 1); getTypeColors()[i] = c; typeColorRGBComponents[i][0] = (float) c.getRed() / 255; typeColorRGBComponents[i][1] = (float) c.getGreen() / 255; typeColorRGBComponents[i][2] = (float) c.getBlue() / 255; JButton but = new JButton(" "); // TODO why is this button here? maybe to be used by some subclasses or // users? but.setBackground(c); but.setForeground(c); b.append(String.format("type %d: %.2f, %.2f, %.2f\n", i, typeColorRGBComponents[i][0], typeColorRGBComponents[i][1], typeColorRGBComponents[i][2])); } log.info(b.toString()); } } /** * Creates colors for each cell type (e.g. orientation) so that they are * spread over hue space in a manner to attempt to be maximally different in * hue. * <p> * Subclasses can override this method to customize the colors drawn but the * subclasses should check if the color have been created since * checkTypeColors is called on every rendering cycle. This method should * first check if typeColorRGBComponents already exists and has the correct * number of elements. If not, allocate and populate typeColorRGBComponents * so that type t corresponds to typeColorRGBComponents[t][0] for red, * typeColorRGBComponents[t][1] for green, and typeColorRGBComponents[t][3] * for blue. It should also populate the Color[] typeColors. * * @param numCellTypes * the number of colors to generate * @return the float[][] of colors, each row of which is an RGB color * triplet in float 0-1 range for a particular cell type * @see #typeColors * @see #typeColorRGBComponents */ public float[][] makeTypeColors(int numCellTypes) { float[][] colors = typeColorsMap.get(numCellTypes); if (colors == null) { colors = new float[numCellTypes][3]; setTypeColors(new Color[numCellTypes]); for (int i = 0; i < numCellTypes; i++) { int hueIndex = (int) Math.floor(((float) i / numCellTypes) * HUES.length); float hue = HUES[hueIndex] / 255f; Color c = Color.getHSBColor(hue, 1, 1); colors[i][0] = (float) c.getRed() / 255; colors[i][1] = (float) c.getGreen() / 255; colors[i][2] = (float) c.getBlue() / 255; } typeColorsMap.put(numCellTypes, colors); return colors; } return typeColorsMap.get(numCellTypes); } /** * go on to next rendering method */ public synchronized void cycleColorMode() { int m = colorMode.ordinal(); if (++m >= colorModes.length) { m = 0; } setColorMode(colorModes[m]); // method++; // if (method > NUM_METHODS-1) method = 0; // setColorMode(method); // store preferences } /** * returns the last packet rendered * * @return the last packet that was rendered */ public EventPacket getPacket() { return packet; } public void setChip(AEChip chip) { this.chip = chip; } public AEChip getChip() { return chip; } public ColorMode getColorMode() { return colorMode; } public int getSubsampleThresholdEventCount() { return subsampleThresholdEventCount; } public boolean isIgnorePolarityEnabled() { return ignorePolarityEnabled; } protected boolean isMethodMonochrome() { if ((colorMode == ColorMode.GrayLevel) || (colorMode == ColorMode.Contrast)) { return true; } else { return false; } } public boolean isStereoEnabled() { return stereoEnabled; } public boolean isSubsamplingEnabled() { return subsamplingEnabled; } /** * Plays a single spike click and increments the selectedPixelEventCount * counter * * @param type * 0 to play left, 1 to play right */ protected void playSpike(int type) { spikeSound.play(type); selectedPixelEventCount++; } /** * Sets whether an external renderer adds data to the array and resets it * * @param extRender */ public void setExternalRenderer(boolean extRender) { externalRenderer = extRender; } /** * Sets whether to ignore event polarity when rendering so that all event * types increase brightness * * @param ignorePolarityEnabled * true to ignore */ public void setIgnorePolarityEnabled(boolean ignorePolarityEnabled) { this.ignorePolarityEnabled = ignorePolarityEnabled; } /** * @param colorMode * the rendering method, e.g. gray, red/green opponency, * time encoded. */ public synchronized void setColorMode(ColorMode colorMode) { ColorMode old = this.colorMode; this.colorMode = colorMode; prefs.put("ChipRenderer.colorMode", colorMode.name()); log.info("set colorMode=" + colorMode); getSupport().firePropertyChange(EVENT_COLOR_MODE_CHANGE, old, colorMode); // if (method<0 || method >NUM_METHODS-1) throw new RuntimeException("no such rendering method "+method); // this.method = method; // prefs.putInt("ChipRenderer.method",method); } public void setStereoEnabled(boolean stereoEnabled) { this.stereoEnabled = stereoEnabled; } public void setSubsampleThresholdEventCount(int subsampleThresholdEventCount) { prefs.putInt("ChipRenderer.subsampleThresholdEventCount", subsampleThresholdEventCount); this.subsampleThresholdEventCount = subsampleThresholdEventCount; } public void setSubsamplingEnabled(boolean subsamplingEnabled) { this.subsamplingEnabled = subsamplingEnabled; prefs.putBoolean("ChipRenderer.subsamplingEnabled", subsamplingEnabled); } /** * @see AEChipRenderer#typeColorRGBComponents * @return a 2-d float array of color components. Each row of the array is a * 3-vector of RGB color components for rendering a particular cell type. */ public float[][] getTypeColorRGBComponents() { checkTypeColors(chip.getNumCellTypes()); // should be efficient return typeColorRGBComponents; } /** * @see AEChipRenderer#typeColorRGBComponents */ public void setTypeColorRGBComponents(float[][] typeColors) { this.typeColorRGBComponents = typeColors; } /** * @see AEChipRenderer#typeColors */ public Color[] getTypeColors() { return typeColors; } /** * @see AEChipRenderer#typeColors */ public void setTypeColors(Color[] typeColors) { this.typeColors = typeColors; } @Override public void propertyChange(PropertyChangeEvent pce) { if (pce.getPropertyName() == AEInputStream.EVENT_REWIND) { resetFrame(grayValue); } } }
package net.wigle.wigleandroid; import static android.location.LocationManager.GPS_PROVIDER; import static android.location.LocationManager.NETWORK_PROVIDER; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import org.andnav.osm.util.GeoPoint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Color; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.GpsStatus.Listener; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnErrorListener; import android.net.Uri; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.provider.Settings; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public final class WigleAndroid extends Activity { // state. anything added here should be added to the retain copy-construction private ArrayAdapter<Network> listAdapter; private Set<String> runNetworks; private GpsStatus gpsStatus; private Location location; private Location networkLocation; private Location prevGpsLocation; private Handler wifiTimer; private DatabaseHelper dbHelper; private ServiceConnection serviceConnection; private AtomicBoolean finishing; private String savedStats; private long prevNewNetCount; private Long satCountLowTime = 0L; // set these times to avoid NPE in locationOK() seen by <DooMMasteR> private Long lastLocationTime = 0L; private Long lastNetworkLocationTime = 0L; private long scanRequestTime = Long.MIN_VALUE; private MediaPlayer soundPop; private MediaPlayer soundNewPop; private WifiLock wifiLock; // created every time, even after retain private Listener gpsStatusListener; private LocationListener locationListener; private BroadcastReceiver wifiReceiver; private NumberFormat numberFormat1; private NumberFormat numberFormat8; private TTS tts; private AudioManager audioManager; private long previousTalkTime = System.currentTimeMillis(); private boolean inEmulator; public static final String FILE_POST_URL = "https://wigle.net/gps/gps/main/confirmfile/"; private static final String LOG_TAG = "wigle"; private static final int MENU_SETTINGS = 10; private static final int MENU_EXIT = 11; private static final int MENU_MAP = 12; private static final int MENU_DASH = 13; public static final String ENCODING = "ISO-8859-1"; private static final long GPS_TIMEOUT = 15000L; private static final long NET_LOC_TIMEOUT = 60000L; // color by signal strength public static final int COLOR_1 = Color.rgb( 70, 170, 0); public static final int COLOR_2 = Color.rgb(170, 170, 0); public static final int COLOR_3 = Color.rgb(170, 95, 30); public static final int COLOR_4 = Color.rgb(180, 60, 40); public static final int COLOR_5 = Color.rgb(180, 45, 70); // preferences static final String SHARED_PREFS = "WiglePrefs"; static final String PREF_USERNAME = "username"; static final String PREF_PASSWORD = "password"; static final String PREF_SHOW_CURRENT = "showCurrent"; static final String PREF_BE_ANONYMOUS = "beAnonymous"; static final String PREF_DB_MARKER = "dbMarker"; static final String PREF_SCAN_PERIOD = "scanPeriod"; static final String PREF_FOUND_SOUND = "foundSound"; static final String PREF_SPEECH_PERIOD = "speechPeriod"; static final String PREF_SPEECH_GPS = "speechGPS"; static final String PREF_MUTED = "muted"; static final String PREF_WIFI_WAS_OFF = "wifiWasOff"; static final String PREF_DISTANCE_RUN = "distRun"; static final String PREF_DISTANCE_TOTAL = "distTotal"; static final long DEFAULT_SPEECH_PERIOD = 60L; static final String ANONYMOUS = "anonymous"; private static final String WIFI_LOCK_NAME = "wigleWifiLock"; //static final String THREAD_DEATH_MESSAGE = "threadDeathMessage"; /** XXX: switch to using the service */ public static class LameStatic { public Location location; public String savedStats; public ConcurrentLinkedHashMap<GeoPoint,Integer> trail = new ConcurrentLinkedHashMap<GeoPoint,Integer>( 512 ); public int runNets; public long newNets; public int preQueueSize; } public static final LameStatic lameStatic = new LameStatic(); // cache private static final ThreadLocal<CacheMap<String,Network>> networkCache = new ThreadLocal<CacheMap<String,Network>>() { protected CacheMap<String,Network> initialValue() { return new CacheMap<String,Network>( 16, 64 ); } }; private static final Comparator<Network> signalCompare = new Comparator<Network>() { public int compare( Network a, Network b ) { return b.getLevel() - a.getLevel(); } }; /** Called when the activity is first created. */ @Override public void onCreate( final Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.main ); final String id = Settings.Secure.getString( getContentResolver(), Settings.Secure.ANDROID_ID ); inEmulator = id == null; inEmulator |= "sdk".equals( android.os.Build.PRODUCT ); inEmulator |= "google_sdk".equals( android.os.Build.PRODUCT ); info( "id: '" + id + "' inEmulator: " + inEmulator + " product: " + android.os.Build.PRODUCT ); // Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler(){ // public void uncaughtException( Thread thread, Throwable throwable ) { // String error = "Thread: " + thread + " throwable: " + throwable; // WigleAndroid.error( error ); // throwable.printStackTrace(); // WigleAndroid.writeError( thread, throwable ); // // throw new RuntimeException( error, throwable ); // WigleAndroid.this.finish(); // System.exit( -1 ); final Object stored = getLastNonConfigurationInstance(); if ( stored != null && stored instanceof WigleAndroid ) { // pry an orientation change, which calls destroy, but we set this in onRetainNonConfigurationInstance final WigleAndroid retained = (WigleAndroid) stored; this.listAdapter = retained.listAdapter; this.runNetworks = retained.runNetworks; this.gpsStatus = retained.gpsStatus; this.location = retained.location; this.wifiTimer = retained.wifiTimer; this.dbHelper = retained.dbHelper; this.serviceConnection = retained.serviceConnection; this.finishing = retained.finishing; this.savedStats = retained.savedStats; this.prevNewNetCount = retained.prevNewNetCount; this.soundPop = retained.soundPop; this.soundNewPop = retained.soundNewPop; this.wifiLock = retained.wifiLock; final TextView tv = (TextView) findViewById( R.id.stats ); tv.setText( savedStats ); } else { runNetworks = new HashSet<String>(); finishing = new AtomicBoolean( false ); // new run, reset final SharedPreferences prefs = this.getSharedPreferences( SHARED_PREFS, 0 ); Editor edit = prefs.edit(); edit.putFloat( PREF_DISTANCE_RUN, 0f ); edit.commit(); } numberFormat1 = NumberFormat.getNumberInstance( Locale.US ); if ( numberFormat1 instanceof DecimalFormat ) { ((DecimalFormat) numberFormat1).setMaximumFractionDigits( 1 ); } numberFormat8 = NumberFormat.getNumberInstance( Locale.US ); if ( numberFormat8 instanceof DecimalFormat ) { ((DecimalFormat) numberFormat8).setMaximumFractionDigits( 8 ); } setupService(); setupDatabase(); setupMaxidDebug(); setupUploadButton(); setupList(); setupSound(); setupWifi(); setupLocation(); } @Override public Object onRetainNonConfigurationInstance() { // return this whole class to copy data from return this; } @Override public void onPause() { info( "paused. networks: " + runNetworks.size() ); super.onPause(); } @Override public void onResume() { info( "resumed. networks: " + runNetworks.size() ); super.onResume(); } @Override public void onStart() { info( "start. networks: " + runNetworks.size() ); super.onStart(); } @Override public void onStop() { info( "stop. networks: " + runNetworks.size() ); super.onStop(); } @Override public void onRestart() { info( "restart. networks: " + runNetworks.size() ); super.onRestart(); } @Override public void onDestroy() { info( "destroy. networks: " + runNetworks.size() ); try { this.unregisterReceiver( wifiReceiver ); } catch ( final IllegalArgumentException ex ) { info( "wifiReceiver not registered: " + ex ); } // stop the service, so when we die it's both stopped and unbound and will die final Intent serviceIntent = new Intent( this, WigleService.class ); this.stopService( serviceIntent ); try { this.unbindService( serviceConnection ); } catch ( final IllegalArgumentException ex ) { info( "serviceConnection not registered: " + ex ); } if ( wifiLock != null && wifiLock.isHeld() ) { wifiLock.release(); } // clean up. if ( soundPop != null ) { soundPop.release(); } if ( soundNewPop != null ) { soundNewPop.release(); } super.onDestroy(); } @Override public void finish() { info( "finish. networks: " + runNetworks.size() ); finishing.set( true ); // close the db. not in destroy, because it'll still write after that. dbHelper.close(); final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if ( gpsStatusListener != null ) { locationManager.removeGpsStatusListener( gpsStatusListener ); } if ( locationListener != null ) { locationManager.removeUpdates( locationListener ); } try { this.unregisterReceiver( wifiReceiver ); } catch ( final IllegalArgumentException ex ) { info( "wifiReceiver not registered: " + ex ); } // stop the service, so when we die it's both stopped and unbound and will die final Intent serviceIntent = new Intent( this, WigleService.class ); this.stopService( serviceIntent ); try { this.unbindService( serviceConnection ); } catch ( final IllegalArgumentException ex ) { info( "serviceConnection not registered: " + ex ); } // release the lock before turning wifi off if ( wifiLock != null && wifiLock.isHeld() ) { wifiLock.release(); } final SharedPreferences prefs = this.getSharedPreferences( SHARED_PREFS, 0 ); final boolean wifiWasOff = prefs.getBoolean( PREF_WIFI_WAS_OFF, false ); // don't call on emulator, it crashes it if ( wifiWasOff && ! inEmulator ) { // well turn it of now that we're done final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); info( "turning back off wifi" ); wifiManager.setWifiEnabled( false ); } if ( tts != null ) { tts.shutdown(); } super.finish(); } /* Creates the menu items */ @Override public boolean onCreateOptionsMenu( final Menu menu ) { MenuItem item = menu.add(0, MENU_DASH, 0, "Dashboard"); item.setIcon( android.R.drawable.ic_menu_info_details ); item = menu.add(0, MENU_MAP, 0, "Map"); item.setIcon( android.R.drawable.ic_menu_mapmode ); item = menu.add(0, MENU_EXIT, 0, "Exit"); item.setIcon( android.R.drawable.ic_menu_close_clear_cancel ); item = menu.add(0, MENU_SETTINGS, 0, "Settings"); item.setIcon( android.R.drawable.ic_menu_preferences ); return true; } /* Handles item selections */ @Override public boolean onOptionsItemSelected( final MenuItem item ) { switch ( item.getItemId() ) { case MENU_SETTINGS: { info("start settings activity"); final Intent intent = new Intent( this, SettingsActivity.class ); this.startActivity( intent ); return true; } case MENU_MAP: { info("start map activity"); final Intent intent = new Intent( this, MappingActivity.class ); this.startActivity( intent ); return true; } case MENU_DASH: { info("start dashboard activity"); final Intent intent = new Intent( this, DashboardActivity.class ); this.startActivity( intent ); return true; } case MENU_EXIT: // stop the service, so when we die it's both stopped and unbound and will die final Intent serviceIntent = new Intent( this, WigleService.class ); this.stopService( serviceIntent ); // call over to finish finish(); // actually kill //System.exit( 0 ); return true; } return false; } // why is this even here? this is retarded. via: @Override public void onConfigurationChanged( final Configuration newConfig ) { super.onConfigurationChanged( newConfig ); setContentView( R.layout.main ); } private void setupDatabase() { // could be set by nonconfig retain if ( dbHelper == null ) { dbHelper = new DatabaseHelper( this ); dbHelper.open(); dbHelper.start(); } dbHelper.checkDB(); } private void setupList() { final LayoutInflater mInflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE ); // may have been set by nonconfig retain if ( listAdapter == null ) { listAdapter = new ArrayAdapter<Network>( this, R.layout.row ) { // @Override // public boolean areAllItemsEnabled() { // return false; // @Override // public boolean isEnabled( int position ) { // return false; @Override public View getView( final int position, final View convertView, final ViewGroup parent ) { // long start = System.currentTimeMillis(); View row; if ( null == convertView ) { row = mInflater.inflate( R.layout.row, parent, false ); } else { row = convertView; } final Network network = getItem(position); // info( "listing net: " + network.getBssid() ); final ImageView ico = (ImageView) row.findViewById( R.id.wepicon ); switch ( network.getCrypto() ) { case Network.CRYPTO_WEP: ico.setImageResource( R.drawable.wep_ico ); break; case Network.CRYPTO_WPA: ico.setImageResource( R.drawable.wpa_ico ); break; case Network.CRYPTO_NONE: ico.setImageResource( R.drawable.no_ico ); break; default: throw new IllegalArgumentException( "unhanded crypto: " + network.getCrypto() + " in network: " + network ); } TextView tv = (TextView) row.findViewById( R.id.ssid ); tv.setText( network.getSsid() ); tv = (TextView) row.findViewById( R.id.level_string ); int level = network.getLevel(); if ( level <= -90 ) { tv.setTextColor( COLOR_5 ); } else if ( level <= -80 ) { tv.setTextColor( COLOR_4 ); } else if ( level <= -70 ) { tv.setTextColor( COLOR_3 ); } else if ( level <= -60 ) { tv.setTextColor( COLOR_2 ); } else { tv.setTextColor( COLOR_1 ); } tv.setText( Integer.toString( level ) ); tv = (TextView) row.findViewById( R.id.detail ); String det = network.getDetail(); tv.setText( det ); // status( position + " view done. ms: " + (System.currentTimeMillis() - start ) ); return row; } }; } final ListView listView = (ListView) findViewById( R.id.ListView01 ); listView.setAdapter( listAdapter ); } private void setupWifi() { // warn about turning off network notification final String notifOn = Settings.Secure.getString(getContentResolver(), Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON ); if ( notifOn != null && "1".equals( notifOn ) ) { Toast.makeText( this, "For best results, unset \"Network notification\" in" + " \"Wireless & networks\"->\"Wi-Fi settings\"", Toast.LENGTH_LONG ).show(); } final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); final SharedPreferences prefs = this.getSharedPreferences( SHARED_PREFS, 0 ); final Editor edit = prefs.edit(); if ( ! wifiManager.isWifiEnabled() ) { // save so we can turn it back off when we exit edit.putBoolean( PREF_WIFI_WAS_OFF, true ); // just turn it on, but not in emulator cuz it crashes it if ( ! inEmulator ) { wifiManager.setWifiEnabled( true ); } } else { edit.putBoolean( PREF_WIFI_WAS_OFF, false ); } edit.commit(); // wifi scan listener wifiReceiver = new BroadcastReceiver(){ public void onReceive( final Context context, final Intent intent ){ final long start = System.currentTimeMillis(); final List<ScanResult> results = wifiManager.getScanResults(); // return can be null! long nonstopScanRequestTime = Long.MIN_VALUE; final long period = prefs.getLong( PREF_SCAN_PERIOD, 1000L ); if ( period == 0 ) { // treat as "continuous", so request scan in here wifiManager.startScan(); nonstopScanRequestTime = System.currentTimeMillis(); } final boolean showCurrent = prefs.getBoolean( PREF_SHOW_CURRENT, true ); if ( showCurrent ) { listAdapter.clear(); } final int preQueueSize = dbHelper.getQueueSize(); final boolean fastMode = dbHelper.isFastMode(); final CacheMap<String,Network> networkCache = getNetworkCache(); boolean somethingAdded = false; int resultSize = 0; int newForRun = 0; // can be null on shutdown if ( results != null ) { resultSize = results.size(); for ( ScanResult result : results ) { Network network = networkCache.get( result.BSSID ); if ( network == null ) { network = new Network( result ); networkCache.put( network.getBssid(), network ); } else { // cache hit, just set the level network.setLevel( result.level ); } final boolean added = runNetworks.add( result.BSSID ); if ( added ) { newForRun++; } somethingAdded |= added; // if we're showing current, or this was just added, put on the list if ( showCurrent || added ) { listAdapter.add( network ); // load test // for ( int i = 0; i< 10; i++) { // listAdapter.add( network ); } else { // not showing current, and not a new thing, go find the network and update the level // this is O(n), ohwell, that's why showCurrent is the default config. for ( int index = 0; index < listAdapter.getCount(); index++ ) { final Network testNet = listAdapter.getItem(index); if ( testNet.getBssid().equals( network.getBssid() ) ) { testNet.setLevel( result.level ); } } } if ( location != null && dbHelper != null ) { // if in fast mode, only add new-for-run stuff to the db queue if ( fastMode && ! added ) { info( "in fast mode, not adding seen-this-run: " + network.getBssid() ); } else { // loop for stress-testing // for ( int i = 0; i < 10; i++ ) { dbHelper.addObservation( network, location, added ); } } } } // check if there are more "New" nets final long newNetCount = dbHelper.getNewNetworkCount(); final boolean newNet = newNetCount > prevNewNetCount; prevNewNetCount = newNetCount; final boolean play = prefs.getBoolean( PREF_FOUND_SOUND, true ); if ( play && ! isMuted() ) { if ( newNet ) { if ( soundNewPop != null && ! soundNewPop.isPlaying() ) { // play sound on something new soundNewPop.start(); } else { info( "soundNewPop is playing or null" ); } } else if ( somethingAdded ) { if ( soundPop != null && ! soundPop.isPlaying() ) { // play sound on something new soundPop.start(); } else { info( "soundPop is playing or null" ); } } } // sort by signal strength listAdapter.sort( signalCompare ); // update stat final TextView tv = (TextView) findViewById( R.id.stats ); final StringBuilder builder = new StringBuilder( 40 ); builder.append( "Run: " ).append( runNetworks.size() ); builder.append( " New: " ).append( newNetCount ); builder.append( " DB: " ).append( dbHelper.getNetworkCount() ); builder.append( " Locs: " ).append( dbHelper.getLocationCount() ); savedStats = builder.toString(); tv.setText( savedStats ); // set the statics for the map WigleAndroid.lameStatic.savedStats = savedStats; WigleAndroid.lameStatic.runNets = runNetworks.size(); WigleAndroid.lameStatic.newNets = newNetCount; WigleAndroid.lameStatic.preQueueSize = preQueueSize; if ( newForRun > 0 && location != null ) { final GeoPoint geoPoint = new GeoPoint( location ); Integer points = lameStatic.trail.get( geoPoint ); if ( points == null ) { points = newForRun; } else { points += newForRun; } lameStatic.trail.put( geoPoint, points ); } // info( savedStats ); // notify listAdapter.notifyDataSetChanged(); final long now = System.currentTimeMillis(); if ( scanRequestTime <= 0 ) { // wasn't set, set to now scanRequestTime = now; } status( resultSize + " scan " + (now - scanRequestTime) + "ms, process " + (now - start) + "ms. DB Q: " + preQueueSize ); // we've shown it, reset it to the nonstop time above, or min_value if nonstop wasn't set. scanRequestTime = nonstopScanRequestTime; // do distance calcs if ( location != null && GPS_PROVIDER.equals( location.getProvider() ) ) { if ( prevGpsLocation != null ) { float dist = location.distanceTo( prevGpsLocation ); // info( "dist: " + dist ); if ( dist > 0f ) { final Editor edit = prefs.edit(); edit.putFloat( PREF_DISTANCE_RUN, dist + prefs.getFloat( PREF_DISTANCE_RUN, 0f ) ); edit.putFloat( PREF_DISTANCE_TOTAL, dist + prefs.getFloat( PREF_DISTANCE_TOTAL, 0f ) ); edit.commit(); } } // set for next time prevGpsLocation = location; } final long speechPeriod = prefs.getLong( PREF_SPEECH_PERIOD, DEFAULT_SPEECH_PERIOD ); if ( speechPeriod != 0 && now - previousTalkTime > speechPeriod * 1000L ) { String gps = ""; if ( location == null ) { gps = ", no gps fix"; } String queue = ""; if ( preQueueSize > 0 ) { queue = ", queue " + preQueueSize; } float dist = prefs.getFloat( PREF_DISTANCE_RUN, 0f ); String miles = ". From " + numberFormat1.format( dist / 1609.344f ) + " miles"; speak("run " + runNetworks.size() + ", new " + newNetCount + gps + queue + miles ); previousTalkTime = now; } } }; // register final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction( WifiManager.SCAN_RESULTS_AVAILABLE_ACTION ); this.registerReceiver( wifiReceiver, intentFilter ); if ( wifiLock == null ) { // lock the radio on wifiLock = wifiManager.createWifiLock( WifiManager.WIFI_MODE_SCAN_ONLY, WIFI_LOCK_NAME ); wifiLock.acquire(); } // might not be null on a nonconfig retain if ( wifiTimer == null ) { wifiTimer = new Handler(); final Runnable mUpdateTimeTask = new Runnable() { public void run() { // make sure the app isn't trying to finish if ( ! finishing.get() ) { // info( "timer start scan" ); wifiManager.startScan(); if ( scanRequestTime <= 0 ) { scanRequestTime = System.currentTimeMillis(); } long period = prefs.getLong( PREF_SCAN_PERIOD, 1000L); // check if set to "continuous" if ( period == 0L ) { // set to default here, as a scan will also be requested on the scan result listener period = 1000L; } // info("wifitimer: " + period ); wifiTimer.postDelayed( this, period ); } else { info( "finishing timer" ); } } }; wifiTimer.removeCallbacks( mUpdateTimeTask ); wifiTimer.postDelayed( mUpdateTimeTask, 100 ); // starts scan, sends event when done final boolean scanOK = wifiManager.startScan(); if ( scanRequestTime <= 0 ) { scanRequestTime = System.currentTimeMillis(); } info( "startup finished. wifi scanOK: " + scanOK ); } } private void speak( final String string ) { if ( ! isMuted() && tts != null ) { tts.speak( string ); } } private void setupLocation() { // set on UI if we already have one updateLocationData( (Location) null ); final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if ( ! locationManager.isProviderEnabled( GPS_PROVIDER ) ) { Toast.makeText( this, "Please turn on GPS", Toast.LENGTH_SHORT ).show(); final Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS ); startActivity(myIntent); } // emulator crashes if you ask this if ( ! inEmulator && ! locationManager.isProviderEnabled( NETWORK_PROVIDER ) ) { Toast.makeText( this, "For best results, set \"Use wireless networks\" in \"Location & security\"", Toast.LENGTH_LONG ).show(); } gpsStatusListener = new Listener(){ public void onGpsStatusChanged( final int event ) { updateLocationData( (Location) null ); } }; locationManager.addGpsStatusListener( gpsStatusListener ); final List<String> providers = locationManager.getAllProviders(); locationListener = new LocationListener(){ public void onLocationChanged( final Location newLocation ) { updateLocationData( newLocation ); } public void onProviderDisabled( final String provider ) {} public void onProviderEnabled( final String provider ) {} public void onStatusChanged( final String provider, final int status, final Bundle extras ) {} }; for ( String provider : providers ) { info( "provider: " + provider ); locationManager.requestLocationUpdates( provider, 1000L, 0, locationListener ); } } /** newLocation can be null */ private void updateLocationData( final Location newLocation ) { final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // see if we have new data gpsStatus = locationManager.getGpsStatus( gpsStatus ); final int satCount = getSatCount(); boolean newOK = newLocation != null; final boolean locOK = locationOK( location, satCount ); final long now = System.currentTimeMillis(); if ( newOK ) { if ( NETWORK_PROVIDER.equals( newLocation.getProvider() ) ) { // save for later, in case we lose gps networkLocation = newLocation; lastNetworkLocationTime = now; } else { lastLocationTime = now; // make sure there's enough sats on this new gps location newOK = locationOK( newLocation, satCount ); } } if ( inEmulator && newLocation != null ) { newOK = true; } final boolean netLocOK = locationOK( networkLocation, satCount ); boolean wasProviderChange = false; if ( ! locOK ) { if ( newOK ) { wasProviderChange = true; if ( location != null && ! location.getProvider().equals( newLocation.getProvider() ) ) { wasProviderChange = false; } location = newLocation; } else if ( netLocOK ) { location = networkLocation; wasProviderChange = true; } else if ( location != null ) { // transition to null info( "nulling location: " + location ); location = null; wasProviderChange = true; } } else if ( newOK && GPS_PROVIDER.equals( newLocation.getProvider() ) ) { if ( NETWORK_PROVIDER.equals( location.getProvider() ) ) { // this is an upgrade from network to gps wasProviderChange = true; } location = newLocation; } else if ( newOK && NETWORK_PROVIDER.equals( newLocation.getProvider() ) ) { if ( NETWORK_PROVIDER.equals( location.getProvider() ) ) { // just a new network provided location over an old one location = newLocation; } } // for maps. so lame! lameStatic.location = location; if ( wasProviderChange ) { info( "wasProviderChange: run: " + this.runNetworks.size() + " satCount: " + satCount + " newOK: " + newOK + " locOK: " + locOK + " netLocOK: " + netLocOK + " wasProviderChange: " + wasProviderChange + (newOK ? " newProvider: " + newLocation.getProvider() : "") + (locOK ? " locProvider: " + location.getProvider() : "") + " newLocation: " + newLocation ); } if ( wasProviderChange ) { final String announce = location == null ? "Lost Location" : "Now have location from \"" + location.getProvider() + "\""; Toast.makeText( this, announce, Toast.LENGTH_SHORT ).show(); final SharedPreferences prefs = this.getSharedPreferences( SHARED_PREFS, 0 ); final boolean speechGPS = prefs.getBoolean( PREF_SPEECH_GPS, true ); if ( speechGPS ) { // no quotes or the voice pauses final String speakAnnounce = location == null ? "Lost Location" : "Now have location from " + location.getProvider() + "."; speak( speakAnnounce ); } } // update the UI setLocationUI(); } private boolean locationOK( final Location location, final int satCount ) { boolean retval = false; final long now = System.currentTimeMillis(); if ( location == null ) { // bad! } else if ( GPS_PROVIDER.equals( location.getProvider() ) ) { if ( satCount < 3 ) { if ( satCountLowTime == null ) { satCountLowTime = now; } } else { // plenty of sats satCountLowTime = null; } boolean gpsLost = satCountLowTime != null && (now - satCountLowTime) > GPS_TIMEOUT; gpsLost |= now - lastLocationTime > GPS_TIMEOUT; retval = ! gpsLost; } else if ( NETWORK_PROVIDER.equals( location.getProvider() ) ) { boolean gpsLost = now - lastNetworkLocationTime > NET_LOC_TIMEOUT; retval = ! gpsLost; } return retval; } private int getSatCount() { int satCount = 0; if ( gpsStatus != null ) { for ( GpsSatellite sat : gpsStatus.getSatellites() ) { if ( sat.usedInFix() ) { satCount++; } } } return satCount; } private void setLocationUI() { if ( gpsStatus != null ) { final int satCount = getSatCount(); final TextView tv = (TextView) this.findViewById( R.id.LocationTextView06 ); tv.setText( "Sats: " + satCount ); } TextView tv = (TextView) this.findViewById( R.id.LocationTextView01 ); tv.setText( "Lat: " + (location == null ? " (Waiting for GPS sync..)" : numberFormat8.format( location.getLatitude() ) ) ); tv = (TextView) this.findViewById( R.id.LocationTextView02 ); tv.setText( "Lon: " + (location == null ? "" : numberFormat8.format( location.getLongitude() ) ) ); tv = (TextView) this.findViewById( R.id.LocationTextView03 ); tv.setText( "Speed: " + (location == null ? "" : numberFormat1.format( location.getSpeed() * 2.23693629f ) + "mph" ) ); tv = (TextView) this.findViewById( R.id.LocationTextView04 ); tv.setText( location == null ? "" : ("+/- " + numberFormat1.format( location.getAccuracy() ) + "m") ); tv = (TextView) this.findViewById( R.id.LocationTextView05 ); tv.setText( location == null ? "" : ("Alt: " + numberFormat1.format( location.getAltitude() ) + "m") ); } private void setupUploadButton() { final Button button = (Button) findViewById( R.id.upload_button ); button.setOnClickListener( new OnClickListener() { public void onClick( final View view ) { uploadFile( WigleAndroid.this, dbHelper ); } }); } private void setupService() { final Intent serviceIntent = new Intent( this, WigleService.class ); // could be set by nonconfig retain if ( serviceConnection == null ) { final ComponentName compName = startService( serviceIntent ); if ( compName == null ) { WigleAndroid.error( "startService() failed!" ); } else { WigleAndroid.info( "service started ok: " + compName ); } serviceConnection = new ServiceConnection(){ public void onServiceConnected( final ComponentName name, final IBinder iBinder ) { WigleAndroid.info( name + " service connected" ); } public void onServiceDisconnected( final ComponentName name ) { WigleAndroid.info( name + " service disconnected" ); } }; } int flags = 0; this.bindService( serviceIntent, serviceConnection, flags ); } private void setupSound() { // could have been retained if ( soundPop == null ) { soundPop = createMediaPlayer( R.raw.pop ); } if ( soundNewPop == null ) { soundNewPop = createMediaPlayer( R.raw.newpop ); } audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); // make volume change "media" this.setVolumeControlStream( AudioManager.STREAM_MUSIC ); if ( TTS.hasTTS() ) { tts = new TTS( this ); } final Button mute = (Button) this.findViewById(R.id.mute); final SharedPreferences prefs = this.getSharedPreferences(SHARED_PREFS, 0); final boolean muted = prefs.getBoolean(PREF_MUTED, false); if ( muted ) { mute.setText("Play"); } mute.setOnClickListener(new OnClickListener(){ public void onClick( final View buttonView ) { boolean muted = prefs.getBoolean(PREF_MUTED, false); muted = ! muted; Editor editor = prefs.edit(); editor.putBoolean( PREF_MUTED, muted ); editor.commit(); if ( muted ) { mute.setText("Play"); } else { mute.setText("Mute"); } } }); } /** * create a mediaplayer for a given raw resource id. * @param soundId the R.raw. id for a given sound * @return the mediaplayer for soundId or null if it could not be created. */ private MediaPlayer createMediaPlayer( final int soundId ) { final MediaPlayer sound = createMp( this, soundId ); if ( sound == null ) { info( "sound null from media player" ); return null; } // try to figure out why sounds stops after a while sound.setOnErrorListener( new OnErrorListener() { public boolean onError( final MediaPlayer mp, final int what, final int extra ) { String whatString = null; switch ( what ) { case MediaPlayer.MEDIA_ERROR_UNKNOWN: whatString = "error unknown"; break; case MediaPlayer.MEDIA_ERROR_SERVER_DIED: whatString = "server died"; break; default: whatString = "not defined"; } info( "media player error \"" + whatString + "\" what: " + what + " extra: " + extra + " mp: " + mp ); return false; } } ); return sound; } /** * externalize the file from a given resource id (if it dosen't already exist), write to our dir if there is one. * @param context the context to use * @param resid the resource id * @param name the file name to write out * @return the uri of a file containing resid's resource */ private static Uri resToFile( final Context context, final int resid, final String name ) throws IOException { // throw it in our bag of fun. String openString = name; final boolean hasSD = hasSD(); if ( hasSD ) { final String filepath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/wiglewifi/"; final File path = new File( filepath ); path.mkdirs(); openString = filepath + name; } final File f = new File( openString ); // see if it exists already if ( ! f.exists() ) { info("causing "+f.getCanonicalPath()+" to be made"); // make it happen: f.createNewFile(); InputStream is = null; FileOutputStream fos = null; try { is = context.getResources().openRawResource( resid ); if ( hasSD ) { fos = new FileOutputStream( f ); } else { // XXX: should this be using openString instead? baroo? fos = context.openFileOutput( name, Context.MODE_WORLD_READABLE ); } final byte[] buff = new byte[ 1024 ]; int rv = -1; while( ( rv = is.read( buff ) ) > -1 ) { fos.write( buff, 0, rv ); } } finally { if ( fos != null ) { fos.close(); } if ( is != null ) { is.close(); } } } return Uri.fromFile( f ); } /** * create a media player (trying several paths if available) * @param context the context to use * @param resid the resource to use * @return the media player for resid (or null if it wasn't creatable) */ private static MediaPlayer createMp( final Context context, final int resid ) { try { MediaPlayer mp = MediaPlayer.create( context, resid ); // this can fail for many reasons, but android 1.6 on archos5 definitely hates creating from resource if ( mp == null ) { Uri sounduri; // XXX: find a better way? baroo. if ( resid == R.raw.pop ) { sounduri = resToFile( context, resid, "pop.wav" ); } else if ( resid == R.raw.newpop ) { sounduri = resToFile( context, resid, "newpop.wav" ); } else { info( "unknown raw sound id:"+resid ); return null; } mp = MediaPlayer.create( context, sounduri ); // may still end up null } return mp; } catch (IOException ex) { error("ioe create failed:", ex); // fall through } catch (IllegalArgumentException ex) { error("iae create failed:", ex); // fall through } catch (SecurityException ex) { error("se create failed:", ex); // fall through } catch ( Resources.NotFoundException ex ) { error("rnfe create failed("+resid+"):", ex ); } return null; } @SuppressWarnings("unused") private boolean isRingerOn() { boolean retval = false; if ( audioManager != null ) { retval = audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL; } return retval; } private boolean isMuted() { boolean retval = this.getSharedPreferences(SHARED_PREFS, 0).getBoolean(PREF_MUTED, false); // info( "ismuted: " + retval ); return retval; } private static void uploadFile( final Context context, final DatabaseHelper dbHelper ){ info( "upload file" ); final FileUploaderTask task = new FileUploaderTask( context, dbHelper ); task.start(); } private void status( String status ) { // info( status ); final TextView tv = (TextView) findViewById( R.id.status ); tv.setText( status ); } public static void sleep( final long sleep ) { try { Thread.sleep( sleep ); } catch ( final InterruptedException ex ) { // no worries } } public static void info( final String value ) { Log.i( LOG_TAG, Thread.currentThread().getName() + "] " + value ); } public static void error( final String value ) { Log.e( LOG_TAG, Thread.currentThread().getName() + "] " + value ); } public static void error( final String value, final Throwable t ) { Log.e( LOG_TAG, Thread.currentThread().getName() + "] " + value, t ); } /** * get the per-thread network LRU cache * @return per-thread network cache */ public static CacheMap<String,Network> getNetworkCache() { return networkCache.get(); } public static void writeError( final Thread thread, final Throwable throwable ) { try { final String error = "Thread: " + thread + " throwable: " + throwable; error( error ); if ( hasSD() ) { File file = new File( Environment.getExternalStorageDirectory().getCanonicalPath() + "/wiglewifi/" ); file.mkdirs(); file = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/wiglewifi/errorstack_" + System.currentTimeMillis() + ".txt" ); if ( ! file.exists() ) { file.createNewFile(); } final FileOutputStream fos = new FileOutputStream( file ); fos.write( error.getBytes( ENCODING ) ); throwable.printStackTrace( new PrintStream( fos ) ); fos.close(); } } catch ( final Exception ex ) { error( "error logging error: " + ex ); ex.printStackTrace(); } } public static boolean hasSD() { File sdCard = null; try { sdCard = new File( Environment.getExternalStorageDirectory().getCanonicalPath() + "/" ); } catch ( final IOException ex ) { // ohwell } return sdCard != null && sdCard.exists() && sdCard.isDirectory() && sdCard.canRead() && sdCard.canWrite(); } private void setupMaxidDebug() { final SharedPreferences prefs = WigleAndroid.this.getSharedPreferences( SHARED_PREFS, 0 ); final long maxid = prefs.getLong( PREF_DB_MARKER, -1L ); if ( maxid == -1L ) { // load up the local value dbHelper.getLocationCountFromDB(); final long loccount = dbHelper.getLocationCount(); if ( loccount > 0 ) { // there is no preference set, yet there are locations, this is likely // a developer testing a new install on an old db, so set the pref. info( "setting db marker to: " + loccount ); final Editor edit = prefs.edit(); edit.putLong( PREF_DB_MARKER, loccount ); edit.commit(); } } } }
package org.nuxeo.ecm.platform.ec.notification; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.mail.MessagingException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DataModel; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.NuxeoGroup; import org.nuxeo.ecm.core.api.NuxeoPrincipal; import org.nuxeo.ecm.core.api.blobholder.BlobHolder; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.EventBundle; import org.nuxeo.ecm.core.event.EventContext; import org.nuxeo.ecm.core.event.PostCommitFilteringEventListener; import org.nuxeo.ecm.core.event.impl.DocumentEventContext; import org.nuxeo.ecm.platform.ec.notification.email.EmailHelper; import org.nuxeo.ecm.platform.ec.notification.service.NotificationService; import org.nuxeo.ecm.platform.ec.notification.service.NotificationServiceHelper; import org.nuxeo.ecm.platform.notification.api.Notification; import org.nuxeo.ecm.platform.url.DocumentViewImpl; import org.nuxeo.ecm.platform.url.api.DocumentView; import org.nuxeo.ecm.platform.url.api.DocumentViewCodecManager; import org.nuxeo.ecm.platform.usermanager.UserManager; import org.nuxeo.runtime.api.Framework; public class NotificationEventListener implements PostCommitFilteringEventListener { private static final Log log = LogFactory.getLog(NotificationEventListener.class); private DocumentViewCodecManager docLocator; private UserManager userManager; private EmailHelper emailHelper = new EmailHelper(); private NotificationService notificationService = NotificationServiceHelper.getNotificationService(); @Override public boolean acceptEvent(Event event) { if (notificationService == null) { return false; } return notificationService.getNotificationEventNames().contains(event.getName()); } @Override public void handleEvent(EventBundle events) throws ClientException { if (notificationService == null) { log.error("Unable to get NotificationService, exiting"); return; } boolean processEvents = false; for (String name : notificationService.getNotificationEventNames()) { if (events.containsEventName(name)) { processEvents = true; break; } } if (! processEvents) { return; } for (Event event : events) { Boolean block = (Boolean)event.getContext().getProperty(NotificationConstants.DISABLE_NOTIFICATION_SERVICE); if (block != null && block) { // ignore the event - we are blocked by the caller continue; } List<Notification> notifs = notificationService.getNotificationsForEvents(event.getName()); if (notifs != null && !notifs.isEmpty()) { try { handleNotifications(event, notifs); } catch (Exception e) { log.error("Error during Notification processing for event " + event.getName(), e); } } } } protected void handleNotifications(Event event, List<Notification> notifs) throws Exception { EventContext ctx = event.getContext(); DocumentEventContext docCtx = null; if (ctx instanceof DocumentEventContext) { docCtx = (DocumentEventContext) ctx; } else { log.warn("Can not handle notification on a event that is not bound to a DocumentEventContext"); return; } CoreSession coreSession = event.getContext().getCoreSession(); Map<String, Serializable> properties = event.getContext().getProperties(); Map<Notification, List<String>> targetUsers = new HashMap<Notification, List<String>>(); for (NotificationListenerVeto veto : notificationService.getNotificationVetos()) { if (!veto.accept(event)) { return; } } for(NotificationListenerHook hookListener:notificationService.getListenerHooks()) { hookListener.handleNotifications(event); } gatherConcernedUsersForDocument(coreSession, docCtx.getSourceDocument(), notifs, targetUsers); for (Notification notif : targetUsers.keySet()) { if (!notif.getAutoSubscribed()) { for (String user : targetUsers.get(notif)) { sendNotificationSignalForUser(notif, user, event, docCtx); } } else { Object recipientProperty = properties.get(NotificationConstants.RECIPIENTS_KEY); String[] recipients = null; if (recipientProperty != null) { if (recipientProperty instanceof String[]) { recipients = (String[]) properties.get(NotificationConstants.RECIPIENTS_KEY); } else if (recipientProperty instanceof String ) { recipients = new String[1]; recipients[0] = (String) recipientProperty; } } if (recipients == null) { continue; } Set<String> users = new HashSet<String>(); for (String recipient : recipients) { if (recipient == null) { continue; } if (recipient.contains(NuxeoPrincipal.PREFIX)) { users.add(recipient.replace(NuxeoPrincipal.PREFIX, "")); } else if (recipient.contains(NuxeoGroup.PREFIX)) { List<String> groupMembers = getGroupMembers(recipient.replace( NuxeoGroup.PREFIX, "")); for (String member : groupMembers) { users.add(member); } } else { users.add(recipient); } } for (String user : users) { sendNotificationSignalForUser(notif, user, event, docCtx); } } } } protected UserManager getUserManager() { if (userManager == null) { try { userManager = Framework.getService(UserManager.class); } catch (Exception e) { throw new IllegalStateException( "UserManager service not deployed.", e); } } return userManager; } protected List<String> getGroupMembers(String groupId) throws ClientException { return getUserManager().getUsersInGroupAndSubGroups(groupId); } private void sendNotificationSignalForUser(Notification notification, String subscriptor, Event event, DocumentEventContext ctx) throws ClientException { log.debug("Producing notification message."); Map<String, Serializable> eventInfo = ctx.getProperties(); DocumentModel doc = ctx.getSourceDocument(); String author = ctx.getPrincipal().getName(); Calendar created = (Calendar) ctx.getSourceDocument().getPropertyValue( "dc:created"); eventInfo.put(NotificationConstants.DESTINATION_KEY, subscriptor); eventInfo.put(NotificationConstants.NOTIFICATION_KEY, notification); eventInfo.put(NotificationConstants.DOCUMENT_ID_KEY, doc.getId()); eventInfo.put(NotificationConstants.DATE_TIME_KEY, new Date(event.getTime())); eventInfo.put(NotificationConstants.AUTHOR_KEY, author); eventInfo.put(NotificationConstants.DOCUMENT_VERSION, doc.getVersionLabel()); eventInfo.put(NotificationConstants.DOCUMENT_STATE, doc.getCurrentLifeCycleState()); eventInfo.put(NotificationConstants.DOCUMENT_CREATED, created.getTime()); StringBuilder userUrl = new StringBuilder(); userUrl.append( notificationService.getServerUrlPrefix()).append( "user/").append(ctx.getPrincipal().getName()); eventInfo.put(NotificationConstants.USER_URL_KEY, userUrl.toString()); eventInfo.put(NotificationConstants.DOCUMENT_LOCATION, doc.getPathAsString()); // Main file link for downloading BlobHolder bh = doc.getAdapter(BlobHolder.class); if (bh != null && bh.getBlob() != null) { StringBuilder docMainFile = new StringBuilder(); docMainFile.append( notificationService.getServerUrlPrefix()).append( "nxfile/default/").append(doc.getId()).append( "/blobholder:0/").append(bh.getBlob().getFilename()); eventInfo.put(NotificationConstants.DOCUMENT_MAIN_FILE, docMainFile.toString()); } if (!isDeleteEvent(event.getName())) { DocumentView docView = new DocumentViewImpl(doc); DocumentViewCodecManager docLocator = getDocLocator(); if (docLocator != null) { eventInfo.put( NotificationConstants.DOCUMENT_URL_KEY, getDocLocator().getUrlFromDocumentView( docView, true, notificationService.getServerUrlPrefix())); } else { eventInfo.put(NotificationConstants.DOCUMENT_URL_KEY, ""); } eventInfo.put(NotificationConstants.DOCUMENT_TITLE_KEY, doc.getTitle()); } if (isInterestedInNotification(notification)) { try { sendNotification(event, ctx); if (log.isDebugEnabled()) { log.debug("notification " + notification.getName() + " sent to " + notification.getSubject()); } } catch (ClientException e) { log.error( "An error occurred while trying to send user notification", e); } } } public void sendNotification(Event event, DocumentEventContext ctx) throws ClientException { String eventId = event.getName(); log.debug("Received a message for notification sender with eventId : " + eventId); Map<String, Serializable> eventInfo = ctx.getProperties(); String userDest = (String) eventInfo.get(NotificationConstants.DESTINATION_KEY); NotificationImpl notif = (NotificationImpl) eventInfo.get(NotificationConstants.NOTIFICATION_KEY); // send email NuxeoPrincipal recepient = NotificationServiceHelper.getUsersService().getPrincipal( userDest); if (recepient == null) { log.error("Couldn't find user: " + userDest + " to send her a mail."); return; } // XXX hack, principals have only one model DataModel model = recepient.getModel().getDataModels().values().iterator().next(); String email = (String) model.getData("email"); if (email == null || "".equals(email)) { log.error("No email found for user: " + userDest); return; } String subjectTemplate = notif.getSubjectTemplate(); String mailTemplate = null; // mail template can be dynamically computed from a MVEL expression if (notif.getTemplateExpr() != null) { mailTemplate = emailHelper.evaluateMvelExpresssion( notif.getTemplateExpr(), eventInfo); } // if there is no mailTemplate evaluated, use the defined one if (StringUtils.isEmpty(mailTemplate)) { mailTemplate = notif.getTemplate(); } log.debug("email: " + email); log.debug("mail template: " + mailTemplate); log.debug("subject template: " + subjectTemplate); Map<String, Object> mail = new HashMap<String, Object>(); mail.put("mail.to", email); String authorUsername = (String) eventInfo.get(NotificationConstants.AUTHOR_KEY); if (authorUsername != null) { NuxeoPrincipal author = NotificationServiceHelper.getUsersService().getPrincipal( authorUsername); mail.put(NotificationConstants.PRINCIPAL_AUTHOR_KEY, author); } mail.put(NotificationConstants.DOCUMENT_KEY, ctx.getSourceDocument()); String subject = notif.getSubject() == null ? NotificationConstants.NOTIFICATION_KEY : notif.getSubject(); subject = notificationService.getEMailSubjectPrefix() + subject; mail.put("subject", subject); mail.put("template", mailTemplate); mail.put("subjectTemplate", subjectTemplate); // Transferring all data from event to email for (String key : eventInfo.keySet()) { mail.put(key, eventInfo.get(key) == null ? "" : eventInfo.get(key)); log.debug("Mail prop: " + key); } mail.put(NotificationConstants.EVENT_ID_KEY, eventId); try { emailHelper.sendmail(mail); } catch (MessagingException e) { log.warn("Failed to send notification email to '" + email + "': " + e.getClass().getName() + ": " + e.getMessage()); } catch (Exception e) { if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder( "Failed to send email with these properties:\n"); for (String key : mail.keySet()) { sb.append("\t " + key + ": " + mail.get(key) + "\n"); } log.debug(sb.toString()); } throw new ClientException("Failed to send notification email ", e); } } /** * Adds the concerned users to the list of targeted users for these * notifications. */ private void gatherConcernedUsersForDocument(CoreSession coreSession, DocumentModel doc, List<Notification> notifs, Map<Notification, List<String>> targetUsers) throws Exception { if (doc.getPath().segmentCount() > 1) { log.debug("Searching document: " + doc.getName()); getInterstedUsers(doc, notifs, targetUsers); if (doc.getParentRef() != null && coreSession.exists(doc.getParentRef())) { DocumentModel parent = getDocumentParent(coreSession, doc); gatherConcernedUsersForDocument(coreSession, parent, notifs, targetUsers); } } } private DocumentModel getDocumentParent(CoreSession coreSession, DocumentModel doc) throws ClientException { if (doc == null) { return null; } return coreSession.getDocument(doc.getParentRef()); } private void getInterstedUsers(DocumentModel doc, List<Notification> notifs, Map<Notification, List<String>> targetUsers) throws Exception { for (Notification notification : notifs) { if (!notification.getAutoSubscribed()) { List<String> userGroup = notificationService.getSubscribers( notification.getName(), doc.getId()); for (String subscriptor : userGroup) { if (subscriptor != null) { if (isUser(subscriptor)) { storeUserForNotification(notification, subscriptor.substring(5), targetUsers); } else { // it is a group - get all users and send // notifications to them List<String> usersOfGroup = getGroupMembers(subscriptor.substring(6)); if (usersOfGroup != null && !usersOfGroup.isEmpty()) { for (String usr : usersOfGroup) { storeUserForNotification(notification, usr, targetUsers); } } } } } } else { // An automatic notification happens // should be sent to interested users targetUsers.put(notification, new ArrayList<String>()); } } } private static void storeUserForNotification(Notification notification, String user, Map<Notification, List<String>> targetUsers) { List<String> subscribedUsers = targetUsers.get(notification); if (subscribedUsers == null) { targetUsers.put(notification, new ArrayList<String>()); } if (!targetUsers.get(notification).contains(user)) { targetUsers.get(notification).add(user); } } private boolean isDeleteEvent(String eventId) { List<String> deletionEvents = new ArrayList<String>(); deletionEvents.add("aboutToRemove"); deletionEvents.add("documentRemoved"); return deletionEvents.contains(eventId); } private boolean isUser(String subscriptor) { return subscriptor != null && subscriptor.startsWith("user:"); } public boolean isInterestedInNotification(Notification notif) { return notif != null && "email".equals(notif.getChannel()); } public DocumentViewCodecManager getDocLocator() { if (docLocator == null) { try { docLocator = Framework.getService(DocumentViewCodecManager.class); if (docLocator == null) { log.warn("Could not get service for document view manager"); } } catch (Exception e) { log.info("Could not get service for document view manager"); } } return docLocator; } public EmailHelper getEmailHelper() { return emailHelper; } public void setEmailHelper(EmailHelper emailHelper) { this.emailHelper = emailHelper; } }
package org.adligo.i.log.client; import org.adligo.i.util.client.CollectionFactory; import org.adligo.i.util.client.Event; import org.adligo.i.util.client.I_Collection; import org.adligo.i.util.client.I_Event; import org.adligo.i.util.client.I_ImmutableMap; import org.adligo.i.util.client.I_Iterator; import org.adligo.i.util.client.I_Listener; import org.adligo.i.util.client.I_Map; import org.adligo.i.util.client.I_SystemOutput; import org.adligo.i.util.client.I_ThreadPopulator; import org.adligo.i.util.client.InstanceForName; import org.adligo.i.util.client.MapFactory; import org.adligo.i.util.client.Platform; import org.adligo.i.util.client.PropertyFactory; import org.adligo.i.util.client.PropertyFileReadException; import org.adligo.i.util.client.StringUtils; import org.adligo.i.util.client.SystemOutput; import org.adligo.i.util.client.ThreadPopulatorFactory; import org.adligo.i.util.client.ThrowableHelperFactory; /** * this holds the properties which need to be used to init the * Log Impl (SimpleLog in this case) * @author scott * */ public class LogPlatform implements I_Listener { public static final String NET_LOG_URL = "net_log_url"; /** * this is a key for adligo_log.properties * that tells the LogPlatform what log factory to use * * NOTE this was done after j2se, j2me and gwt log impls * and currently only supports log4j and java.util.logging * * obviously you can't use log4j on gwt or j2me, * but you can send those messages to a log servlet * and have them log there over http * * exc. * read Samudra Gupta * Logging in Java * * written before i_log * */ public static final String LOG_FACTORY = "log_factory"; protected static final LogPlatform instance = new LogPlatform(); private static String logConfigName = null; private static boolean debug = false; private static boolean trace = false; private static I_Map props = null; private static I_LogDispatcher dispatcher = null; protected static boolean isInit = false; protected static boolean isInitLevelsSet = false; private static I_LogFactory customFactory = null; private static I_Formatter formatter; private static I_ThreadPopulator threadPopulator = null; private static I_SystemOutput out = SystemOutput.INSTANCE; public void onEvent(I_Event p) { if (debug) { System.out.println("entering onEvent in LogPlatform"); } Object value = p.getValue(); props = (I_Map) p.getValue(); if (p.threwException()) { Throwable ex = p.getException(); try { PropertyFileReadException pfre = (PropertyFileReadException) ex; out.err("error reading file '" + pfre.getFileName() + "' system file '" + pfre.getAttemptedSystemFileName() + "' using defaults;"); props = getDefaults(); out.err("using defaults " + props); } catch (ClassCastException x) { out.exception(p.getException()); } } synchronized (LogPlatform.class) { I_Iterator it = props.getKeysIterator(); removeCommentLines(it); String logFactory = (String) props.get(LOG_FACTORY); if ( !StringUtils.isEmpty(logFactory)) { switch (Platform.getPlatform()) { case Platform.GWT: out.err("LogPlatform can't set dynamic log_factory from adligo_log.properties on GWT," + " you must use the org.adligo.gwt.util.client.GwtLogFactory class instead. "); break; case Platform.JME: out.err("LogPlatform can't set dynamic log_factory from adligo_log.properties on J2ME."); break; case Platform.JSE: I_LogFactory fac = (I_LogFactory) InstanceForName.create(logFactory); out.err("LogPlatform setting log_factory " + logFactory + " instance " + fac); if (fac != null) { LogFactory.setLogFactoryInstance(fac); } else { Exception ex = new Exception("log_factory is null, because your code" + " needs to call LogPlatform.init(String name, I_LogFactory p)" + " with a valid instance of your logFactory " + logFactory + "!"); ThrowableHelperFactory.fillInStackTrace(ex); out.exception(ex); } break; } } } if (!isInitLevelsSet) { if (debug) { System.out.println("property file looked like..."); I_Iterator it = props.getKeysIterator(); } String format = (String) props.get("format"); if (!StringUtils.isEmpty(format)) { formatter.setFormatString(format); } LogFactory.setInitalLogLevels(props, customFactory); isInitLevelsSet = true; } else { LogFactory.resetLogLevels(); } } private void removeCommentLines(I_Iterator it) { //remove item with I_Collection items = CollectionFactory.create(); while (it.hasNext()) { items.add(it.next()); } it = items.getIterator(); while (it.hasNext()) { String key = (String) it.next(); if (key.indexOf(" if (debug) { log("LogPlatform", " removing property " + key); } props.remove(key); } } } public synchronized static final void init(String pFileName, I_LogFactory p) { if (!isInit) { formatter = new SimpleFormatter(); logConfigName = pFileName; customFactory = p; PropertyFactory.get(logConfigName, instance); threadPopulator = ThreadPopulatorFactory.getThreadPopulator(); //wait for file return event to set the LogFactory isInit = true; } else { throw new RuntimeException("LogPlatform has already been initialized."); } } /** * * @param pFileName * a relative url (on GWT) * or a file from the filesystem or classpath */ public synchronized static final void resetLevels(String pFileName) { out.out("Reading in log file " + pFileName); logConfigName = pFileName; PropertyFactory.get(pFileName, instance); } /** * * @param pFileName * a relative url (on GWT) * or a file from the filesystem or classpath */ public static final void init(String pFileName) { checkInit(); logConfigName = pFileName; init(); } public static final void init(boolean p_debug) { checkInit(); debug = p_debug; init(getFileName()); } public static final void init() { checkInit(); init(getFileName(), null); } private static void checkInit() { if (!Platform.isInit()) { throw new RuntimeException("Please initalize your platform BEFORE the LogPlatform," + " for instance JSEPlatform.init(), GWTPlatform.init(), J2MEPlatform.init. "); } } private static String getFileName() { if (logConfigName != null) { if (Platform.getPlatform() == Platform.GWT) { return logConfigName; } else { if (logConfigName.startsWith("/")) { return logConfigName; } else { return "/" + logConfigName; } } } else if (Platform.getPlatform() == Platform.GWT) { return "adligo_log.properties"; } else { return "/adligo_log.properties"; } } public synchronized static I_ImmutableMap getProps() { I_ImmutableMap toRet = MapFactory.create(props); return toRet; } public synchronized static I_LogDispatcher getDispatcher() { return dispatcher; } public synchronized static void setDispatcher(I_LogDispatcher dispatcher) { LogPlatform.dispatcher = dispatcher; } /** * Only call after init has been called! * * this rereads the property file and sets all the log levels to match with it */ public synchronized static final void reloadConfig() { PropertyFactory.get(logConfigName, instance); //onEvent is called next through the callback } public synchronized static final void loadConfig(String fileName) { logConfigName = fileName; PropertyFactory.get(logConfigName, instance); //onEvent is called next through the callback } public synchronized static boolean isDebug() { return debug; } public synchronized static void setDebug(boolean log) { LogPlatform.debug = log; } public synchronized static boolean isTrace() { return trace; } public synchronized static void setTrace(boolean trace) { LogPlatform.trace = trace; } public static void log(String clazz, String message) { System.out.println(clazz + " due to LogPlatform.isDebug() " + message); } public static void trace(String clazz, String message) { System.err.println(clazz + " due to LogPlatform.isTrace() " + message); } public static void trace(String clazz, Exception message) { System.err.println(clazz + " due to LogPlatform.trace "); message.printStackTrace(); } public synchronized static I_Formatter getFormatter() { return formatter; } public synchronized static void setFormatter(I_Formatter formatter) { LogPlatform.formatter = formatter; } public static I_ThreadPopulator getThreadPopulator() { return threadPopulator; } public synchronized static void setThreadPopulator(I_ThreadPopulator threadPopulator) { LogPlatform.threadPopulator = threadPopulator; } protected static I_SystemOutput getOut() { return out; } protected static void setOut(I_SystemOutput out) { LogPlatform.out = out; } public static boolean isInit() { return isInit; } public I_Map getDefaults() { I_Map map = MapFactory.create(); map.put("defaultlog", "INFO"); map.put("gwt_loggers", "simple"); return map; } }
package com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.repository; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import com.ecwid.consul.v1.ConsulClient; import com.ecwid.consul.v1.Response; import com.ecwid.consul.v1.kv.model.GetValue; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.Rate; import java.io.IOException; import java.util.Base64; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class ConsulRateLimiterTest extends BaseRateLimiterTest { @Mock private RateLimiterErrorHandler rateLimiterErrorHandler; @Mock private ConsulClient consulClient; @Mock private ObjectMapper objectMapper; @Before public void setUp() { MockitoAnnotations.initMocks(this); Map<String, String> repository = Maps.newHashMap(); when(consulClient.setKVValue(any(), any())).thenAnswer(invocation -> { String key = invocation.getArgument(0); String value = invocation.getArgument(1); repository.put(key, value); return null; }); when(consulClient.getKVValue(any())).thenAnswer(invocation -> { String key = invocation.getArgument(0); GetValue getValue = new GetValue(); String value = repository.get(key); getValue.setValue(value != null ? Base64.getEncoder().encodeToString(value.getBytes()) : null); return new Response<>(getValue, 1L, true, 1L); }); ObjectMapper objectMapper = new ObjectMapper(); target = new ConsulRateLimiter(rateLimiterErrorHandler, consulClient, objectMapper); } @Test public void testGetRateException() throws IOException { GetValue getValue = new GetValue(); getValue.setValue(""); when(consulClient.getKVValue(any())).thenReturn(new Response<>(getValue, 1L, true, 1L)); when(objectMapper.readValue(anyString(), eq(Rate.class))).thenThrow(new IOException()); ConsulRateLimiter consulRateLimiter = new ConsulRateLimiter(rateLimiterErrorHandler, consulClient, objectMapper); Rate rate = consulRateLimiter.getRate(""); assertThat(rate).isNull(); } @Test public void testSaveRateException() throws IOException { JsonProcessingException jsonProcessingException = Mockito.mock(JsonProcessingException.class); when(objectMapper.writeValueAsString(any())).thenThrow(jsonProcessingException); ConsulRateLimiter consulRateLimiter = new ConsulRateLimiter(rateLimiterErrorHandler, consulClient, objectMapper); consulRateLimiter.saveRate(null); verifyZeroInteractions(consulClient); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.tools; import net.sf.samtools.util.CloseableIterator; import org.broad.igv.feature.*; import org.broad.igv.feature.genome.Genome; import org.broad.igv.sam.Alignment; import org.broad.igv.sam.AlignmentBlock; import org.broad.igv.sam.ReadMate; import org.broad.igv.sam.reader.AlignmentQueryReader; import org.broad.igv.sam.reader.MergedAlignmentReader; import org.broad.igv.sam.reader.SamQueryReaderFactory; import org.broad.igv.tools.parsers.DataConsumer; import org.broad.igv.ui.filefilters.AlignmentFileFilter; import org.broad.igv.util.FileUtils; import org.broad.igv.util.stats.Distribution; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.util.List; /** * TODO -- normalize option * -n Normalize the count by the total number of reads. This option multiplies each count by (1,000,000 / total # of reads). It is useful when comparing multiple chip-seq experiments when the absolute coverage depth is not important. */ public class CoverageCounter { private int countThreshold = 0; private int upperExpectedInsertSize = 600; private int lowerExpectedInsertSize = 200; private Locus interval; enum Event { mismatch, indel, largeISize, smallISize, inversion, duplication, inter, unmappedMate } private String alignmentFile; private File tdfFile; private DataConsumer consumer; private float[] buffer; private int windowSize = 1; // TODO -- make mapping qulaity a parameter private int minMappingQuality = 0; private int strandOption = -1; private int extFactor; private int totalCount = 0; private File wigFile = null; private WigWriter wigWriter = null; private boolean keepZeroes = false; private boolean includeDuplicates = false; private Genome genome; private String readGroup; // The read group to count Map<Event, WigWriter> writers = new HashMap(); private boolean computeTDF = true; private Distribution coverageHistogram; private static final double LOG_1__1 = 0.09531018; //private String interval = null; public CoverageCounter(String alignmentFile, DataConsumer consumer, int windowSize, int extFactor, File tdfFile, // For reference File wigFile, Genome genome, String options) { this.alignmentFile = alignmentFile; this.tdfFile = tdfFile; this.consumer = consumer; this.windowSize = windowSize; this.extFactor = extFactor; this.wigFile = wigFile; this.genome = genome; buffer = strandOption < 0 ? new float[1] : new float[2]; if (options != null) { parseOptions(options); } } private void parseOptions(String options) { try { String[] opts = options.split(","); for (String opt : opts) { if (opt.startsWith("d")) { includeDuplicates = true; } else if (opt.startsWith("m=")) { String[] tmp = opt.split("="); minMappingQuality = Integer.parseInt(tmp[1]); System.out.println("Minimum mapping quality = " + minMappingQuality); } else if (opt.startsWith("t=")) { String[] tmp = opt.split("="); countThreshold = Integer.parseInt(tmp[1]); System.out.println("Count threshold = " + countThreshold); } else if (opt.startsWith("l:")) { String[] tmp = opt.split(":"); readGroup = tmp[1]; } else if (opt.startsWith("q")) { String[] tmp = opt.split("@"); interval = new Locus(tmp[1]); } else if (opt.startsWith("i")) { writers.put(Event.largeISize, new WigWriter(new File(getFilenameBase() + ".large_isize.wig"), windowSize)); writers.put(Event.smallISize, new WigWriter(new File(getFilenameBase() + ".small_isize.wig"), windowSize)); // Optionally specify mean and std dev (todo -- just specify min and max) String[] tokens = opt.split(":"); if (tokens.length > 2) { //float median = Float.parseFloat(tokens[1]); //float mad = Float.parseFloat(tokens[2]); //upperExpectedInsertSize = (int) (median + 3 * mad); //lowerExpectedInsertSize = Math.max(50, (int) (median - 3 * mad)); int min = Integer.parseInt(tokens[1]); int max = Integer.parseInt(tokens[2]); upperExpectedInsertSize = min; lowerExpectedInsertSize = max; } else { PairedEndStats stats = PairedEndStats.compute(alignmentFile); if (stats == null) { System.out.println("Warning: error computing stats. Using default insert size settings"); } else { //double median = stats.getMedianInsertSize(); //double mad = stats.getMadInsertSize(); //upperExpectedInsertSize = (int) (median + 3 * mad); //lowerExpectedInsertSize = Math.max(50, (int) (median - 3 * mad)); upperExpectedInsertSize = (int) stats.getMaxPercentileInsertSize(); lowerExpectedInsertSize = (int) stats.getMinPercentileInsertSize(); System.out.println(alignmentFile + " min = " + lowerExpectedInsertSize + " max = " + upperExpectedInsertSize); } } } else if (opt.equals("o")) { writers.put(Event.inversion, new WigWriter(new File(getFilenameBase() + ".inversion.wig"), windowSize)); writers.put(Event.duplication, new WigWriter(new File(getFilenameBase() + ".duplication.wig"), windowSize)); } else if (opt.equals("m")) { writers.put(Event.mismatch, new WigWriter(new File(getFilenameBase() + ".mismatch.wig"), windowSize)); } else if (opt.equals("d")) { writers.put(Event.indel, new WigWriter(new File(getFilenameBase() + ".indel.wig"), windowSize)); } else if (opt.equals("u")) { writers.put(Event.unmappedMate, new WigWriter(new File(getFilenameBase() + ".nomate.wig"), windowSize)); } else if (opt.equals("r")) { writers.put(Event.inter, new WigWriter(new File(getFilenameBase() + ".inter.wig"), windowSize)); } else if (opt.equals("h")) { coverageHistogram = new Distribution(200); } else if (opt.equals("z")) { keepZeroes = true; } else { System.out.println("Unknown coverage option: " + opt); } } } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } private String getFilenameBase() { String tmp = tdfFile.getAbsolutePath(); tmp = tmp.substring(0, tmp.length() - 4); if (readGroup != null) { tmp += "." + readGroup; } return tmp; } // TODO -- options to ovveride all of these checks private boolean passFilter(Alignment alignment) { return (readGroup == null || readGroup.equals(alignment.getReadGroup())) && alignment.isMapped() && (includeDuplicates || !alignment.isDuplicate()) && alignment.getMappingQuality() >= minMappingQuality && !alignment.isVendorFailedRead(); } public void parse() throws IOException { int tolerance = (int) (windowSize * (Math.floor(extFactor / windowSize) + 2)); consumer.setSortTolerance(tolerance); AlignmentQueryReader reader = null; CloseableIterator<Alignment> iter = null; String lastChr = ""; ReadCounter counter = null; try { if (wigFile != null) { wigWriter = new WigWriter(wigFile, windowSize); } if (interval == null) { reader = getReader(alignmentFile, false); iter = reader.iterator(); } else { reader = getReader(alignmentFile, true); iter = reader.query(interval.getChr(), interval.getStart(), interval.getEnd(), false); } while (iter != null && iter.hasNext()) { Alignment alignment = iter.next(); if (passFilter(alignment)) { totalCount++; String alignmentChr = alignment.getChr(); // Close all counters with position < alignment.getStart() if (alignmentChr.equals(lastChr)) { if (counter != null) { counter.closeBucketsBefore(alignment.getAlignmentStart() - tolerance); } } else { if (counter != null) { counter.closeBucketsBefore(Integer.MAX_VALUE); } counter = new ReadCounter(alignmentChr); lastChr = alignmentChr; } if (alignment.getMappingQuality() == 0) { // TODO -- mq zero event } else if (alignment.isPaired()) { final int start = alignment.getStart(); final int end = alignment.getEnd(); counter.incrementPairedCount(start, end); ReadMate mate = alignment.getMate(); boolean mateMapped = mate != null && mate.isMapped(); boolean sameChromosome = mateMapped && mate.getChr().equals(alignment.getChr()); if (mateMapped) { if (sameChromosome) { // Pair orientation String oStr = alignment.getPairOrientation(); if (oStr.equals("R1F2") || oStr.equals("R2F1")) { counter.incrementPairedEvent(start, end, Event.duplication); } else if (oStr.equals("F1F2") || oStr.equals("F2F1") || oStr.equals("R1R2") || oStr.equals("R2R1")) { counter.incrementPairedEvent(start, end, Event.inversion); } // Insert size int isize = Math.abs(alignment.getInferredInsertSize()); if (isize > upperExpectedInsertSize) { counter.incrementPairedEvent(start, end, Event.largeISize); } if (isize < lowerExpectedInsertSize) { counter.incrementPairedEvent(start, end, Event.smallISize); } } else { counter.incrementPairedEvent(start, end, Event.inter); } } else { // unmapped mate counter.incrementPairedEvent(start, end, Event.unmappedMate); } } AlignmentBlock[] blocks = alignment.getAlignmentBlocks(); if (blocks != null) { int lastBlockEnd = -1; for (AlignmentBlock block : blocks) { if (!block.isSoftClipped()) { if (lastBlockEnd >= 0) { String c = alignment.getCigarString(); int s = block.getStart(); if (s > lastBlockEnd) { counter.incrementEvent(lastBlockEnd, Event.indel); } } byte[] bases = block.getBases(); int blockStart = block.getStart(); int adjustedStart = block.getStart(); int adjustedEnd = block.getEnd(); if (alignment.isNegativeStrand()) { adjustedStart = Math.max(0, adjustedStart - extFactor); } else { adjustedEnd += extFactor; } if (interval != null) { adjustedStart = Math.max(interval.getStart() - 1, adjustedStart); adjustedEnd = Math.min(interval.getEnd(), adjustedEnd); } for (int pos = adjustedStart; pos < adjustedEnd; pos++) { byte base = 0; int baseIdx = pos - blockStart; if (bases != null && baseIdx >= 0 && baseIdx < bases.length) { base = bases[baseIdx]; } int idx = pos - blockStart; byte quality = (idx >= 0 && idx < block.qualities.length) ? block.qualities[pos - blockStart] : (byte) 0; counter.incrementCount(pos, base, quality); } lastBlockEnd = block.getEnd(); } } } else { int adjustedStart = alignment.getAlignmentStart(); int adjustedEnd = alignment.getAlignmentEnd(); if (alignment.isNegativeStrand()) { adjustedStart = Math.max(0, adjustedStart - extFactor); } else { adjustedEnd += extFactor; } if (interval != null) { adjustedStart = Math.max(interval.getStart() - 1, adjustedStart); adjustedEnd = Math.min(interval.getEnd(), adjustedEnd); } for (int pos = adjustedStart; pos < adjustedEnd; pos++) { counter.incrementCount(pos, (byte) 0, (byte) 0); } } if (writers.containsKey(Event.indel)) { for (AlignmentBlock block : alignment.getInsertions()) { if (interval == null || (block.getStart() >= interval.getStart() - 1 && block.getStart() <= interval.getEnd())) { counter.incrementEvent(block.getStart(), Event.indel); } } } } } } catch (Exception e) { e.printStackTrace(); } finally { if (counter != null) { counter.closeBucketsBefore(Integer.MAX_VALUE); } consumer.setAttribute("totalCount", String.valueOf(totalCount)); consumer.parsingComplete(); if (iter != null) { iter.close(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } if (wigWriter != null) { wigWriter.close(); } for (WigWriter writer : writers.values()) { writer.close(); } if (coverageHistogram != null) { try { PrintWriter pw = new PrintWriter(new FileWriter(getFilenameBase() + ".hist.txt")); coverageHistogram.print(pw); pw.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } } private AlignmentQueryReader getReader(String alignmentFile, boolean b) throws IOException { boolean isList = alignmentFile.indexOf(",") > 0; if (isList) { String[] tokens = alignmentFile.split(","); List<AlignmentQueryReader> readers = new ArrayList(tokens.length); for (String f : tokens) { readers.add(SamQueryReaderFactory.getReader(f, b)); } return new MergedAlignmentReader(readers); } else { if (!FileUtils.isRemote(alignmentFile)) { File f = new File(alignmentFile); if (f.isDirectory()) { List<AlignmentQueryReader> readers = new ArrayList(); for (File file : f.listFiles(new AlignmentFileFilter())) { readers.add(SamQueryReaderFactory.getReader(file.getAbsolutePath(), b)); } return new MergedAlignmentReader(readers); } } return SamQueryReaderFactory.getReader(alignmentFile, b); } } class ReadCounter { String chr; TreeMap<Integer, Counter> counts = new TreeMap(); ReadCounter(String chr) { this.chr = chr; } void incrementCount(int position, byte base, byte quality) { final Counter counter = getCounterForPosition(position); counter.increment(position, base, quality); } void incrementEvent(int position, Event type) { final Counter counter = getCounterForPosition(position); counter.incrementEvent(type, 1); } void incrementPairedCount(int start, int end) { int startIdx = start / windowSize; int endIdx = end / windowSize; for (int idx = startIdx; idx <= endIdx; idx++) { Counter counter = getCounter(idx); counter.incrementPairedCount(fractionOverlap(counter, start, end)); } } // frac should be between 0 and 1 void incrementPairedEvent(int start, int end, Event type) { int startIdx = start / windowSize; int endIdx = end / windowSize; for (int idx = startIdx; idx <= endIdx; idx++) { Counter counter = getCounter(idx); counter.incrementEvent(type, fractionOverlap(counter, start, end)); } } // todo -- move to counter class? float fractionOverlap(Counter counter, int start, int end) { float counterLength = counter.end - counter.start; float overlapLength = Math.min(end, counter.end) - Math.max(start, counter.start); return overlapLength / counterLength; } //public void incrementISize(Alignment alignment) { // int startBucket = alignment.getStart() / windowSize; // int endBucket = alignment.getAlignmentEnd() / windowSize; // for (int bucket = startBucket; bucket <= endBucket; bucket++) { // int bucketStartPosition = bucket * windowSize; // int bucketEndPosition = bucketStartPosition + windowSize; // if (!counts.containsKey(bucket)) { // counts.put(bucket, new Counter(chr, bucketStartPosition, bucketEndPosition)); // final Counter counter = counts.get(bucket); // counter.incrementISize(alignment.getInferredInsertSize()); private Counter getCounterForPosition(int position) { int idx = position / windowSize; return getCounter(idx); } private Counter getCounter(int idx) { if (!counts.containsKey(idx)) { int counterStartPosition = idx * windowSize; int counterEndPosition = counterStartPosition + windowSize; counts.put(idx, new Counter(chr, counterStartPosition, counterEndPosition)); } final Counter counter = counts.get(idx); return counter; } //void incrementNegCount(int position) { // Integer bucket = position / windowSize; // if (!counts.containsKey(bucket)) { // counts.put(bucket, new Counter()); // counts.get(bucket).incrementNeg(); void closeBucketsBefore(int position) { List<Integer> bucketsToClose = new ArrayList(); Integer bucket = position / windowSize; for (Map.Entry<Integer, Counter> entry : counts.entrySet()) { if (entry.getKey() < bucket) { final Counter counter = entry.getValue(); int totalCount = counter.getCount(); if (totalCount > countThreshold) { // Divide total count by window size. This is the average count per // base over the window, so 30x coverage remains 30x irrespective of window size. int bucketStartPosition = entry.getKey() * windowSize; int bucketEndPosition = bucketStartPosition + windowSize; if (genome != null) { Chromosome chromosome = genome.getChromosome(chr); if (chromosome != null) { bucketEndPosition = Math.min(bucketEndPosition, chromosome.getLength()); } } int bucketSize = bucketEndPosition - bucketStartPosition; buffer[0] = ((float) totalCount) / bucketSize; if (strandOption > 0) { buffer[1] = ((float) counter.getCount()) / bucketSize; } consumer.addData(chr, bucketStartPosition, bucketEndPosition, buffer, null); for (Map.Entry<Event, WigWriter> entries : writers.entrySet()) { Event evt = entries.getKey(); WigWriter writer = entries.getValue(); float score = counter.getEventScore(evt); writer.addData(chr, bucketStartPosition, bucketEndPosition, score); } if (wigWriter != null) { wigWriter.addData(chr, bucketStartPosition, bucketEndPosition, buffer[0]); } /* if (coverageHistogram != null) { List<Feature> transcripts = FeatureUtils.getAllFeaturesAt(bucketStartPosition, 10000, 5, genes, false); if (transcripts != null && !transcripts.isEmpty()) { boolean isCoding = false; for (Feature t : transcripts) { Exon exon = ((IGVFeature) t).getExonAt(bucketStartPosition); if (exon != null && !exon.isUTR(bucketStartPosition)) { isCoding = true; break; } } if (isCoding) { int[] baseCounts = counter.getBaseCount(); for (int i = 0; i < baseCounts.length; i++) { coverageHistogram.addDataPoint(baseCounts[i]); } } } */ } bucketsToClose.add(entry.getKey()); } } for (Integer key : bucketsToClose) { counts.remove(key); } } } /** * Events * base mismatch * translocation * insertion (small) * insertion (large, rearrangment) * deletion (small) * deletion (large, rearrangment) */ class Counter { int count = 0; int negCount = 0; int qualityCount = 0; float pairedCount = 0; float mismatchCount = 0; float indelCount = 0; float largeISizeCount = 0; float smallISizeCount = 0; float inversionCount = 0; float duplicationCount = 0; float unmappedMate = 0; float interChrCount = 0; float totalISizeCount = 0; String chr; int start; int end; byte[] ref; int[] baseCount; //int isizeCount = 0; //float isizeZScore = 0; //float totalIsize = 0; Counter(String chr, int start, int end) { this.chr = chr; this.start = start; this.end = end; baseCount = new int[end - start]; //ref = SequenceHelper.readSequence(genome.getId(), chr, start, end); } int getCount() { return count; } int getNegCount() { return negCount; } void incrementNeg() { negCount++; } // frac should be between 0 znd 1 void incrementPairedCount(float frac) { pairedCount += frac; } public int[] getBaseCount() { return baseCount; } void increment(int position, byte base, byte quality) { // Qualities of 2 or less => no idea what this base is //if (quality <= 2) { // return; int offset = position - start; baseCount[offset]++; if (ref != null && ref.length > offset) { byte refBase = ref[offset]; if (refBase != base) { mismatchCount += quality; } } count++; qualityCount += quality; } // frac should be between 0 and 1 void incrementEvent(Event evt, float frac) { switch (evt) { case indel: indelCount += frac; break; case largeISize: largeISizeCount += frac; break; case smallISize: smallISizeCount += frac; break; case inversion: inversionCount += frac; break; case duplication: duplicationCount += frac; break; case inter: interChrCount += frac; break; case unmappedMate: unmappedMate += frac; break; } } public float getEventScore(Event evt) { switch (evt) { case mismatch: return qualityCount < 25 ? 0 : mismatchCount / qualityCount; case indel: return count < 5 ? 0 : indelCount / count; case largeISize: return pairedCount < 5 ? 0 : largeISizeCount / pairedCount; case smallISize: return pairedCount < 5 ? 0 : smallISizeCount / pairedCount; case inversion: return pairedCount < 5 ? 0 : inversionCount / pairedCount; case duplication: return pairedCount < 5 ? 0 : duplicationCount / pairedCount; case inter: return (pairedCount < 5 ? 0 : interChrCount / pairedCount); case unmappedMate: return (pairedCount < 5 ? 0 : unmappedMate / pairedCount); } throw new RuntimeException("Unknown event type: " + evt); } public void incrementISize(int inferredInsertSize) { totalISizeCount++; if (inferredInsertSize > 600) { largeISizeCount++; } else if (inferredInsertSize < 200) { smallISizeCount++; } //float zs = Math.min(6, (Math.abs(inferredInsertSize) - meanInsertSize) / stdDevInsertSize); //isizeZScore += zs; //ppCount++; //if (Math.abs(Math.abs(inferredInsertSize) - meanInsertSize) > 2 * stdDevInsertSize) { // isizeCount++; //otalIsize += Math.abs(inferredInsertSize); } //float getISizeFraction() { // if (pairedCount < 3) { // return 0; // float frac = ((float) isizeCount) / pairedCount; // return frac; //float avg = isizeZScore / ppCount; //return avg; //float getAvgIsize() { // return pairedCount == 0 ? 0 : totalIsize / pairedCount; } /** * Creates a vary step wig file */ class WigWriter { Event event = null; String lastChr = null; int lastPosition = 0; int step; int span; PrintWriter pw; WigWriter(File file, int step) throws IOException { this.step = step; this.span = step; pw = new PrintWriter(new FileWriter(file)); } WigWriter(File file, int step, Event event) throws IOException { this.step = step; this.span = step; pw = new PrintWriter(new FileWriter(file)); this.event = event; } public void addData(String chr, int start, int end, float data) { if (Float.isNaN(data)) { return; } if (genome.getChromosome(chr) == null) { return; } if ((!keepZeroes && data == 0) || end <= start) { return; } int dataSpan = end - start; if (chr == null || !chr.equals(lastChr) || dataSpan != span) { span = dataSpan; outputStepLine(chr, start + 1); } pw.println((start + 1) + "\t" + data); lastPosition = start; lastChr = chr; } private void close() { pw.close(); } private void outputStepLine(String chr, int start) { pw.println("variableStep chrom=" + chr + " span=" + span); } } }
package org.frc1675.subsystems.arm; import edu.wpi.first.wpilibj.AnalogPotentiometer; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.command.PIDSubsystem; import org.frc1675.RobotMap; import org.frc1675.commands.arm.shoulder.ShoulderMoveWithJoysticks; /** * Shoulder represents the system used for changing the angle of the entire claw * and shooter assembly. * * @author josh */ public class Shoulder extends PIDSubsystem { private static final double BUMP = 10; private static final int ABSOLUTE_TOLERANCE = 10; //degrees private static final int POT_SCALE = 50; public AnalogPotentiometer pot; private SpeedController motor; double setpoint = 250; boolean potWasBad = false; boolean potWasWasBad = false; public Shoulder(double p, double i, double d) { super(p, i, d); this.pot = new AnalogPotentiometer(RobotMap.SHOULDER_POT, POT_SCALE); this.motor = new Talon(RobotMap.SHOULDER_MOTOR); this.setInputRange(-1, 256); this.setAbsoluteTolerance(ABSOLUTE_TOLERANCE); } public void initDefaultCommand() { setDefaultCommand(new ShoulderMoveWithJoysticks()); //setDefaultCommand(new IncreaseShoulderSetpoint()); // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void rawMoveShoulder(double joystickValue) { motor.set(joystickValue); } protected double returnPIDInput() { return pot.get(); } protected void usePIDOutput(double d) { motor.set((d) * .75); } public void setPIDSetpoint(double angle) { this.setSetpoint(angle); this.enable(); } public void bumpUp(){ this.setSetpoint((this.getSetpoint())-BUMP); } public void bumpDown(){ this.setSetpoint((this.getSetpoint())+BUMP); } public void stopAndReset() { this.disable(); this.getPIDController().reset(); motor.set(0); } public boolean potIsBad(){ boolean potIsBad = pot.get()<5; if(potIsBad && potWasBad && potWasWasBad){ return true; } potWasWasBad = potWasBad; potWasBad = potIsBad; return false; } }
package org.irmacard.idemix; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.TreeMap; import java.util.Vector; import net.sourceforge.scuba.smartcards.CommandAPDU; import net.sourceforge.scuba.smartcards.ISO7816; import net.sourceforge.scuba.smartcards.ProtocolCommand; import net.sourceforge.scuba.smartcards.ProtocolCommands; import net.sourceforge.scuba.smartcards.ProtocolErrors; import net.sourceforge.scuba.smartcards.ProtocolResponses; import com.ibm.zurich.idmx.dm.Values; import com.ibm.zurich.idmx.dm.structure.AttributeStructure; import com.ibm.zurich.idmx.dm.structure.CredentialStructure; import com.ibm.zurich.idmx.issuance.IssuanceSpec; import com.ibm.zurich.idmx.issuance.Message; import com.ibm.zurich.idmx.issuance.Message.IssuanceProtocolValues; import com.ibm.zurich.idmx.key.IssuerPublicKey; import com.ibm.zurich.idmx.showproof.Identifier; import com.ibm.zurich.idmx.showproof.Proof; import com.ibm.zurich.idmx.showproof.ProofSpec; import com.ibm.zurich.idmx.showproof.predicates.CLPredicate; import com.ibm.zurich.idmx.showproof.predicates.Predicate; import com.ibm.zurich.idmx.showproof.predicates.Predicate.PredicateType; import com.ibm.zurich.idmx.showproof.sval.SValue; import com.ibm.zurich.idmx.showproof.sval.SValuesProveCL; import com.ibm.zurich.idmx.utils.StructureStore; import com.ibm.zurich.idmx.utils.SystemParameters; public class IdemixSmartcard { /** * AID of the Idemix applet: ASCII encoding of "idemix". */ private static final byte[] AID = {0x69, 0x64, 0x65, 0x6D, 0x69, 0x78}; /** * INStruction to select an applet. */ private static final byte INS_SELECT = (byte) 0xA4; /** * P1 parameter for select by name. */ private static final byte P1_SELECT = 0x04; /** * CLAss to be used for Idemix APDUs. */ private static final byte CLA_IDEMIX = (byte) 0x80; /** * INStruction to select a credential on the card. */ @SuppressWarnings("unused") private static final byte INS_SELECT_CREDENTIAL = 0x00; /** * INStruction to generate the master secret on the card. */ private static final byte INS_GENERATE_SECRET = 0x01; /** * INStruction to start issuing a credential (and to set the corresponding * context). */ private static final byte INS_ISSUE_CREDENTIAL = 0x10; /** * INStruction to issue the n value from the issuer public key. */ private static final byte INS_ISSUE_PUBLIC_KEY_N = 0x11; /** * INStruction to issue the z value from the issuer public key. */ private static final byte INS_ISSUE_PUBLIC_KEY_Z = 0x12; /** * INStruction to issue the s value from the issuer public key. */ private static final byte INS_ISSUE_PUBLIC_KEY_S = 0x13; /** * INStruction to issue the R values from the issuer public key. */ private static final byte INS_ISSUE_PUBLIC_KEY_R = 0x14; /** * INStruction to issue the attributes. */ private static final byte INS_ISSUE_ATTRIBUTES = 0x15; /** * INStruction to send the first nonce (n_1) and compute/receive the * combined hidden attributes (U). */ private static final byte INS_ISSUE_NONCE_1 = 0x16; /** * INStruction to receive the zero-knowledge proof for correct construction * of U (c, v^', s_A). */ private static final byte INS_ISSUE_PROOF_U = 0x17; /** * INStruction to receive the second nonce (n_2). */ private static final byte INS_ISSUE_NONCE_2 = 0x18; /** * INStruction to send the blind signature (A, e, v''). */ private static final byte INS_ISSUE_SIGNATURE = 0x19; /** * INStruction to send the zero-knowledge proof for correct construction of * the signature (s_e, c'). */ private static final byte INS_ISSUE_PROOF_A = 0x1A; /** * INStruction to start proving attributes from a credential (and to set * the corresponding context). */ private static final byte INS_PROVE_CREDENTIAL = 0x20; /** * INStruction to send the list of attributes to be disclosed. */ private static final byte INS_PROVE_SELECTION = 0x21; /** * INStruction to send the challenge (m) to be signed in the proof and * receive the commitment for the proof (a). */ private static final byte INS_PROVE_NONCE = 0x22; /** * INStruction to receive the values A', e^ and v^. */ private static final byte INS_PROVE_SIGNATURE = 0x23; /** * INStruction to receive the disclosed attributes (A_i). */ private static final byte INS_PROVE_ATTRIBUTE = 0x24; /** * INStruction to receive the values for the undisclosed attributes (r_i). */ private static final byte INS_PROVE_RESPONSE = 0x25; /** * INStruction to select a credential on the card. */ private static final byte INS_ADMIN_CREDENTIAL = 0x30; /** * INStruction to get a list of credentials stored on the card. */ private static final byte INS_ADMIN_CREDENTIALS = 0x31; /** * INStruction to get an attribute from the current selected credential. */ private static final byte INS_ADMIN_ATTRIBUTE = 0x32; /** * INStruction to remove a credential from the card. */ private static final byte INS_ADMIN_REMOVE = 0x33; /** * INStruction to get the flags of a credential. */ private static final byte INS_ADMIN_GET_FLAGS = 0x34; /** * INStruction to modify the flags of a credential. */ private static final byte INS_ADMIN_SET_FLAGS = 0x35; /** * INStruction to get the transaction log from the card. */ private static final byte INS_ADMIN_LOG = 0x36; /** * P1 parameter for the PROOF_U data instructions. */ private static final byte P1_PROOF_U_C = 0x00; private static final byte P1_PROOF_U_VPRIMEHAT = 0x01; private static final byte P1_PROOF_U_S_A = 0x02; /** * P1 parameters for SIGNATURE data instructions. */ private static final byte P1_SIGNATURE_A = 0x00; private static final byte P1_SIGNATURE_E = 0x01; private static final byte P1_SIGNATURE_V = 0x02; private static final byte P1_SIGNATURE_VERIFY = 0x03; /** * P1 parameters for PROOF_A data instructions. */ private static final byte P1_PROOF_A_C = 0x00; private static final byte P1_PROOF_A_S_E = 0x01; private static final byte P1_PROOF_A_VERIFY = 0x02; public static final byte PIN_CRED = 0x00; public static final byte PIN_CARD = 0x01; /** * Produces an unsigned byte-array representation of a BigInteger. * * <p>BigInteger adds an extra sign bit to the beginning of its byte * array representation. In some cases this will cause the size * of the byte array to increase, which may be unacceptable for some * applications. This function returns a minimal byte array representing * the BigInteger without extra sign bits. * * <p>This method is taken from the Network Security Services for Java (JSS) * currently maintained by the Mozilla Foundation and originally developed * by the Netscape Communications Corporation. * * @return unsigned big-endian byte array representation of a BigInteger. */ public static byte[] BigIntegerToUnsignedByteArray(BigInteger big) { byte[] ret; // big must not be negative assert(big.signum() != -1); // bitLength is the size of the data without the sign bit. If // it exactly fills an integral number of bytes, that means a whole // new byte will have to be added to accommodate the sign bit. In // this case we need to remove the first byte. if(big.bitLength() % 8 == 0) { byte[] array = big.toByteArray(); // The first byte should just be sign bits assert( array[0] == 0 ); ret = new byte[array.length-1]; System.arraycopy(array, 1, ret, 0, ret.length); } else { ret = big.toByteArray(); } return ret; } /** * Fix the length of array representation of BigIntegers put into the APDUs. * * @param integer of which the length needs to be fixed. * @param the new length of the integer in bits * @return an array with a fixed length. */ public static byte[] fixLength(BigInteger integer, int length_in_bits) { byte[] array = BigIntegerToUnsignedByteArray(integer); int length; length = length_in_bits/8; if (length_in_bits % 8 != 0){ length++; } assert (array.length <= length); int padding = length - array.length; byte[] fixed = new byte[length]; Arrays.fill(fixed, (byte) 0x00); System.arraycopy(array, 0, fixed, padding, array.length); return fixed; } private static byte[] addTimeStamp(byte[] argument) { int time = (int) ((new Date()).getTime() / 1000); return ByteBuffer.allocate(argument.length + 4).put(argument) .putInt(time).array(); } /* Idemix Smart Card commands */ public static ProtocolCommand selectAppletCommand = new ProtocolCommand( "selectapplet", "Select idemix applet", new CommandAPDU(ISO7816.CLA_ISO7816, INS_SELECT, P1_SELECT, 0x00, AID, 256)); // LE == 0 is required. /** * Get the APDU commands for setting the specification of * a certificate issuance: * <ul> * <li> issuer public key, and * <li> context. * </ul> * * @param spec the specification to be set * @param id * @return */ public static ProtocolCommands setIssuanceSpecificationCommands(IssuanceSpec spec, short id) { ProtocolCommands commands = new ProtocolCommands(); commands.add(startIssuanceCommand(spec, id)); commands.addAll(setPublicKeyCommands( spec.getPublicKey(), spec.getCredentialStructure().getAttributeStructs().size() + 1)); return commands; } /** * Get the APDU commands for setting the public key on * the card. * * @param spec Issuance spec to get the public key from. * @return */ public static ProtocolCommands setPublicKeyCommands(IssuerPublicKey pubKey, int pubKeyElements) { int l_n = pubKey.getGroupParams().getSystemParams().getL_n(); ProtocolCommands commands = new ProtocolCommands(); commands.add( new ProtocolCommand( "publickey_n", "Set public key (n)", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_PUBLIC_KEY_N, 0x00, 0x00, fixLength(pubKey.getN(), l_n)))); commands.add( new ProtocolCommand( "publickey_z", "Set public key (Z)", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_PUBLIC_KEY_Z, 0x00, 0x00, fixLength(pubKey.getCapZ(), l_n)))); commands.add( new ProtocolCommand( "publickey_s", "Set public key (S)", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_PUBLIC_KEY_S, 0x00, 0x00, fixLength(pubKey.getCapS(), l_n)))); BigInteger[] pubKeyElement = pubKey.getCapR(); for (int i = 0; i < pubKeyElements; i++) { commands.add( new ProtocolCommand( "publickey_element" + i, "Set public key element (R@index " + i + ")", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_PUBLIC_KEY_R, i, 0x00, fixLength(pubKeyElement[i], l_n)))); } return commands; } /** * Get the APDU commands to start issuance. * * @param spec Issuance specification * @param id id of credential * @return */ public static ProtocolCommand startIssuanceCommand(IssuanceSpec spec, short id) { int l_H = spec.getPublicKey().getGroupParams().getSystemParams().getL_H(); return new ProtocolCommand( "start_issuance", "Start credential issuance.", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_CREDENTIAL, id >> 8, id & 0xff, addTimeStamp(fixLength(spec.getContext(), l_H))), new ProtocolErrors( 0x00006986,"Credential already issued.")); } /** * Get the APDU commands to start proof. * * @param spec Proof specification * @param id id of credential * @return */ public static ProtocolCommand startProofCommand(ProofSpec spec, short id) { int l_H = spec.getGroupParams().getSystemParams().getL_H(); return new ProtocolCommand( "startprove", "Start credential proof.", new CommandAPDU( CLA_IDEMIX, INS_PROVE_CREDENTIAL, id >> 8, id & 0xff, addTimeStamp(fixLength(spec.getContext(), l_H))), new ProtocolErrors( 0x00006A88,"Credential not found.")); } public static ProtocolCommand generateMasterSecretCommand = new ProtocolCommand( "generatesecret", "Generate master secret", new CommandAPDU( CLA_IDEMIX, INS_GENERATE_SECRET, 0x00, 0x00), new ProtocolErrors( 0x00006986,"Master secret already set.")); public static ProtocolCommand sendPinCommand(byte pinID, byte[] pin) { return new ProtocolCommand( "sendpin", "Authorize using PIN", new CommandAPDU( ISO7816.CLA_ISO7816, ISO7816.INS_VERIFY, pinID, 0x00, pin) ); } public static ProtocolCommand updatePinCommand(byte pinID, byte[] pin) { return new ProtocolCommand( "updatepin", "Update current PIN", new CommandAPDU( ISO7816.CLA_ISO7816, ISO7816.INS_CHANGE_CHV, pinID, 0x00, pin) ); } /** * Get the APDU commands for setting the attributes: * * <pre> * m_1, ..., m_l * </pre> * * @param spec the issuance specification for the ordering of the values. * @param values the attributes to be set. * @return */ public static ProtocolCommands setAttributesCommands(IssuanceSpec spec, Values values) { ProtocolCommands commands = new ProtocolCommands(); Vector<AttributeStructure> structs = spec.getCredentialStructure().getAttributeStructs(); int L_m = spec.getPublicKey().getGroupParams().getSystemParams().getL_m(); int i = 1; for (AttributeStructure struct : structs) { BigInteger attr = (BigInteger) values.get(struct.getName()).getContent(); commands.add( new ProtocolCommand( "setattr"+i, "Set attribute (m@index" + i + ")", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_ATTRIBUTES, i, 0x00, fixLength(attr, L_m)))); i += 1; } return commands; } public static ProtocolCommands round1Commands(IssuanceSpec spec, final Message msg) { ProtocolCommands commands = new ProtocolCommands(); BigInteger theNonce1 = msg.getIssuanceElement( IssuanceProtocolValues.nonce); int L_Phi = spec.getPublicKey().getGroupParams().getSystemParams().getL_Phi(); commands.add( new ProtocolCommand( "nonce_n1", "Issue nonce n1", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_NONCE_1, 0x00, 0x00, fixLength(theNonce1,L_Phi)))); commands.add( new ProtocolCommand( "proof_c", "Issue proof c", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_PROOF_U, P1_PROOF_U_C, 0x00))); commands.add( new ProtocolCommand( "vHatPrime", "Issue proof v^'", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_PROOF_U, P1_PROOF_U_VPRIMEHAT, 0x00))); commands.add( new ProtocolCommand( "proof_s_A", "Issue proof s_A", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_PROOF_U, P1_PROOF_U_S_A, 0x00))); commands.add( new ProtocolCommand( "nonce_n2", "Issue nonce n2", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_NONCE_2, 0x00, 0x00))); return commands; } public static Message processRound1Responses(ProtocolResponses responses) { HashMap<IssuanceProtocolValues, BigInteger> issuanceProtocolValues = new HashMap<IssuanceProtocolValues, BigInteger>(); TreeMap<String, BigInteger> additionalValues = new TreeMap<String, BigInteger>(); HashMap<String, SValue> sValues = new HashMap<String, SValue>(); issuanceProtocolValues.put(IssuanceProtocolValues.capU, new BigInteger(1, responses.get("nonce_n1").getData())); BigInteger challenge = new BigInteger(1, responses.get("proof_c").getData()); additionalValues.put(IssuanceSpec.vHatPrime, new BigInteger(1, responses.get("vHatPrime").getData())); sValues.put(IssuanceSpec.MASTER_SECRET_NAME, new SValue(new BigInteger(1, responses.get("proof_s_A").getData()))); issuanceProtocolValues.put(IssuanceProtocolValues.nonce, new BigInteger(1, responses.get("nonce_n2").getData())); // Return the next protocol message return new Message(issuanceProtocolValues, new Proof(challenge, sValues, additionalValues)); } public static ProtocolCommands round3Commands(IssuanceSpec spec, final Message msg) { ProtocolCommands commands = new ProtocolCommands(); SystemParameters sysPars = spec.getPublicKey().getGroupParams().getSystemParams(); BigInteger A = msg.getIssuanceElement(IssuanceProtocolValues.capA); commands.add( new ProtocolCommand( "signature_A", "Issue signature A", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_SIGNATURE, P1_SIGNATURE_A, 0x00, fixLength(A, sysPars.getL_n())))); BigInteger e = msg.getIssuanceElement(IssuanceProtocolValues.e); commands.add( new ProtocolCommand( "signature_e", "Issue signature e", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_SIGNATURE, P1_SIGNATURE_E, 0x00, fixLength(e, sysPars.getL_e())))); BigInteger v = msg.getIssuanceElement(IssuanceProtocolValues.vPrimePrime); commands.add( new ProtocolCommand( "vPrimePrime", "Issue signature v''", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_SIGNATURE, P1_SIGNATURE_V, 0x00, fixLength(v, sysPars.getL_v())))); commands.add( new ProtocolCommand( "verify", "Verify issued signature", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_SIGNATURE, P1_SIGNATURE_VERIFY, 0x00))); BigInteger c = msg.getProof().getChallenge(); commands.add( new ProtocolCommand( "proof_c", "Issue proof c'", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_PROOF_A, P1_PROOF_A_C, 0x00, fixLength(c, sysPars.getL_H())))); BigInteger s_e = (BigInteger) msg.getProof().getSValue(IssuanceSpec.s_e).getValue(); commands.add( new ProtocolCommand( "proof_s_e", "Issue proof s_e", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_PROOF_A, P1_PROOF_A_S_E, 0x00, fixLength(s_e, sysPars.getL_n())))); commands.add( new ProtocolCommand( "proof_verify", "Verify proof", new CommandAPDU( CLA_IDEMIX, INS_ISSUE_PROOF_A, P1_PROOF_A_VERIFY, 0x00))); return commands; } public static ProtocolCommands buildProofCommands(final BigInteger nonce, final ProofSpec spec, short id) { ProtocolCommands commands = new ProtocolCommands(); // Set the system parameters SystemParameters sysPars = spec.getGroupParams().getSystemParams(); Predicate predicate = spec.getPredicates().firstElement(); if (predicate.getPredicateType() != PredicateType.CL) { throw new RuntimeException("Unimplemented predicate."); } CLPredicate pred = ((CLPredicate) predicate); CredentialStructure cred = (CredentialStructure) StructureStore.getInstance().get(pred.getCredStructLocation()); // Determine the disclosure selection bitmask int D = 0; for (AttributeStructure attribute : cred.getAttributeStructs()) { Identifier identifier = pred.getIdentifier(attribute.getName()); if (identifier.isRevealed()) { D |= 1 << attribute.getKeyIndex(); } } commands.add( startProofCommand(spec, id)); commands.add( new ProtocolCommand( "disclosure_d", "Attribute disclosure selection", new CommandAPDU(CLA_IDEMIX, INS_PROVE_SELECTION, (byte) ((D >> 8) & 0xFF), (byte) (D & 0xFF)))); commands.add( new ProtocolCommand( "challenge_c", "Send challenge n1", new CommandAPDU(CLA_IDEMIX, INS_PROVE_NONCE, 0x00, 0x00, fixLength(nonce, sysPars.getL_Phi())))); commands.add( new ProtocolCommand( "signature_A", "Get random signature A", new CommandAPDU(CLA_IDEMIX, INS_PROVE_SIGNATURE, P1_SIGNATURE_A, 0x00))); commands.add( new ProtocolCommand( "signature_e", "Get random signature e^", new CommandAPDU(CLA_IDEMIX, INS_PROVE_SIGNATURE, P1_SIGNATURE_E, 0x00))); commands.add( new ProtocolCommand( "signature_v", "Get random signature v^", new CommandAPDU(CLA_IDEMIX, INS_PROVE_SIGNATURE, P1_SIGNATURE_V, 0x00))); commands.add( new ProtocolCommand( "master", "Get random value (@index 0).", new CommandAPDU(CLA_IDEMIX, INS_PROVE_RESPONSE, 0x00, 0x00))); // iterate over all the identifiers for (AttributeStructure attribute : cred.getAttributeStructs()) { String attName = attribute.getName(); Identifier identifier = pred.getIdentifier(attName); int i = attribute.getKeyIndex(); if (identifier.isRevealed()) { commands.add( new ProtocolCommand( "attr_"+attName, "Get disclosed attribute (@index " + i + ")", new CommandAPDU(CLA_IDEMIX, INS_PROVE_ATTRIBUTE, i, 0x00))); } else { commands.add( new ProtocolCommand( "attr_"+attName, "Get random value (@index " + i + ").", new CommandAPDU(CLA_IDEMIX, INS_PROVE_RESPONSE, i, 0x00))); } } return commands; } public static Proof processBuildProofResponses(ProtocolResponses responses, final ProofSpec spec) { HashMap<String, SValue> sValues = new HashMap<String, SValue>(); TreeMap<String, BigInteger> commonList = new TreeMap<String, BigInteger>(); Predicate predicate = spec.getPredicates().firstElement(); if (predicate.getPredicateType() != PredicateType.CL) { throw new RuntimeException("Unimplemented predicate."); } CLPredicate pred = ((CLPredicate) predicate); StructureStore store = StructureStore.getInstance(); CredentialStructure cred = (CredentialStructure) store.get( pred.getCredStructLocation()); BigInteger challenge = new BigInteger(1, responses.get("challenge_c").getData()); commonList.put(pred.getTempCredName(), new BigInteger(1, responses.get("signature_A").getData())); sValues.put(pred.getTempCredName(), new SValue( new SValuesProveCL( new BigInteger(1, responses.get("signature_e").getData()), new BigInteger(1, responses.get("signature_v").getData()) ))); sValues.put(IssuanceSpec.MASTER_SECRET_NAME, new SValue(new BigInteger(1, responses.get("master").getData()))); for (AttributeStructure attribute : cred.getAttributeStructs()) { String attName = attribute.getName(); Identifier identifier = pred.getIdentifier(attName); sValues.put(identifier.getName(), new SValue(new BigInteger(1, responses.get("attr_" + attName).getData()))); } // Return the generated proof, based on the proof specification return new Proof(challenge, sValues, commonList); } public static ProtocolCommand getCredentialsCommand() { return new ProtocolCommand( "getcredentials", "Get list of credentials", new CommandAPDU(CLA_IDEMIX, INS_ADMIN_CREDENTIALS, 0x00, 0x00)); } public static ProtocolCommand selectCredentialCommand(short id) { return new ProtocolCommand( "selectcredential", "Select a credential for further modifications", new CommandAPDU(CLA_IDEMIX, INS_ADMIN_CREDENTIAL, id >> 8, id & 0xff)); } public static ProtocolCommands getAttributesCommands(IssuanceSpec spec) { ProtocolCommands commands = new ProtocolCommands(); for (AttributeStructure attribute : spec.getCredentialStructure() .getAttributeStructs()) { String attName = attribute.getName(); int i = attribute.getKeyIndex(); commands.add(new ProtocolCommand( "attr_" + attName, "Get attribute (@index " + i + ")", new CommandAPDU(CLA_IDEMIX, INS_ADMIN_ATTRIBUTE, i, 0x00))); } return commands; } public static ProtocolCommand removeCredentialCommand(short id) { byte[] empty = {}; return new ProtocolCommand( "removecredential", "Remove credential (id " + id + ")", new CommandAPDU(CLA_IDEMIX, INS_ADMIN_REMOVE, id >> 8, id & 0xff, addTimeStamp(empty))); } public static ProtocolCommand getCredentialFlagsCommand() { return new ProtocolCommand( "getcredflags", "Get credential flags", new CommandAPDU(CLA_IDEMIX, INS_ADMIN_GET_FLAGS, 0, 0)); } public static ProtocolCommand getLogCommand(byte idx) { return new ProtocolCommand( "getlog", "Get logs", new CommandAPDU(CLA_IDEMIX, INS_ADMIN_LOG, idx, 0)); } public static ProtocolCommand setCredentialFlagsCommand(short flags) { return new ProtocolCommand( "setcredflags", "Set credential flags (" + flags + ")", new CommandAPDU(CLA_IDEMIX, INS_ADMIN_SET_FLAGS, flags >> 8, flags)); } }
package org.csstudio.trends.databrowser2.waveformview; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.csstudio.archive.vtype.TimestampHelper; import org.csstudio.archive.vtype.VTypeHelper; import org.csstudio.swt.rtplot.PointType; import org.csstudio.swt.rtplot.RTPlot; import org.csstudio.swt.rtplot.RTValuePlot; import org.csstudio.swt.rtplot.Trace; import org.csstudio.swt.rtplot.TraceType; import org.csstudio.swt.rtplot.YAxis; import org.csstudio.swt.rtplot.data.TimeDataSearch; import org.csstudio.trends.databrowser2.Activator; import org.csstudio.trends.databrowser2.Messages; import org.csstudio.trends.databrowser2.editor.DataBrowserAwareView; import org.csstudio.trends.databrowser2.model.AnnotationInfo; import org.csstudio.trends.databrowser2.model.Model; import org.csstudio.trends.databrowser2.model.ModelItem; import org.csstudio.trends.databrowser2.model.ModelListener; import org.csstudio.trends.databrowser2.model.ModelListenerAdapter; import org.csstudio.trends.databrowser2.model.PlotSample; import org.csstudio.trends.databrowser2.model.PlotSamples; import org.diirt.vtype.VNumberArray; import org.diirt.vtype.VType; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Slider; import org.eclipse.swt.widgets.Text; /** View for inspecting Waveform (Array) Samples of the current Model * @author Kay Kasemir * @author Will Rogers Show current waveform sample in plot, various bugfixes * @author Takashi Nakamoto changed WaveformView to handle multiple items with * the same name. * @author Xihui Chen (Added some work around to make it work for rap). */ @SuppressWarnings("nls") public class WaveformView extends DataBrowserAwareView { /** View ID registered in plugin.xml */ final public static String ID = "org.csstudio.trends.databrowser.waveformview.WaveformView"; /** Text used for the annotation that indicates waveform sample */ final public static String ANNOTATION_TEXT = "Waveform view"; /** PV Name selector */ private Combo pv_name; /** Plot */ private RTValuePlot plot; /** Selector for model_item's current sample */ private Slider sample_index; /** Timestamp of current sample. */ private Text timestamp; /** Status/severity of current sample. */ private Text status; /** Model of the currently active Data Browser plot or <code>null</code> */ private Model model; /** Annotation in plot that indicates waveform sample */ private AnnotationInfo waveform_annotation; private boolean changing_annotations = false; private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture<?> pending_move = null; final private ModelListener model_listener = new ModelListenerAdapter() { @Override public void itemAdded(final ModelItem item) { update(false); } @Override public void itemRemoved(final ModelItem item) { if (item == model_item) { model_item = null; } update(false); } @Override public void changedItemLook(final ModelItem item) { update(false); } @Override public void changedAnnotations() { if (changing_annotations) return; // Reacting as the user moves the annotation // would be too expensive. // Delay, canceling previous request, for "post-selection" // type update once the user stops moving the annotation for a little time if (pending_move != null) pending_move.cancel(false); pending_move = timer.schedule(WaveformView.this::userMovedAnnotation, 500, TimeUnit.MILLISECONDS); } @Override public void changedTimerange() { // Update selected sample to assert that it's one of the visible ones. if (model_item != null) showSelectedSample(); } }; /** Selected model item in model, or <code>null</code> */ private ModelItem model_item = null; /** Waveform for the currently selected sample */ private WaveformValueDataProvider waveform = null; /** {@inheritDoc} */ @Override protected void doCreatePartControl(final Composite parent) { // Arrange disposal parent.addDisposeListener((DisposeEvent e) -> { // Ignore current model after this view is disposed. if (model != null) { model.removeListener(model_listener); removeAnnotation(); } }); final GridLayout layout = new GridLayout(4, false); parent.setLayout(layout); // PV: .pvs..... [Refresh] // <<<<<< Slider >>>>>> // PV: .pvs..... [Refresh] Label l = new Label(parent, 0); l.setText(Messages.SampleView_Item); l.setLayoutData(new GridData()); pv_name = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY); pv_name.setLayoutData(new GridData(SWT.FILL, 0, true, false, layout.numColumns-2, 1)); pv_name.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { widgetDefaultSelected(e); } @Override public void widgetDefaultSelected(final SelectionEvent e) { // First item is "--select PV name--" if (pv_name.getSelectionIndex() == 0) selectPV(null); else selectPV(model.getItem(pv_name.getText())); } }); final Button refresh = new Button(parent, SWT.PUSH); refresh.setText(Messages.SampleView_Refresh); refresh.setToolTipText(Messages.SampleView_RefreshTT); refresh.setLayoutData(new GridData()); refresh.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { // First item is "--select PV name--" if (pv_name.getSelectionIndex() == 0) selectPV(null); else selectPV(model.getItem(pv_name.getText())); } }); plot = new RTValuePlot(parent); plot.getXAxis().setName(Messages.WaveformIndex); plot.getYAxes().get(0).setName(Messages.WaveformAmplitude); plot.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, layout.numColumns, 1)); // <<<<<< Slider >>>>>> sample_index = new Slider(parent, SWT.HORIZONTAL); sample_index.setToolTipText(Messages.WaveformTimeSelector); sample_index.setLayoutData(new GridData(SWT.FILL, 0, true, false, layout.numColumns, 1)); sample_index.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { showSelectedSample(); } }); l = new Label(parent, 0); l.setText(Messages.WaveformTimestamp); l.setLayoutData(new GridData()); timestamp = new Text(parent, SWT.BORDER | SWT.READ_ONLY); timestamp.setLayoutData(new GridData(SWT.FILL, 0, true, false)); l = new Label(parent, 0); l.setText(Messages.WaveformStatus); l.setLayoutData(new GridData()); status = new Text(parent, SWT.BORDER | SWT.READ_ONLY); status.setLayoutData(new GridData(SWT.FILL, 0, true, false)); final MenuManager mm = new MenuManager(); mm.setRemoveAllWhenShown(true); final Menu menu = mm.createContextMenu(plot.getPlotControl()); plot.getPlotControl().setMenu(menu); getSite().registerContextMenu(mm, null); mm.addMenuListener(new IMenuListener(){ @Override public void menuAboutToShow(IMenuManager manager) { mm.add(plot.getToolbarAction()); mm.add(plot.getLegendAction()); mm.add(new Separator()); mm.add(new ToggleYAxisAction<Double>(plot, true)); } }); } /** {@inheritDoc} */ @Override public void setFocus() { pv_name.setFocus(); } /** {@inheritDoc} */ @Override protected void updateModel(final Model old_model, final Model model) { if (this.model == model) return; removeAnnotation(); this.model = model; if (old_model != model) { if (old_model != null) old_model.removeListener(model_listener); if (model != null) model.addListener(model_listener); } update(old_model != model); } /** Update combo box of this view. * Since it interacts with the UI run on the UI thread. * @param model_changed Is this a different model? */ private void update(final boolean model_changed) { Display.getDefault().asyncExec( () -> { if (pv_name.isDisposed()) { return; } if (model == null) { // Clear/disable GUI pv_name.setItems(new String[] { Messages.SampleView_NoPlot}); pv_name.select(0); pv_name.setEnabled(false); selectPV(null); return; } // Show PV names final List<String> names_list = new ArrayList<>(); names_list.add(Messages.SampleView_SelectItem); for (ModelItem item : model.getItems()) names_list.add(item.getName()); final String[] names = names_list.toArray(new String[names_list.size()]); // Is the previously selected item still valid? final int selected = pv_name.getSelectionIndex(); if (!model_changed && selected > 0 && model_item != null && pv_name.getText().equals(model_item.getName())) { // Show same PV name again in combo box pv_name.setItems(names); pv_name.select(selected); pv_name.setEnabled(true); return; } // Previously selected item no longer valid. // Show new items, clear rest pv_name.setItems(names); pv_name.select(0); pv_name.setEnabled(true); selectPV(null); }); } /** Select given PV item (or <code>null</code>). */ private void selectPV(final ModelItem new_item) { model_item = new_item; // Delete all existing traces for (Trace<Double> trace : plot.getTraces()) plot.removeTrace(trace); // No or unknown PV name? if (model_item == null) { pv_name.setText(""); sample_index.setEnabled(false); removeAnnotation(); return; } // Prepare to show waveforms of model item in plot waveform = new WaveformValueDataProvider(); // Create trace for waveform plot.addTrace(model_item.getResolvedDisplayName(), model_item.getUnits(), waveform, model_item.getColor(), TraceType.NONE, 1, PointType.CIRCLES, 5, 0); // Enable waveform selection and update slider's range sample_index.setEnabled(true); showSelectedSample(); // Autoscale Y axis by default. If the user tries to move the axis this will automatically turn off. for (YAxis<Double> yaxis : plot.getYAxes()) { yaxis.setAutoscale(true); } } /** Show the current sample of the current model item. */ private void showSelectedSample() { // Get selected sample (= one waveform) final PlotSamples samples = model_item.getSamples(); final int idx = sample_index.getSelection(); final PlotSample sample; samples.getLock().lock(); try { sample_index.setMaximum(samples.size()); sample = samples.get(idx); } finally { samples.getLock().unlock(); } // Setting the value can be delayed while the plot is being updated final VType value = sample.getVType(); Activator.getThreadPool().execute(() -> waveform.setValue(value)); if (value == null) clearInfo(); else { updateAnnotation(sample.getPosition(), sample.getValue()); int size = value instanceof VNumberArray ? ((VNumberArray)value).getData().size() : 1; plot.getXAxis().setValueRange(0.0, (double)size); timestamp.setText(TimestampHelper.format(VTypeHelper.getTimestamp(value))); status.setText(NLS.bind(Messages.SeverityStatusFmt, VTypeHelper.getSeverity(value).toString(), VTypeHelper.getMessage(value))); } plot.requestUpdate(); } /** Clear all the info fields. */ private void clearInfo() { timestamp.setText(""); status.setText(""); removeAnnotation(); } private void userMovedAnnotation() { if (waveform_annotation == null) return; for (AnnotationInfo annotation : model.getAnnotations()) { // Locate the annotation for this waveform if (annotation.isInternal() && annotation.getItemIndex() == waveform_annotation.getItemIndex() && annotation.getText().equals(waveform_annotation.getText())) { // Locate index of sample for annotation's time stamp final PlotSamples samples = model_item.getSamples(); final TimeDataSearch search = new TimeDataSearch(); final int idx; samples.getLock().lock(); try { idx = search.findClosestSample(samples, annotation.getTime()); } finally { samples.getLock().unlock(); } // Update waveform view for that sample on UI thread sample_index.getDisplay().asyncExec(() -> { sample_index.setSelection(idx); showSelectedSample(); }); return; } } } private void removeAnnotation() { if (model != null) { final List<AnnotationInfo> modelAnnotations = new ArrayList<AnnotationInfo>(model.getAnnotations()); if (modelAnnotations.remove(waveform_annotation)) { changing_annotations = true; model.setAnnotations(modelAnnotations); changing_annotations = false; } } waveform_annotation = null; } private void updateAnnotation(final Instant time, final double value) { final List<AnnotationInfo> annotations = new ArrayList<AnnotationInfo>(model.getAnnotations()); // Initial annotation offset Point offset = new Point(20, -20); // If already in model, note its offset and remove for (AnnotationInfo annotation : annotations) { if (annotation.getText().equals(ANNOTATION_TEXT)) { // Update offset to where user last placed it offset = annotation.getOffset(); waveform_annotation = annotation; annotations.remove(waveform_annotation); break; } } int i = 0; int item_index = 0; for (ModelItem item : model.getItems()) { if (item == model_item) { item_index = i; break; } i++; } waveform_annotation = new AnnotationInfo(true, item_index, time, value, offset, ANNOTATION_TEXT); annotations.add(waveform_annotation); changing_annotations = true; model.setAnnotations(annotations); changing_annotations = false; } public class ToggleYAxisAction<XTYPE extends Comparable<XTYPE>> extends Action { final private RTPlot<XTYPE> plot; public ToggleYAxisAction(final RTPlot<XTYPE> plot, final boolean is_visible) { super(plot.getYAxes().get(0).isLogarithmic() ? "Linear Axis" : "Logarithmic Axis", null); this.plot = plot; } public void updateText() { setText(plot.getYAxes().get(0).isLogarithmic() ? "Linear Axis" : "Logarithmic Axis"); } @Override public void run() { plot.getYAxes().get(0).setLogarithmic(!plot.getYAxes().get(0).isLogarithmic()); plot.requestUpdate(); } } }
package org.intermine.bio.web.logic; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionMessage; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.Profile; import org.intermine.api.query.WebResultsExecutor; import org.intermine.api.results.WebResults; import org.intermine.metadata.Model; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.pathquery.Constraints; import org.intermine.pathquery.Path; import org.intermine.pathquery.PathQuery; import org.intermine.web.logic.Constants; import org.intermine.web.logic.bag.BagConverter; import org.intermine.web.logic.config.WebConfig; import org.intermine.web.logic.pathqueryresult.PathQueryResultHelper; import org.intermine.web.logic.session.SessionMethods; /** * @author "Xavier Watkins" * */ public class OrthologueConverter implements BagConverter { private static final Logger LOG = Logger.getLogger(OrthologueConverter.class); /** * The Constructor */ public OrthologueConverter() { super(); } /** * {@inheritDoc} */ public WebResults getConvertedObjects (HttpSession session, String organism, List<Integer> fromList, String type) throws ObjectStoreException { final InterMineAPI im = SessionMethods.getInterMineAPI(session); Model model = im.getModel(); ObjectStore os = im.getObjectStore(); WebConfig webConfig = SessionMethods.getWebConfig(session.getServletContext()); PathQuery q = new PathQuery(model); List<Path> view = PathQueryResultHelper.getDefaultView(type, model, webConfig, "Gene.homologues.homologue", false); view = getFixedView(view); q.setViewPaths(view); List<InterMineObject> objectList = os.getObjectsByIds(fromList); // gene q.addConstraint("Gene", Constraints.in(objectList)); // organism q.addConstraint("Gene.homologues.homologue.organism", Constraints.lookup(organism)); // homologue.type = "orthologue" q.addConstraint("Gene.homologues.type", Constraints.eq("orthologue")); q.setConstraintLogic("A and B and C"); q.syncLogicExpression("and"); LOG.info("PATH QUERY:" + q.toXml(PathQuery.USERPROFILE_VERSION)); Profile profile = SessionMethods.getProfile(session); WebResultsExecutor executor = im.getWebResultsExecutor(profile); return executor.execute(q); } /** * If view contains joined organism, this will make sure, that * organism is joined as a inner join. Else constraint on organism doesn't work. * @param pathQuery * @param joinPath */ private List<Path> getFixedView(List<Path> view) { String invalidPath = "Gene.homologues.homologue:organism"; String validPath = "Gene.homologues.homologue.organism"; List<Path> ret = new ArrayList<Path>(); for (Path path : view) { if (path.toString().contains(invalidPath)) { String newPathString = path.toString().replace(invalidPath, validPath); path = new Path(path.getModel(), newPathString); } ret.add(path); } return ret; } /** * {@inheritDoc} */ public ActionMessage getActionMessage(Model model, String externalids, int convertedSize, String type, String organism) throws UnsupportedEncodingException { PathQuery q = new PathQuery(model); // add columns to the output q.setView("Gene.primaryIdentifier, " + "Gene.organism.shortName," + "Gene.homologues.homologue.primaryIdentifier," + "Gene.homologues.homologue.organism.shortName," + "Gene.homologues.type"); // homologue.type = "orthologue" q.addConstraint("Gene.homologues.type", Constraints.eq("orthologue")); // organism q.addConstraint("Gene.organism", Constraints.lookup(organism)); // if the XML is too long, the link generates "HTTP Error 414 - Request URI too long" if (externalids.length() < 4000) { q.addConstraint("Gene.homologues.homologue", Constraints.lookup(externalids)); } q.setConstraintLogic("A and B and C"); q.syncLogicExpression("and"); String query = q.toXml(PathQuery.USERPROFILE_VERSION); String encodedurl = URLEncoder.encode(query, "UTF-8"); String[] values = new String[] { String.valueOf(convertedSize), organism, String.valueOf(externalids.split(",").length), type, encodedurl }; ActionMessage am = new ActionMessage("portal.orthologues", values); return am; } }
package bndtools.editor.pages; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.forms.events.ExpansionAdapter; import org.eclipse.ui.forms.events.ExpansionEvent; public class ResizeExpansionAdapter extends ExpansionAdapter { private final Composite layoutParent; private final Control control; public ResizeExpansionAdapter(Control control) { this(control.getParent(), control); } public ResizeExpansionAdapter(Composite layoutParent, Control control) { this.layoutParent = layoutParent; this.control = control; } @Override public void expansionStateChanged(ExpansionEvent e) { Object layoutData = (Boolean.TRUE.equals(e.data)) ? PageLayoutUtils.createExpanded() : PageLayoutUtils.createCollapsed(); control.setLayoutData(layoutData); layoutParent.layout(true, true); } }
package org.jgroups.protocols.pbcast; import org.jgroups.*; import org.jgroups.annotations.*; import org.jgroups.conf.PropertyConverters; import org.jgroups.stack.*; import org.jgroups.util.*; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Negative AcKnowledgement layer (NAKs). Messages are assigned a monotonically * increasing sequence number (seqno). Receivers deliver messages ordered * according to seqno and request retransmission of missing messages.<br/> * Retransmit requests are usually sent to the original sender of a message, but * this can be changed by xmit_from_random_member (send to random member) or * use_mcast_xmit_req (send to everyone). Responses can also be sent to everyone * instead of the requester by setting use_mcast_xmit to true. * * @author Bela Ban * @version $Id: NAKACK.java,v 1.216 2009/04/28 07:53:46 belaban Exp $ */ @MBean(description="Reliable transmission multipoint FIFO protocol") @DeprecatedProperty(names={"max_xmit_size", "eager_lock_release"}) public class NAKACK extends Protocol implements Retransmitter.RetransmitCommand, NakReceiverWindow.Listener { private static final long INITIAL_SEQNO=0; private static final String name="NAKACK"; /** * the weight with which we take the previous smoothed average into account, * WEIGHT should be >0 and <= 1 */ private static final double WEIGHT=0.9; private static final double INITIAL_SMOOTHED_AVG=30.0; private static final int NUM_REBROADCAST_MSGS=3; @Property(name="retransmit_timeout", converter=PropertyConverters.LongArray.class, description="Timeout before requesting retransmissions. Default is 600, 1200, 2400, 4800") private long[] retransmit_timeouts= { 600, 1200, 2400, 4800 }; // time(s) to wait before requesting retransmission @Property(description="If true, retransmissions stats will be captured. Default is false") boolean enable_xmit_time_stats=false; @ManagedAttribute(description="Garbage collection lag", writable=true) @Property(description="Garbage collection lag. Default is 20 msec") private int gc_lag=20; // number of msgs garbage collection lags behind /** * Retransmit messages using multicast rather than unicast. This has the * advantage that, if many receivers lost a message, the sender only * retransmits once. */ @Property(description="Retransmit messages using multicast rather than unicast. Default is true") @ManagedAttribute(description="Retransmit messages using multicast rather than unicast", writable=true) private boolean use_mcast_xmit=true; /** * Use a multicast to request retransmission of missing messages. This may * be costly as every member in the cluster will send a response */ @Property(description="Use a multicast to request retransmission of missing messages. Default is false") private boolean use_mcast_xmit_req=false; /** * Ask a random member for retransmission of a missing message. If set to * true, discard_delivered_msgs will be set to false */ @Property(description="Ask a random member for retransmission of a missing message. Default is false") @ManagedAttribute(description="Ask a random member for retransmission of a missing message", writable=true) private boolean xmit_from_random_member=false; /** * The first value (in milliseconds) to use in the exponential backoff * retransmission mechanism. Only enabled if the value is > 0 */ @Property(description="The first value (in milliseconds) to use in the exponential backoff. Enabled if greater than 0. Default is 0") private long exponential_backoff=0; /** * If enabled, we use statistics gathered from actual retransmission times * to compute the new retransmission times */ @Property(description="Use statistics gathered from actual retransmission times to compute new retransmission times. Default is false") private boolean use_stats_for_retransmission=false; /** * Messages that have been received in order are sent up the stack (= * delivered to the application). Delivered messages are removed from * NakReceiverWindow.xmit_table and moved to * NakReceiverWindow.delivered_msgs, where they are later garbage collected * (by STABLE). Since we do retransmits only from sent messages, never * received or delivered messages, we can turn the moving to delivered_msgs * off, so we don't keep the message around, and don't need to wait for * garbage collection to remove them. */ @Property(description="Should messages delivered to application be discarded. Default is false") @ManagedAttribute(description="Discard delivered messages", writable=true) private boolean discard_delivered_msgs=false; @Property(description="See http://jira.jboss.com/jira/browse/JGRP-656. Default is true") private boolean eager_lock_release=false; /** * If value is > 0, the retransmit buffer is bounded: only the * max_xmit_buf_size latest messages are kept, older ones are discarded when * the buffer size is exceeded. A value <= 0 means unbounded buffers */ @Property(description="If value is > 0, the retransmit buffer is bounded. If value <= 0 unbounded buffers are used. Default is 0") @ManagedAttribute(description="If value is > 0, the retransmit buffer is bounded. If value <= 0 unbounded buffers are used", writable=true) private int max_xmit_buf_size=0; @Property(description="Size of retransmission history. Default is 50 entries") private int xmit_history_max_size=50; @Property(description="Timeout to rebroadcast messages. Default is 2000 msec") private long max_rebroadcast_timeout=2000; /** * When not finding a message on an XMIT request, include the last N * stability messages in the error message */ @Property(description="Should stability history be printed if we fail in retransmission. Default is false") protected boolean print_stability_history_on_failed_xmit=false; @Property(description="Size of send and receive history. Default is 20 entries") private int stats_list_size=20; @ManagedAttribute(description="Number of retransmit requests received") private long xmit_reqs_received; @ManagedAttribute(description="Number of retransmit requests sent") private long xmit_reqs_sent; @ManagedAttribute(description="Number of retransmit responses received") private long xmit_rsps_received; @ManagedAttribute(description="Number of retransmit responses sent") private long xmit_rsps_sent; @ManagedAttribute(description="Number of missing messages received") private long missing_msgs_received; /** * Maintains retransmission related data across a time. Only used if enable_xmit_time_stats is set to true. * At program termination, accumulated data is dumped to a file named by the address of the member. * Careful, don't enable this in production as the data in this hashmap are * never reaped ! Really only meant for diagnostics ! */ private ConcurrentMap<Long,XmitTimeStat> xmit_time_stats=null; private long xmit_time_stats_start; /** * BoundedList<MissingMessage>. Keeps track of the last stats_list_size * XMIT requests */ private BoundedList<MissingMessage> receive_history; /** * BoundedList<XmitRequest>. Keeps track of the last stats_list_size * missing messages received */ private BoundedList<XmitRequest> send_history; /** Captures stats on XMIT_REQS, XMIT_RSPS per sender */ private ConcurrentMap<Address,StatsEntry> sent=new ConcurrentHashMap<Address,StatsEntry>(); /** Captures stats on XMIT_REQS, XMIT_RSPS per receiver */ private ConcurrentMap<Address,StatsEntry> received=new ConcurrentHashMap<Address,StatsEntry>(); /** * Per-sender map of seqnos and timestamps, to keep track of avg times for retransmission of messages */ private final ConcurrentMap<Address,ConcurrentMap<Long,Long>> xmit_stats=new ConcurrentHashMap<Address,ConcurrentMap<Long,Long>>(); /** * Maintains a list of the last N retransmission times (duration it took to * retransmit a message) for all members */ private final ConcurrentMap<Address,BoundedList<Long>> xmit_times_history=new ConcurrentHashMap<Address,BoundedList<Long>>(); /** * Maintains a smoothed average of the retransmission times per sender, * these are the actual values that are used for new retransmission requests */ private final Map<Address,Double> smoothed_avg_xmit_times=new HashMap<Address,Double>(); private boolean is_server=false; private Address local_addr=null; private final List<Address> members=new CopyOnWriteArrayList<Address>(); private View view; @GuardedBy("seqno_lock") private long seqno=0; // current message sequence number (starts with 1) private final Lock seqno_lock=new ReentrantLock(); /** Map to store sent and received messages (keyed by sender) */ private final ConcurrentMap<Address,NakReceiverWindow> xmit_table=new ConcurrentHashMap<Address,NakReceiverWindow>(11); private volatile boolean leaving=false; private volatile boolean started=false; private TimeScheduler timer=null; /** * Keeps track of OOB messages sent by myself, needed by * {@link #handleMessage(org.jgroups.Message, NakAckHeader)} */ private final Set<Long> oob_loopback_msgs=Collections.synchronizedSet(new HashSet<Long>()); private final Lock rebroadcast_lock=new ReentrantLock(); private final Condition rebroadcast_done=rebroadcast_lock.newCondition(); // set during processing of a rebroadcast event private volatile boolean rebroadcasting=false; private final Lock rebroadcast_digest_lock=new ReentrantLock(); @GuardedBy("rebroadcast_digest_lock") private Digest rebroadcast_digest=null; /** BoundedList<Digest>, keeps the last 10 stability messages */ protected final BoundedList<Digest> stability_msgs=new BoundedList<Digest>(10); /** Keeps a bounded list of the last N merges */ protected final BoundedList<String> merge_history=new BoundedList<String>(10); /** If true, logs messages discarded because received from other members */ @ManagedAttribute(description="If true, logs messages discarded because received from other members", writable=true) private boolean log_discard_msgs=true; /** <em>Regular</em> messages which have been added, but not removed */ private final AtomicInteger undelivered_msgs=new AtomicInteger(0); public NAKACK() { } public String getName() { return name; } @ManagedAttribute public int getUndeliveredMessages() { return undelivered_msgs.get(); } public long getXmitRequestsReceived() {return xmit_reqs_received;} public long getXmitRequestsSent() {return xmit_reqs_sent;} public long getXmitResponsesReceived() {return xmit_rsps_received;} public long getXmitResponsesSent() {return xmit_rsps_sent;} public long getMissingMessagesReceived() {return missing_msgs_received;} @ManagedAttribute public int getPendingRetransmissionRequests() { int num=0; for(NakReceiverWindow win: xmit_table.values()) { num+=win.getPendingXmits(); } return num; } @ManagedAttribute public int getXmitTableSize() { int num=0; for(NakReceiverWindow win: xmit_table.values()) { num+=win.size(); } return num; } public int getReceivedTableSize() { return getPendingRetransmissionRequests(); } public void resetStats() { xmit_reqs_received=xmit_reqs_sent=xmit_rsps_received=xmit_rsps_sent=missing_msgs_received=0; sent.clear(); received.clear(); if(receive_history !=null) receive_history.clear(); if(send_history != null) send_history.clear(); stability_msgs.clear(); merge_history.clear(); } public void init() throws Exception { if(enable_xmit_time_stats) { if(log.isWarnEnabled()) log.warn("enable_xmit_time_stats is experimental, and may be removed in any release"); xmit_time_stats=new ConcurrentHashMap<Long,XmitTimeStat>(); xmit_time_stats_start=System.currentTimeMillis(); } if(xmit_from_random_member) { if(discard_delivered_msgs) { discard_delivered_msgs=false; log.warn("xmit_from_random_member set to true: changed discard_delivered_msgs to false"); } } if(stats) { send_history=new BoundedList<XmitRequest>(stats_list_size); receive_history=new BoundedList<MissingMessage>(stats_list_size); } } public int getGcLag() { return gc_lag; } public void setGcLag(int gc_lag) { this.gc_lag=gc_lag; } public boolean isUseMcastXmit() { return use_mcast_xmit; } public void setUseMcastXmit(boolean use_mcast_xmit) { this.use_mcast_xmit=use_mcast_xmit; } public boolean isXmitFromRandomMember() { return xmit_from_random_member; } public void setXmitFromRandomMember(boolean xmit_from_random_member) { this.xmit_from_random_member=xmit_from_random_member; } public boolean isDiscardDeliveredMsgs() { return discard_delivered_msgs; } public void setDiscardDeliveredMsgs(boolean discard_delivered_msgs) { boolean old=this.discard_delivered_msgs; this.discard_delivered_msgs=discard_delivered_msgs; if(old != this.discard_delivered_msgs) { for(NakReceiverWindow win: xmit_table.values()) { win.setDiscardDeliveredMessages(this.discard_delivered_msgs); } } } public int getMaxXmitBufSize() { return max_xmit_buf_size; } public void setMaxXmitBufSize(int max_xmit_buf_size) { this.max_xmit_buf_size=max_xmit_buf_size; } /** * * @return * @deprecated removed in 2.6 */ public long getMaxXmitSize() { return -1; } /** * * @param max_xmit_size * @deprecated removed in 2.6 */ public void setMaxXmitSize(long max_xmit_size) { } public void setLogDiscardMessages(boolean flag) { log_discard_msgs=flag; } public void setLogDiscardMsgs(boolean flag) { setLogDiscardMessages(flag); } public boolean getLogDiscardMessages() { return log_discard_msgs; } public Map<String,Object> dumpStats() { Map<String,Object> retval=super.dumpStats(); retval.put("msgs", printMessages()); return retval; } public String printStats() { Map.Entry entry; Object key, val; StringBuilder sb=new StringBuilder(); sb.append("sent:\n"); for(Iterator it=sent.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); key=entry.getKey(); if(key == null || key == Global.NULL) key="<mcast dest>"; val=entry.getValue(); sb.append(key).append(": ").append(val).append("\n"); } sb.append("\nreceived:\n"); for(Iterator it=received.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); key=entry.getKey(); if(key == null || key == Global.NULL) key="<mcast dest>"; val=entry.getValue(); sb.append(key).append(": ").append(val).append("\n"); } sb.append("\nXMIT_REQS sent:\n"); for(XmitRequest tmp: send_history) { sb.append(tmp).append("\n"); } sb.append("\nMissing messages received\n"); for(MissingMessage missing: receive_history) { sb.append(missing).append("\n"); } sb.append("\nStability messages received\n"); sb.append(printStabilityMessages()).append("\n"); return sb.toString(); } @ManagedOperation(description="TODO") public String printStabilityMessages() { StringBuilder sb=new StringBuilder(); sb.append(Util.printListWithDelimiter(stability_msgs, "\n")); return sb.toString(); } public String printStabilityHistory() { StringBuilder sb=new StringBuilder(); int i=1; for(Digest digest: stability_msgs) { sb.append(i++).append(": ").append(digest).append("\n"); } return sb.toString(); } @ManagedOperation(description="Keeps information about the last N merges") public String printMergeHistory() { StringBuilder sb=new StringBuilder(); for(String tmp: merge_history) sb.append(tmp).append("\n"); return sb.toString(); } @ManagedOperation(description="TODO") public String printLossRates() { StringBuilder sb=new StringBuilder(); NakReceiverWindow win; for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) { win=entry.getValue(); sb.append(entry.getKey()).append(": ").append(win.printLossRate()).append("\n"); } return sb.toString(); } @ManagedAttribute public double getAverageLossRate() { double retval=0.0; int count=0; if(xmit_table.isEmpty()) return 0.0; for(NakReceiverWindow win: xmit_table.values()) { retval+=win.getLossRate(); count++; } return retval / (double)count; } @ManagedAttribute public double getAverageSmoothedLossRate() { double retval=0.0; int count=0; if(xmit_table.isEmpty()) return 0.0; for(NakReceiverWindow win: xmit_table.values()) { retval+=win.getSmoothedLossRate(); count++; } return retval / (double)count; } public Vector<Integer> providedUpServices() { Vector<Integer> retval=new Vector<Integer>(5); retval.addElement(new Integer(Event.GET_DIGEST)); retval.addElement(new Integer(Event.SET_DIGEST)); retval.addElement(new Integer(Event.MERGE_DIGEST)); return retval; } public void start() throws Exception { timer=getTransport().getTimer(); if(timer == null) throw new Exception("timer is null"); started=true; leaving=false; if(xmit_time_stats != null) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { String filename="xmit-stats-" + local_addr + ".log"; try { dumpXmitStats(filename); } catch(IOException e) { e.printStackTrace(); } } }); } } public void stop() { started=false; reset(); // clears sent_msgs and destroys all NakReceiverWindows oob_loopback_msgs.clear(); } /** * <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>down_prot.down()</code> in this * method as the event is passed down by default by the superclass after this method returns !</b> */ public Object down(Event evt) { switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); Address dest=msg.getDest(); if(dest != null && !dest.isMulticastAddress()) { break; // unicast address: not null and not mcast, pass down unchanged } send(evt, msg); return null; // don't pass down the stack case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg stable((Digest)evt.getArg()); return null; // do not pass down further (Bela Aug 7 2001) case Event.GET_DIGEST: return getDigest(); case Event.SET_DIGEST: setDigest((Digest)evt.getArg()); return null; case Event.MERGE_DIGEST: mergeDigest((Digest)evt.getArg()); return null; case Event.TMP_VIEW: View tmp_view=(View)evt.getArg(); Vector<Address> mbrs=tmp_view.getMembers(); members.clear(); members.addAll(mbrs); // adjustReceivers(false); break; case Event.VIEW_CHANGE: tmp_view=(View)evt.getArg(); mbrs=tmp_view.getMembers(); members.clear(); members.addAll(mbrs); view=tmp_view; adjustReceivers(members); is_server=true; // check vids from now on Set<Address> tmp=new LinkedHashSet<Address>(members); tmp.add(null); // for null destination (= mcast) sent.keySet().retainAll(tmp); received.keySet().retainAll(tmp); xmit_stats.keySet().retainAll(tmp); // in_progress.keySet().retainAll(mbrs); // remove elements which are not in the membership break; case Event.BECOME_SERVER: is_server=true; break; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; case Event.DISCONNECT: leaving=true; reset(); break; case Event.REBROADCAST: rebroadcasting=true; rebroadcast_digest=(Digest)evt.getArg(); try { rebroadcastMessages(); } finally { rebroadcasting=false; rebroadcast_digest_lock.lock(); try { rebroadcast_digest=null; } finally { rebroadcast_digest_lock.unlock(); } } return null; } return down_prot.down(evt); } /** * <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>PassUp</code> in this * method as the event is passed up by default by the superclass after this method returns !</b> */ public Object up(Event evt) { switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); NakAckHeader hdr=(NakAckHeader)msg.getHeader(name); if(hdr == null) break; // pass up (e.g. unicast msg) // discard messages while not yet server (i.e., until JOIN has returned) if(!is_server) { if(log.isTraceEnabled()) log.trace("message was discarded (not yet server)"); return null; } // Changed by bela Jan 29 2003: we must not remove the header, otherwise // further xmit requests will fail ! //hdr=(NakAckHeader)msg.removeHeader(getName()); switch(hdr.type) { case NakAckHeader.MSG: handleMessage(msg, hdr); return null; // transmitter passes message up for us ! case NakAckHeader.XMIT_REQ: if(hdr.range == null) { if(log.isErrorEnabled()) { log.error("XMIT_REQ: range of xmit msg is null; discarding request from " + msg.getSrc()); } return null; } handleXmitReq(msg.getSrc(), hdr.range.low, hdr.range.high, hdr.sender); return null; case NakAckHeader.XMIT_RSP: if(log.isTraceEnabled()) log.trace("received missing message " + msg.getSrc() + ":" + hdr.seqno); handleXmitRsp(msg); return null; default: if(log.isErrorEnabled()) { log.error("NakAck header type " + hdr.type + " not known !"); } return null; } case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg stable((Digest)evt.getArg()); return null; // do not pass up further (Bela Aug 7 2001) case Event.SUSPECT: // release the promise if rebroadcasting is in progress... otherwise we wait forever. there will be a new // flush round anyway if(rebroadcasting) { cancelRebroadcasting(); } break; } return up_prot.up(evt); } private void send(Event evt, Message msg) { if(msg == null) throw new NullPointerException("msg is null; event is " + evt); if(!started) { if(log.isTraceEnabled()) log.trace("[" + local_addr + "] discarded message as start() has not been called, message: " + msg); return; } long msg_id; NakReceiverWindow win=xmit_table.get(local_addr); msg.setSrc(local_addr); // this needs to be done so we can check whether the message sender is the local_addr seqno_lock.lock(); try { try { // incrementing seqno and adding the msg to sent_msgs needs to be atomic msg_id=seqno +1; msg.putHeader(name, new NakAckHeader(NakAckHeader.MSG, msg_id)); if(win.add(msg_id, msg) && !msg.isFlagSet(Message.OOB)) undelivered_msgs.incrementAndGet(); seqno=msg_id; } catch(Throwable t) { throw new RuntimeException("failure adding msg " + msg + " to the retransmit table for " + local_addr, t); } } finally { seqno_lock.unlock(); } try { if(msg.isFlagSet(Message.OOB)) oob_loopback_msgs.add(msg_id); if(log.isTraceEnabled()) log.trace("sending " + local_addr + "#" + msg_id); down_prot.down(evt); // if this fails, since msg is in sent_msgs, it can be retransmitted } catch(Throwable t) { // eat the exception, don't pass it up the stack if(log.isWarnEnabled()) { log.warn("failure passing message down", t); } } } /** * Finds the corresponding NakReceiverWindow and adds the message to it (according to seqno). Then removes as many * messages as possible from the NRW and passes them up the stack. Discards messages from non-members. */ private void handleMessage(Message msg, NakAckHeader hdr) { Address sender=msg.getSrc(); if(sender == null) { if(log.isErrorEnabled()) log.error("sender of message is null"); return; } if(log.isTraceEnabled()) log.trace(new StringBuilder().append('[').append(local_addr).append(": received ").append(sender).append('#').append(hdr.seqno)); NakReceiverWindow win=xmit_table.get(sender); if(win == null) { // discard message if there is no entry for sender if(leaving) return; if(log.isWarnEnabled() && log_discard_msgs) log.warn(local_addr + "] discarded message from non-member " + sender + ", my view is " + view); return; } boolean loopback=local_addr.equals(sender); boolean added_to_window=false; boolean added=loopback || (added_to_window=win.add(hdr.seqno, msg)); if(added_to_window) undelivered_msgs.incrementAndGet(); // message is passed up if OOB. Later, when remove() is called, we discard it. This affects ordering ! if(added && msg.isFlagSet(Message.OOB)) { if(!loopback || oob_loopback_msgs.remove(hdr.seqno)) { up_prot.up(new Event(Event.MSG, msg)); win.removeOOBMessage(); if(!(win.hasMessagesToRemove() && undelivered_msgs.get() > 0)) return; } } // Efficient way of checking whether another thread is already processing messages from 'sender'. // If that's the case, we return immediately and let the exiting thread process our message // can be returned to the thread pool final AtomicBoolean processing=win.getProcessing(); if(!processing.compareAndSet(false, true)) { return; } // where lots of threads can come up to this point concurrently, but only 1 is allowed to pass at a time // We *can* deliver messages from *different* senders concurrently, e.g. reception of P1, Q1, P2, Q2 can result in // delivery of P1, Q1, Q2, P2: FIFO (implemented by NAKACK) says messages need to be delivered in the // order in which they were sent by the sender int num_regular_msgs_removed=0; // 2nd line of defense: in case of an exception, remove() might not be called, therefore processing would never // be set back to false. If we get an exception and released_processing is not true, then we set // processing to false in the finally clause boolean released_processing=false; try { while(true) { // we're removing a msg and set processing to false (if null) *atomically* (wrt to add()) Message msg_to_deliver=win.remove(processing); if(msg_to_deliver == null) { released_processing=true; return; // processing will be set to false now } if(msg_to_deliver.isFlagSet(Message.OOB)) { continue; } num_regular_msgs_removed++; // System.out.println("removed regular #" + ((NakAckHeader)msg_to_deliver.getHeader(name)).seqno); // Changed by bela Jan 29 2003: not needed (see above) //msg_to_deliver.removeHeader(getName()); up_prot.up(new Event(Event.MSG, msg_to_deliver)); } } finally { // We keep track of regular messages that we added, but couldn't remove (because of ordering). // When we have such messages pending, then even OOB threads will remove and process them undelivered_msgs.addAndGet(-num_regular_msgs_removed); // processing is always set in win.remove(processing) above and never here ! This code is just a // 2nd line of defense should there be an exception before win.remove(processing) sets processing if(!released_processing) processing.set(false); } } /** * Retransmits messsages first_seqno to last_seqno from original_sender from xmit_table to xmit_requester, * called when XMIT_REQ is received. * @param xmit_requester The sender of the XMIT_REQ, we have to send the requested copy of the message to this address * @param first_seqno The first sequence number to be retransmitted (<= last_seqno) * @param last_seqno The last sequence number to be retransmitted (>= first_seqno) * @param original_sender The member who originally sent the messsage. Guaranteed to be non-null */ private void handleXmitReq(Address xmit_requester, long first_seqno, long last_seqno, Address original_sender) { Message msg; if(log.isTraceEnabled()) { StringBuilder sb=new StringBuilder(); sb.append(local_addr).append(": received xmit request from ").append(xmit_requester).append(" for "); sb.append(original_sender).append(" [").append(first_seqno).append(" - ").append(last_seqno).append("]"); log.trace(sb.toString()); } if(first_seqno > last_seqno) { if(log.isErrorEnabled()) log.error("first_seqno (" + first_seqno + ") > last_seqno (" + last_seqno + "): not able to retransmit"); return; } if(stats) { xmit_reqs_received+=last_seqno - first_seqno +1; updateStats(received, xmit_requester, 1, 0, 0); } if(xmit_time_stats != null) { long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000; XmitTimeStat stat=xmit_time_stats.get(key); if(stat == null) { stat=new XmitTimeStat(); XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat); if(stat2 != null) stat=stat2; } stat.xmit_reqs_received.addAndGet((int)(last_seqno - first_seqno +1)); stat.xmit_rsps_sent.addAndGet((int)(last_seqno - first_seqno +1)); } NakReceiverWindow win=xmit_table.get(original_sender); if(win == null) { if(log.isErrorEnabled()) { StringBuilder sb=new StringBuilder(); sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); sb.append(") ").append(original_sender).append(" not found in retransmission table:\n").append(printMessages()); if(print_stability_history_on_failed_xmit) { sb.append(" (stability history:\n").append(printStabilityHistory()); } log.error(sb); } return; } for(long i=first_seqno; i <= last_seqno; i++) { msg=win.get(i); if(msg == null) { if(log.isWarnEnabled() && !local_addr.equals(xmit_requester)) { StringBuilder sb=new StringBuilder(); sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); sb.append(") message ").append(original_sender).append("::").append(i); sb.append(" not found in retransmission table of ").append(original_sender).append(":\n").append(win); if(print_stability_history_on_failed_xmit) { sb.append(" (stability history:\n").append(printStabilityHistory()); } log.warn(sb); } continue; } sendXmitRsp(xmit_requester, msg, i); } } private void cancelRebroadcasting() { rebroadcast_lock.lock(); try { rebroadcasting=false; rebroadcast_done.signalAll(); } finally { rebroadcast_lock.unlock(); } } private static void updateStats(ConcurrentMap<Address,StatsEntry> map, Address key, int req, int rsp, int missing) { StatsEntry entry=map.get(key); if(entry == null) { entry=new StatsEntry(); StatsEntry tmp=map.putIfAbsent(key, entry); if(tmp != null) entry=tmp; } entry.xmit_reqs+=req; entry.xmit_rsps+=rsp; entry.missing_msgs_rcvd+=missing; } /** * Sends a message msg to the requester. We have to wrap the original message into a retransmit message, as we need * to preserve the original message's properties, such as src, headers etc. * @param dest * @param msg * @param seqno */ private void sendXmitRsp(Address dest, Message msg, long seqno) { Buffer buf; if(msg == null) { if(log.isErrorEnabled()) log.error("message is null, cannot send retransmission"); return; } if(stats) { xmit_rsps_sent++; updateStats(sent, dest, 0, 1, 0); } if(use_mcast_xmit) dest=null; if(msg.getSrc() == null) msg.setSrc(local_addr); try { buf=Util.messageToByteBuffer(msg); Message xmit_msg=new Message(dest, null, buf.getBuf(), buf.getOffset(), buf.getLength()); // changed Bela Jan 4 2007: we should not use OOB for retransmitted messages, otherwise we tax the // OOB thread pool too much // msg.setFlag(Message.OOB); xmit_msg.putHeader(name, new NakAckHeader(NakAckHeader.XMIT_RSP, seqno)); down_prot.down(new Event(Event.MSG, xmit_msg)); } catch(IOException ex) { log.error("failed marshalling xmit list", ex); } } private void handleXmitRsp(Message msg) { if(msg == null) { if(log.isWarnEnabled()) log.warn("message is null"); return; } try { Message wrapped_msg=Util.byteBufferToMessage(msg.getRawBuffer(), msg.getOffset(), msg.getLength()); if(xmit_time_stats != null) { long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000; XmitTimeStat stat=xmit_time_stats.get(key); if(stat == null) { stat=new XmitTimeStat(); XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat); if(stat2 != null) stat=stat2; } stat.xmit_rsps_received.incrementAndGet(); } if(stats) { xmit_rsps_received++; updateStats(received, msg.getSrc(), 0, 1, 0); } up(new Event(Event.MSG, wrapped_msg)); if(rebroadcasting) { Digest tmp=getDigest(); boolean cancel_rebroadcasting; rebroadcast_digest_lock.lock(); try { cancel_rebroadcasting=tmp.isGreaterThanOrEqual(rebroadcast_digest); } finally { rebroadcast_digest_lock.unlock(); } if(cancel_rebroadcasting) { cancelRebroadcasting(); } } } catch(Exception ex) { if(log.isErrorEnabled()) { log.error("failed reading retransmitted message", ex); } } } /** * Takes the argument highest_seqnos and compares it to the current digest. If the current digest has fewer messages, * then send retransmit messages for the missing messages. Return when all missing messages have been received. If * we're waiting for a missing message from P, and P crashes while waiting, we need to exclude P from the wait set. */ private void rebroadcastMessages() { Digest my_digest; Map<Address,Digest.Entry> their_digest; Address sender; Digest.Entry their_entry, my_entry; long their_high, my_high; long sleep=max_rebroadcast_timeout / NUM_REBROADCAST_MSGS; long wait_time=max_rebroadcast_timeout, start=System.currentTimeMillis(); while(wait_time > 0) { rebroadcast_digest_lock.lock(); try { if(rebroadcast_digest == null) break; their_digest=rebroadcast_digest.getSenders(); } finally { rebroadcast_digest_lock.unlock(); } my_digest=getDigest(); boolean xmitted=false; for(Map.Entry<Address,Digest.Entry> entry: their_digest.entrySet()) { sender=entry.getKey(); their_entry=entry.getValue(); my_entry=my_digest.get(sender); if(my_entry == null) continue; their_high=their_entry.getHighest(); my_high=my_entry.getHighest(); if(their_high > my_high) { if(log.isTraceEnabled()) log.trace("sending XMIT request to " + sender + " for messages " + my_high + " - " + their_high); retransmit(my_high, their_high, sender, true); // use multicast to send retransmit request xmitted=true; } } if(!xmitted) return; // we're done; no retransmissions are needed anymore. our digest is >= rebroadcast_digest rebroadcast_lock.lock(); try { try { my_digest=getDigest(); rebroadcast_digest_lock.lock(); try { if(!rebroadcasting || my_digest.isGreaterThanOrEqual(rebroadcast_digest)) return; } finally { rebroadcast_digest_lock.unlock(); } rebroadcast_done.await(sleep, TimeUnit.MILLISECONDS); wait_time-=(System.currentTimeMillis() - start); } catch(InterruptedException e) { } } finally { rebroadcast_lock.unlock(); } } } /** * Remove old members from NakReceiverWindows and add new members (starting seqno=0). Essentially removes all * entries from xmit_table that are not in <code>members</code>. This method is not called concurrently * multiple times */ private void adjustReceivers(List<Address> new_members) { NakReceiverWindow win; // 1. Remove all senders in xmit_table that are not members anymore for(Iterator<Address> it=xmit_table.keySet().iterator(); it.hasNext();) { Address sender=it.next(); if(!new_members.contains(sender)) { if(local_addr != null && local_addr.equals(sender)) { if(log.isErrorEnabled()) log.error("will not remove myself (" + sender + ") from xmit_table, received incorrect new membership of " + new_members); continue; } win=xmit_table.get(sender); win.reset(); if(log.isDebugEnabled()) { log.debug("removing " + sender + " from xmit_table (not member anymore)"); } it.remove(); } } // 2. Add newly joined members to xmit_table (starting seqno=0) for(Address sender: new_members) { if(!xmit_table.containsKey(sender)) { win=createNakReceiverWindow(sender, INITIAL_SEQNO, 0); xmit_table.put(sender, win); } } } /** * Returns a message digest: for each member P the lowest, highest delivered and highest received seqno is added */ public Digest getDigest() { final Map<Address,Digest.Entry> map=new HashMap<Address,Digest.Entry>(); for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) { Address sender=entry.getKey(); // guaranteed to be non-null (CCHM) NakReceiverWindow win=entry.getValue(); // guaranteed to be non-null (CCHM) long low=win.getLowestSeen(), highest_delivered=win.getHighestDelivered(), highest_received=win.getHighestReceived(); map.put(sender, new Digest.Entry(low, highest_delivered, highest_received)); } return new Digest(map); } /** * Creates a NakReceiverWindow for each sender in the digest according to the sender's seqno. If NRW already exists, * reset it. */ private void setDigest(Digest digest) { if(digest == null) { if(log.isErrorEnabled()) { log.error("digest or digest.senders is null"); } return; } if(local_addr != null && digest.contains(local_addr)) { clear(); } else { // remove all but local_addr (if not null) for(Iterator<Address> it=xmit_table.keySet().iterator(); it.hasNext();) { Address key=it.next(); if(local_addr != null && local_addr.equals(key)) { ; } else { it.remove(); } } } Address sender; Digest.Entry val; long initial_seqno; NakReceiverWindow win; for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) { sender=entry.getKey(); val=entry.getValue(); if(sender == null || val == null) { if(log.isWarnEnabled()) { log.warn("sender or value is null"); } continue; } initial_seqno=val.getHighestDeliveredSeqno(); win=createNakReceiverWindow(sender, initial_seqno, val.getLow()); xmit_table.put(sender, win); } if(!xmit_table.containsKey(local_addr)) { if(log.isWarnEnabled()) { log.warn("digest does not contain local address (local_addr=" + local_addr + ", digest=" + digest); } } } private void mergeDigest(Digest digest) { if(digest == null) { if(log.isErrorEnabled()) { log.error("digest or digest.senders is null"); } return; } StringBuilder sb=new StringBuilder(); sb.append("existing digest: " + getDigest()).append("\nnew digest: " + digest); for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) { Address sender=entry.getKey(); Digest.Entry val=entry.getValue(); if(sender == null || val == null) { if(log.isWarnEnabled()) { log.warn("sender or value is null"); } continue; } long highest_delivered_seqno=val.getHighestDeliveredSeqno(); long low_seqno=val.getLow(); // except for myself NakReceiverWindow win=xmit_table.get(sender); if(win != null) { if(local_addr != null && local_addr.equals(sender)) { continue; } else { win.reset(); // stops retransmission xmit_table.remove(sender); } } win=createNakReceiverWindow(sender, highest_delivered_seqno, low_seqno); xmit_table.put(sender, win); } sb.append("\n").append("resulting digest: " + getDigest()); merge_history.add(sb.toString()); if(log.isDebugEnabled()) log.debug(sb); if(!xmit_table.containsKey(local_addr)) { if(log.isWarnEnabled()) { log.warn("digest does not contain local address (local_addr=" + local_addr + ", digest=" + digest); } } } private NakReceiverWindow createNakReceiverWindow(Address sender, long initial_seqno, long lowest_seqno) { NakReceiverWindow win=new NakReceiverWindow(local_addr, sender, this, initial_seqno, lowest_seqno, timer); if(use_stats_for_retransmission) { win.setRetransmitTimeouts(new ActualInterval(sender)); } else if(exponential_backoff > 0) { win.setRetransmitTimeouts(new ExponentialInterval(exponential_backoff)); } else { win.setRetransmitTimeouts(new StaticInterval(retransmit_timeouts)); } win.setDiscardDeliveredMessages(discard_delivered_msgs); win.setMaxXmitBufSize(this.max_xmit_buf_size); if(stats) win.setListener(this); return win; } private void dumpXmitStats(String filename) throws IOException { Writer out=new FileWriter(filename); try { TreeMap<Long,XmitTimeStat> map=new TreeMap<Long,XmitTimeStat>(xmit_time_stats); StringBuilder sb; XmitTimeStat stat; out.write("time (secs) gaps-detected xmit-reqs-sent xmit-reqs-received xmit-rsps-sent xmit-rsps-received missing-msgs-received\n\n"); for(Map.Entry<Long,XmitTimeStat> entry: map.entrySet()) { sb=new StringBuilder(); stat=entry.getValue(); sb.append(entry.getKey()).append(" "); sb.append(stat.gaps_detected).append(" "); sb.append(stat.xmit_reqs_sent).append(" "); sb.append(stat.xmit_reqs_received).append(" "); sb.append(stat.xmit_rsps_sent).append(" "); sb.append(stat.xmit_rsps_received).append(" "); sb.append(stat.missing_msgs_received).append("\n"); out.write(sb.toString()); } } finally { out.close(); } } /** * Garbage collect messages that have been seen by all members. Update sent_msgs: for the sender P in the digest * which is equal to the local address, garbage collect all messages <= seqno at digest[P]. Update xmit_table: * for each sender P in the digest and its highest seqno seen SEQ, garbage collect all delivered_msgs in the * NakReceiverWindow corresponding to P which are <= seqno at digest[P]. */ private void stable(Digest digest) { NakReceiverWindow recv_win; long my_highest_rcvd; // highest seqno received in my digest for a sender P long stability_highest_rcvd; // highest seqno received in the stability vector for a sender P if(members == null || local_addr == null || digest == null) { if(log.isWarnEnabled()) log.warn("members, local_addr or digest are null !"); return; } if(log.isTraceEnabled()) { log.trace("received stable digest " + digest); } stability_msgs.add(digest); Address sender; Digest.Entry val; long high_seqno_delivered, high_seqno_received; for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) { sender=entry.getKey(); if(sender == null) continue; val=entry.getValue(); high_seqno_delivered=val.getHighestDeliveredSeqno(); high_seqno_received=val.getHighestReceivedSeqno(); // check whether the last seqno received for a sender P in the stability vector is > last seqno // received for P in my digest. if yes, request retransmission (see "Last Message Dropped" topic // in DESIGN) recv_win=xmit_table.get(sender); if(recv_win != null) { my_highest_rcvd=recv_win.getHighestReceived(); stability_highest_rcvd=high_seqno_received; if(stability_highest_rcvd >= 0 && stability_highest_rcvd > my_highest_rcvd) { if(log.isTraceEnabled()) { log.trace("my_highest_rcvd (" + my_highest_rcvd + ") < stability_highest_rcvd (" + stability_highest_rcvd + "): requesting retransmission of " + sender + '#' + stability_highest_rcvd); } retransmit(stability_highest_rcvd, stability_highest_rcvd, sender); } } high_seqno_delivered-=gc_lag; if(high_seqno_delivered < 0) { continue; } if(log.isTraceEnabled()) log.trace("deleting msgs <= " + high_seqno_delivered + " from " + sender); // delete *delivered* msgs that are stable if(recv_win != null) { recv_win.stable(high_seqno_delivered); // delete all messages with seqnos <= seqno } } } /** * Implementation of Retransmitter.RetransmitCommand. Called by retransmission thread when gap is detected. */ public void retransmit(long first_seqno, long last_seqno, Address sender) { retransmit(first_seqno, last_seqno, sender, false); } protected void retransmit(long first_seqno, long last_seqno, final Address sender, boolean multicast_xmit_request) { NakAckHeader hdr; Message retransmit_msg; Address dest=sender; // to whom do we send the XMIT request ? if(multicast_xmit_request || this.use_mcast_xmit_req) { dest=null; } else { if(xmit_from_random_member && !local_addr.equals(sender)) { Address random_member=(Address)Util.pickRandomElement(members); if(random_member != null && !local_addr.equals(random_member)) { dest=random_member; if(log.isTraceEnabled()) log.trace("picked random member " + dest + " to send XMIT request to"); } } } hdr=new NakAckHeader(NakAckHeader.XMIT_REQ, first_seqno, last_seqno, sender); retransmit_msg=new Message(dest, null, null); retransmit_msg.setFlag(Message.OOB); if(log.isTraceEnabled()) log.trace(local_addr + ": sending XMIT_REQ ([" + first_seqno + ", " + last_seqno + "]) to " + dest); retransmit_msg.putHeader(name, hdr); ConcurrentMap<Long,Long> tmp=xmit_stats.get(sender); if(tmp == null) { tmp=new ConcurrentHashMap<Long,Long>(); ConcurrentMap<Long,Long> tmp2=xmit_stats.putIfAbsent(sender, tmp); if(tmp2 != null) tmp=tmp2; } for(long seq=first_seqno; seq < last_seqno; seq++) { tmp.putIfAbsent(seq, System.currentTimeMillis()); } if(xmit_time_stats != null) { long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000; XmitTimeStat stat=xmit_time_stats.get(key); if(stat == null) { stat=new XmitTimeStat(); XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat); if(stat2 != null) stat=stat2; } stat.xmit_reqs_sent.addAndGet((int)(last_seqno - first_seqno +1)); } down_prot.down(new Event(Event.MSG, retransmit_msg)); if(stats) { xmit_reqs_sent+=last_seqno - first_seqno +1; updateStats(sent, sender, 1, 0, 0); XmitRequest req=new XmitRequest(sender, first_seqno, last_seqno, sender); send_history.add(req); } } public void missingMessageReceived(long seqno, final Address original_sender) { ConcurrentMap<Long,Long> tmp=xmit_stats.get(original_sender); if(tmp != null) { Long timestamp=tmp.remove(seqno); if(timestamp != null) { long diff=System.currentTimeMillis() - timestamp; BoundedList<Long> list=xmit_times_history.get(original_sender); if(list == null) { list=new BoundedList<Long>(xmit_history_max_size); BoundedList<Long> list2=xmit_times_history.putIfAbsent(original_sender, list); if(list2 != null) list=list2; } list.add(diff); // compute the smoothed average for retransmission times for original_sender // needs to be synchronized because we rely on the previous value for computation of the next value synchronized(smoothed_avg_xmit_times) { Double smoothed_avg=smoothed_avg_xmit_times.get(original_sender); if(smoothed_avg == null) smoothed_avg=INITIAL_SMOOTHED_AVG; // the smoothed avg takes 90% of the previous value, 100% of the new value and averages them // then, we add 10% to be on the safe side (an xmit value should rather err on the higher than lower side) smoothed_avg=((smoothed_avg * WEIGHT) + diff) / 2; smoothed_avg=smoothed_avg * (2 - WEIGHT); smoothed_avg_xmit_times.put(original_sender, smoothed_avg); } } } if(xmit_time_stats != null) { long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000; XmitTimeStat stat=xmit_time_stats.get(key); if(stat == null) { stat=new XmitTimeStat(); XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat); if(stat2 != null) stat=stat2; } stat.missing_msgs_received.incrementAndGet(); } if(stats) { missing_msgs_received++; updateStats(received, original_sender, 0, 0, 1); MissingMessage missing=new MissingMessage(original_sender, seqno); receive_history.add(missing); } } /** Called when a message gap is detected */ public void messageGapDetected(long from, long to, Address src) { if(xmit_time_stats != null) { long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000; XmitTimeStat stat=xmit_time_stats.get(key); if(stat == null) { stat=new XmitTimeStat(); XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat); if(stat2 != null) stat=stat2; } stat.gaps_detected.addAndGet((int)(to - from +1)); } } private void clear() { // changed April 21 2004 (bela): SourceForge bug# 938584. We cannot delete our own messages sent between // a join() and a getState(). Otherwise retransmission requests from members who missed those msgs might // fail. Not to worry though: those msgs will be cleared by STABLE (message garbage collection) // sent_msgs.clear(); for(NakReceiverWindow win: xmit_table.values()) { win.reset(); } xmit_table.clear(); undelivered_msgs.set(0); } private void reset() { seqno_lock.lock(); try { seqno=0; } finally { seqno_lock.unlock(); } for(NakReceiverWindow win: xmit_table.values()) { win.destroy(); } xmit_table.clear(); undelivered_msgs.set(0); } @ManagedOperation(description="TODO") public String printMessages() { StringBuilder ret=new StringBuilder(); Map.Entry<Address,NakReceiverWindow> entry; Address addr; Object w; for(Iterator<Map.Entry<Address,NakReceiverWindow>> it=xmit_table.entrySet().iterator(); it.hasNext();) { entry=it.next(); addr=entry.getKey(); w=entry.getValue(); ret.append(addr).append(": ").append(w.toString()).append('\n'); } return ret.toString(); } @ManagedOperation(description="TODO") public String printRetransmissionAvgs() { StringBuilder sb=new StringBuilder(); for(Map.Entry<Address,BoundedList<Long>> entry: xmit_times_history.entrySet()) { Address sender=entry.getKey(); BoundedList<Long> list=entry.getValue(); long tmp=0; int i=0; for(Long val: list) { tmp+=val; i++; } double avg=i > 0? tmp / i: -1; sb.append(sender).append(": ").append(avg).append("\n"); } return sb.toString(); } @ManagedOperation(description="TODO") public String printSmoothedRetransmissionAvgs() { StringBuilder sb=new StringBuilder(); for(Map.Entry<Address,Double> entry: smoothed_avg_xmit_times.entrySet()) { sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); } return sb.toString(); } @ManagedOperation(description="TODO") public String printRetransmissionTimes() { StringBuilder sb=new StringBuilder(); for(Map.Entry<Address,BoundedList<Long>> entry: xmit_times_history.entrySet()) { Address sender=entry.getKey(); BoundedList<Long> list=entry.getValue(); sb.append(sender).append(": ").append(list).append("\n"); } return sb.toString(); } @ManagedAttribute public double getTotalAverageRetransmissionTime() { long total=0; int i=0; for(BoundedList<Long> list: xmit_times_history.values()) { for(Long val: list) { total+=val; i++; } } return i > 0? total / i: -1; } @ManagedAttribute public double getTotalAverageSmoothedRetransmissionTime() { double total=0.0; int cnt=0; synchronized(smoothed_avg_xmit_times) { for(Double val: smoothed_avg_xmit_times.values()) { if(val != null) { total+=val; cnt++; } } } return cnt > 0? total / cnt : -1; } /** Returns the smoothed average retransmission time for a given sender */ public double getSmoothedAverageRetransmissionTime(Address sender) { synchronized(smoothed_avg_xmit_times) { Double retval=smoothed_avg_xmit_times.get(sender); if(retval == null) { retval=INITIAL_SMOOTHED_AVG; smoothed_avg_xmit_times.put(sender, retval); } return retval; } } // public static final class LossRate { // private final Set<Long> received=new HashSet<Long>(); // private final Set<Long> missing=new HashSet<Long>(); // private double smoothed_loss_rate=0.0; // public synchronized void addReceived(long seqno) { // received.add(seqno); // missing.remove(seqno); // setSmoothedLossRate(); // public synchronized void addReceived(Long ... seqnos) { // for(int i=0; i < seqnos.length; i++) { // Long seqno=seqnos[i]; // received.add(seqno); // missing.remove(seqno); // setSmoothedLossRate(); // public synchronized void addMissing(long from, long to) { // for(long i=from; i <= to; i++) { // if(!received.contains(i)) // missing.add(i); // setSmoothedLossRate(); // public synchronized double computeLossRate() { // int num_missing=missing.size(); // if(num_missing == 0) // return 0.0; // int num_received=received.size(); // int total=num_missing + num_received; // return num_missing / (double)total; // public synchronized double getSmoothedLossRate() { // return smoothed_loss_rate; // public synchronized String toString() { // StringBuilder sb=new StringBuilder(); // int num_missing=missing.size(); // int num_received=received.size(); // int total=num_missing + num_received; // sb.append("total=").append(total).append(" (received=").append(received.size()).append(", missing=") // .append(missing.size()).append(", loss rate=").append(computeLossRate()) // .append(", smoothed loss rate=").append(smoothed_loss_rate).append(")"); // return sb.toString(); // /** Set the new smoothed_loss_rate value to 70% of the new value and 30% of the old value */ // private void setSmoothedLossRate() { // double new_loss_rate=computeLossRate(); // if(smoothed_loss_rate == 0) { // smoothed_loss_rate=new_loss_rate; // else { // smoothed_loss_rate=smoothed_loss_rate * .3 + new_loss_rate * .7; private static class XmitTimeStat { final AtomicInteger gaps_detected=new AtomicInteger(0); final AtomicInteger xmit_reqs_sent=new AtomicInteger(0); final AtomicInteger xmit_reqs_received=new AtomicInteger(0); final AtomicInteger xmit_rsps_sent=new AtomicInteger(0); final AtomicInteger xmit_rsps_received=new AtomicInteger(0); final AtomicInteger missing_msgs_received=new AtomicInteger(0); } private class ActualInterval implements Interval { private final Address sender; public ActualInterval(Address sender) { this.sender=sender; } public long next() { return (long)getSmoothedAverageRetransmissionTime(sender); } public Interval copy() { return this; } } static class StatsEntry { long xmit_reqs, xmit_rsps, missing_msgs_rcvd; public String toString() { StringBuilder sb=new StringBuilder(); sb.append(xmit_reqs).append(" xmit_reqs").append(", ").append(xmit_rsps).append(" xmit_rsps"); sb.append(", ").append(missing_msgs_rcvd).append(" missing msgs"); return sb.toString(); } } static class XmitRequest { final Address original_sender; // original sender of message final long low, high, timestamp=System.currentTimeMillis(); final Address xmit_dest; // destination to which XMIT_REQ is sent, usually the original sender XmitRequest(Address original_sender, long low, long high, Address xmit_dest) { this.original_sender=original_sender; this.xmit_dest=xmit_dest; this.low=low; this.high=high; } public String toString() { StringBuilder sb=new StringBuilder(); sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #[").append(low); sb.append("-").append(high).append("]"); sb.append(" (XMIT_REQ sent to ").append(xmit_dest).append(")"); return sb.toString(); } } static class MissingMessage { final Address original_sender; final long seq, timestamp=System.currentTimeMillis(); MissingMessage(Address original_sender, long seqno) { this.original_sender=original_sender; this.seq=seqno; } public String toString() { StringBuilder sb=new StringBuilder(); sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #").append(seq); return sb.toString(); } } }
package org.jgroups.protocols.pbcast; import org.jgroups.*; import org.jgroups.annotations.*; import org.jgroups.conf.PropertyConverters; import org.jgroups.protocols.TP; import org.jgroups.stack.*; import org.jgroups.util.BoundedList; import org.jgroups.util.Digest; import org.jgroups.util.TimeScheduler; import org.jgroups.util.Util; import java.util.*; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Negative AcKnowledgement layer (NAKs). Messages are assigned a monotonically * increasing sequence number (seqno). Receivers deliver messages ordered * according to seqno and request retransmission of missing messages.<br/> * Retransmit requests are usually sent to the original sender of a message, but * this can be changed by xmit_from_random_member (send to random member) or * use_mcast_xmit_req (send to everyone). Responses can also be sent to everyone * instead of the requester by setting use_mcast_xmit to true. * * @author Bela Ban */ @MBean(description="Reliable transmission multipoint FIFO protocol") public class NAKACK extends Protocol implements Retransmitter.RetransmitCommand, DiagnosticsHandler.ProbeHandler { private static final int NUM_REBROADCAST_MSGS=3; @Property(name="retransmit_timeout", converter=PropertyConverters.IntegerArray.class, description="Timeout before requesting retransmissions") private int[] retransmit_timeouts= { 600, 1200, 2400, 4800 }; // time(s) to wait before requesting retransmission @Property(description="Max number of messages to be removed from a NakReceiverWindow. This property might " + "get removed anytime, so don't use it !") private int max_msg_batch_size=100; /** * Retransmit messages using multicast rather than unicast. This has the advantage that, if many receivers * lost a message, the sender only retransmits once */ @Property(description="Retransmit retransmit responses (messages) using multicast rather than unicast") private boolean use_mcast_xmit=true; /** * Use a multicast to request retransmission of missing messages. This may * be costly as every member in the cluster will send a response */ @Property(description="Use a multicast to request retransmission of missing messages") private boolean use_mcast_xmit_req=false; @Property(description="Number of milliseconds to delay the sending of an XMIT request. We pick a random number " + "in the range [1 .. xmit_req_stagger_timeout] and add this to the scheduling time of an XMIT request. " + "When use_mcast_xmit is enabled, if a number of members drop messages from the same member, then chances are that, " + "if staggering is enabled, somebody else already sent the XMIT request (via mcast) and we can cancel the XMIT " + "request once we receive the missing messages. For unicast XMIT responses (use_mcast_xmit=false), we still have " + "an advantage by not overwhelming the receiver with XMIT requests, all at the same time. 0 disabless staggering.") protected long xmit_stagger_timeout=200; /** * Ask a random member for retransmission of a missing message. If set to * true, discard_delivered_msgs will be set to false */ @Property(description="Ask a random member for retransmission of a missing message. Default is false") private boolean xmit_from_random_member=false; /** * The first value (in milliseconds) to use in the exponential backoff * retransmission mechanism. Only enabled if the value is > 0 */ @Property(description="The first value (in milliseconds) to use in the exponential backoff. Enabled if greater than 0") private int exponential_backoff=300; @Property(description="Whether to use the old retransmitter which retransmits individual messages or the new one " + "which uses ranges of retransmitted messages. Default is true. Note that this property will be removed in 3.0; " + "it is only used to switch back to the old (and proven) retransmitter mechanism if issues occur") private boolean use_range_based_retransmitter=true; /** * Messages that have been received in order are sent up the stack (= * delivered to the application). Delivered messages are removed from * NakReceiverWindow.xmit_table and moved to * NakReceiverWindow.delivered_msgs, where they are later garbage collected * (by STABLE). Since we do retransmits only from sent messages, never * received or delivered messages, we can turn the moving to delivered_msgs * off, so we don't keep the message around, and don't need to wait for * garbage collection to remove them. */ @Property(description="Should messages delivered to application be discarded") private boolean discard_delivered_msgs=true; @Property(description="Timeout to rebroadcast messages. Default is 2000 msec") private long max_rebroadcast_timeout=2000; /** * When not finding a message on an XMIT request, include the last N * stability messages in the error message */ @Property(description="Should stability history be printed if we fail in retransmission. Default is false") protected boolean print_stability_history_on_failed_xmit=false; /** If true, logs messages discarded because received from other members */ @Property(description="discards warnings about promiscuous traffic") private boolean log_discard_msgs=true; @Property(description="If true, trashes warnings about retransmission messages not found in the xmit_table (used for testing)") private boolean log_not_found_msgs=true; @Property(description="Number of rows of the matrix in the retransmission table (only for experts)",writable=false) int xmit_table_num_rows=5; @Property(description="Number of elements of a row of the matrix in the retransmission table (only for experts). " + "The capacity of the matrix is xmit_table_num_rows * xmit_table_msgs_per_row",writable=false) int xmit_table_msgs_per_row=10000; @Property(description="Resize factor of the matrix in the retransmission table (only for experts)",writable=false) double xmit_table_resize_factor=1.2; @Property(description="Number of milliseconds after which the matrix in the retransmission table " + "is compacted (only for experts)",writable=false) long xmit_table_max_compaction_time=10 * 60 * 1000; @ManagedAttribute(description="Number of retransmit requests received") private final AtomicLong xmit_reqs_received=new AtomicLong(0); @ManagedAttribute(description="Number of retransmit requests sent") private final AtomicLong xmit_reqs_sent=new AtomicLong(0); @ManagedAttribute(description="Number of retransmit responses received") private final AtomicLong xmit_rsps_received=new AtomicLong(0); @ManagedAttribute(description="Number of retransmit responses sent") private final AtomicLong xmit_rsps_sent=new AtomicLong(0); @ManagedAttribute(description="Number of messages sent") protected int num_messages_sent=0; @ManagedAttribute(description="Number of messages received") protected int num_messages_received=0; private boolean is_server=false; private Address local_addr=null; private final List<Address> members=new CopyOnWriteArrayList<Address>(); private View view; private final AtomicLong seqno=new AtomicLong(0); // current message sequence number (starts with 1) /** Map to store sent and received messages (keyed by sender) */ private final ConcurrentMap<Address,NakReceiverWindow> xmit_table=Util.createConcurrentMap(); private volatile boolean leaving=false; private volatile boolean running=false; private TimeScheduler timer=null; private final Lock rebroadcast_lock=new ReentrantLock(); private final Condition rebroadcast_done=rebroadcast_lock.newCondition(); // set during processing of a rebroadcast event private volatile boolean rebroadcasting=false; private final Lock rebroadcast_digest_lock=new ReentrantLock(); @GuardedBy("rebroadcast_digest_lock") private Digest rebroadcast_digest=null; /** BoundedList<Digest>, keeps the last 10 stability messages */ protected final BoundedList<Digest> stability_msgs=new BoundedList<Digest>(10); /** Keeps a bounded list of the last N digest sets */ protected final BoundedList<String> digest_history=new BoundedList<String>(10); public long getXmitRequestsReceived() {return xmit_reqs_received.get();} public long getXmitRequestsSent() {return xmit_reqs_sent.get();} public long getXmitResponsesReceived() {return xmit_rsps_received.get();} public long getXmitResponsesSent() {return xmit_rsps_sent.get();} @ManagedAttribute(description="Total number of missing messages") public int getPendingXmitRequests() { int num=0; for(NakReceiverWindow win: xmit_table.values()) { num+=win.getPendingXmits(); } return num; } @ManagedAttribute public int getXmitTableSize() { int num=0; for(NakReceiverWindow win: xmit_table.values()) { num+=win.size(); } return num; } @ManagedAttribute public int getXmitTableMissingMessages() { int num=0; for(NakReceiverWindow win: xmit_table.values()) { num+=win.getMissingMessages(); } return num; } @ManagedAttribute(description="Returns the number of bytes of all messages in all NakReceiverWindows. To compute " + "the size, Message.getLength() is used") public long getSizeOfAllMessages() { long retval=0; for(NakReceiverWindow win: xmit_table.values()) retval+=win.sizeOfAllMessages(false); return retval; } @ManagedAttribute(description="Returns the number of bytes of all messages in all NakReceiverWindows. To compute " + "the size, Message.size() is used") public long getSizeOfAllMessagesInclHeaders() { long retval=0; for(NakReceiverWindow win: xmit_table.values()) retval+=win.sizeOfAllMessages(true); return retval; } @ManagedAttribute public long getCurrentSeqno() {return seqno.get();} @ManagedOperation public String printRetransmitStats() { StringBuilder sb=new StringBuilder(); for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) sb.append(entry.getKey()).append(": ").append(entry.getValue().printRetransmitStats()).append("\n"); return sb.toString(); } /** * Please don't use this method; it is only provided for unit testing ! * @param mbr * @return */ public NakReceiverWindow getWindow(Address mbr) { return xmit_table.get(mbr); } /** * Only used for unit tests, don't use ! * @param timer */ public void setTimer(TimeScheduler timer) { this.timer=timer; } public void resetStats() { num_messages_sent=num_messages_received=0; xmit_reqs_received.set(0); xmit_reqs_sent.set(0); xmit_rsps_received.set(0); xmit_rsps_sent.set(0); stability_msgs.clear(); digest_history.clear(); } public void init() throws Exception { if(xmit_from_random_member) { if(discard_delivered_msgs) { discard_delivered_msgs=false; log.debug("xmit_from_random_member set to true: changed discard_delivered_msgs to false"); } } TP transport=getTransport(); if(transport != null) { transport.registerProbeHandler(this); if(!transport.supportsMulticasting()) { if(use_mcast_xmit) { log.warn("use_mcast_xmit should not be used because the transport (" + transport.getName() + ") does not support IP multicasting; setting use_mcast_xmit to false"); use_mcast_xmit=false; } if(use_mcast_xmit_req) { log.warn("use_mcast_xmit_req should not be used because the transport (" + transport.getName() + ") does not support IP multicasting; setting use_mcast_xmit_req to false"); use_mcast_xmit_req=false; } } } } public boolean isUseMcastXmit() { return use_mcast_xmit; } public void setUseMcastXmit(boolean use_mcast_xmit) { this.use_mcast_xmit=use_mcast_xmit; } public boolean isXmitFromRandomMember() { return xmit_from_random_member; } public void setXmitFromRandomMember(boolean xmit_from_random_member) { this.xmit_from_random_member=xmit_from_random_member; } public boolean isDiscardDeliveredMsgs() { return discard_delivered_msgs; } public void setDiscardDeliveredMsgs(boolean discard_delivered_msgs) { this.discard_delivered_msgs=discard_delivered_msgs; } public void setLogDiscardMessages(boolean flag) { log_discard_msgs=flag; } public void setLogDiscardMsgs(boolean flag) { setLogDiscardMessages(flag); } public boolean getLogDiscardMessages() { return log_discard_msgs; } public Map<String,Object> dumpStats() { Map<String,Object> retval=super.dumpStats(); retval.put("msgs", printMessages()); return retval; } public String printStats() { StringBuilder sb=new StringBuilder(); sb.append("\nStability messages received\n"); sb.append(printStabilityMessages()).append("\n"); return sb.toString(); } @ManagedOperation(description="TODO") public String printStabilityMessages() { StringBuilder sb=new StringBuilder(); sb.append(Util.printListWithDelimiter(stability_msgs, "\n")); return sb.toString(); } public String printStabilityHistory() { StringBuilder sb=new StringBuilder(); int i=1; for(Digest digest: stability_msgs) { sb.append(i++).append(": ").append(digest).append("\n"); } return sb.toString(); } @ManagedOperation(description="Keeps information about the last N times a digest was set or merged") public String printDigestHistory() { StringBuilder sb=new StringBuilder(local_addr + ":\n"); for(String tmp: digest_history) sb.append(tmp).append("\n"); return sb.toString(); } @ManagedOperation(description="TODO") public String printLossRates() { StringBuilder sb=new StringBuilder(); NakReceiverWindow win; for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) { win=entry.getValue(); sb.append(entry.getKey()).append(": ").append(win.printLossRate()).append("\n"); } return sb.toString(); } @ManagedOperation(description="Returns the sizes of all NakReceiverWindow.RetransmitTables") public String printRetransmitTableSizes() { StringBuilder sb=new StringBuilder(); for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) { NakReceiverWindow win=entry.getValue(); sb.append(entry.getKey() + ": ").append(win.getRetransmitTableSize()) .append(", offset=").append(win.getRetransmitTableOffset()) .append(" (capacity=" + win.getRetransmitTableCapacity()) .append(", fill factor=" + win.getRetransmitTableFillFactor() + "%)\n"); } return sb.toString(); } @ManagedOperation(description="Compacts the retransmission tables") public void compact() { for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) { NakReceiverWindow win=entry.getValue(); win.compact(); } } public List<Integer> providedUpServices() { List<Integer> retval=new ArrayList<Integer>(5); retval.add(Event.GET_DIGEST); retval.add(Event.SET_DIGEST); retval.add(Event.OVERWRITE_DIGEST); retval.add(Event.MERGE_DIGEST); return retval; } public void start() throws Exception { timer=getTransport().getTimer(); if(timer == null) throw new Exception("timer is null"); running=true; leaving=false; } public void stop() { running=false; reset(); // clears sent_msgs and destroys all NakReceiverWindows } /** * <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>down_prot.down()</code> in this * method as the event is passed down by default by the superclass after this method returns !</b> */ public Object down(Event evt) { switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); Address dest=msg.getDest(); if(dest != null || msg.isFlagSet(Message.NO_RELIABILITY)) break; // unicast address: not null and not mcast, pass down unchanged send(evt, msg); return null; // don't pass down the stack case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg stable((Digest)evt.getArg()); return null; // do not pass down further (Bela Aug 7 2001) case Event.GET_DIGEST: return getDigest((Address)evt.getArg()); case Event.SET_DIGEST: setDigest((Digest)evt.getArg()); return null; case Event.OVERWRITE_DIGEST: overwriteDigest((Digest)evt.getArg()); return null; case Event.MERGE_DIGEST: mergeDigest((Digest)evt.getArg()); return null; case Event.TMP_VIEW: View tmp_view=(View)evt.getArg(); List<Address> mbrs=tmp_view.getMembers(); members.clear(); members.addAll(mbrs); break; case Event.VIEW_CHANGE: tmp_view=(View)evt.getArg(); mbrs=tmp_view.getMembers(); members.clear(); members.addAll(mbrs); view=tmp_view; adjustReceivers(members); is_server=true; // check vids from now on break; case Event.BECOME_SERVER: is_server=true; break; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; case Event.DISCONNECT: leaving=true; reset(); break; case Event.REBROADCAST: rebroadcasting=true; rebroadcast_digest=(Digest)evt.getArg(); try { rebroadcastMessages(); } finally { rebroadcasting=false; rebroadcast_digest_lock.lock(); try { rebroadcast_digest=null; } finally { rebroadcast_digest_lock.unlock(); } } return null; case Event.ADD_TO_XMIT_TABLE: msg=(Message)evt.getArg(); dest=msg.getDest(); if(dest != null || msg.isFlagSet(Message.NO_RELIABILITY)) return null; // unicast address: not null and not mcast, pass down unchanged send(evt, msg, false); // add to retransmit window, but don't send (we want to avoid the unneeded traffic) return null; // don't pass down the stack } return down_prot.down(evt); } /** * <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>PassUp</code> in this * method as the event is passed up by default by the superclass after this method returns !</b> */ public Object up(Event evt) { switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); if(msg.isFlagSet(Message.NO_RELIABILITY)) break; NakAckHeader hdr=(NakAckHeader)msg.getHeader(this.id); if(hdr == null) break; // pass up (e.g. unicast msg) if(!is_server) { // discard messages while not yet server (i.e., until JOIN has returned) if(log.isTraceEnabled()) log.trace(local_addr + ": message " + msg.getSrc() + "::" + hdr.seqno + " was discarded (not yet server)"); return null; } // Changed by bela Jan 29 2003: we must not remove the header, otherwise further xmit requests will fail ! //hdr=(NakAckHeader)msg.removeHeader(getName()); switch(hdr.type) { case NakAckHeader.MSG: handleMessage(msg, hdr); return null; // transmitter passes message up for us ! case NakAckHeader.XMIT_REQ: if(hdr.range == null) { if(log.isErrorEnabled()) { log.error("XMIT_REQ: range of xmit msg is null; discarding request from " + msg.getSrc()); } return null; } handleXmitReq(msg.getSrc(), hdr.range.low, hdr.range.high, hdr.sender); return null; case NakAckHeader.XMIT_RSP: handleXmitRsp(msg, hdr); return null; default: if(log.isErrorEnabled()) { log.error("NakAck header type " + hdr.type + " not known !"); } return null; } case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg stable((Digest)evt.getArg()); return null; // do not pass up further (Bela Aug 7 2001) case Event.SUSPECT: // release the promise if rebroadcasting is in progress... otherwise we wait forever. there will be a new // flush round anyway if(rebroadcasting) { cancelRebroadcasting(); } break; } return up_prot.up(evt); } protected void send(Event evt, Message msg, boolean pass_down) { if(msg == null) throw new NullPointerException("msg is null; event is " + evt); if(!running) { if(log.isTraceEnabled()) log.trace(local_addr + ": discarded message as we're not in the 'running' state, message: " + msg); return; } long msg_id; NakReceiverWindow win=xmit_table.get(local_addr); if(win == null) { // discard message if there is no entry for local_addr if(log.isWarnEnabled() && log_discard_msgs) log.warn(local_addr + ": discarded message to " + local_addr + " with no window, my view is " + view); return; } if(msg.getSrc() == null) msg.setSrc(local_addr); // this needs to be done so we can check whether the message sender is the local_addr msg_id=seqno.incrementAndGet(); long sleep=10; while(running) { try { msg.putHeader(this.id, NakAckHeader.createMessageHeader(msg_id)); win.add(msg_id, msg); break; } catch(Throwable t) { if(running) Util.sleep(sleep); sleep=Math.min(5000, sleep*2); } } if(!pass_down) return; try { if(log.isTraceEnabled()) log.trace("sending " + local_addr + "#" + msg_id); down_prot.down(evt); // if this fails, since msg is in sent_msgs, it can be retransmitted num_messages_sent++; } catch(Throwable t) { // eat the exception, don't pass it up the stack if(log.isWarnEnabled()) { log.warn("failure passing message down", t); } } } protected void send(Event evt, Message msg) { send(evt, msg, true); } /** * Finds the corresponding NakReceiverWindow and adds the message to it (according to seqno). Then removes as many * messages as possible from the NRW and passes them up the stack. Discards messages from non-members. */ private void handleMessage(Message msg, NakAckHeader hdr) { Address sender=msg.getSrc(); if(sender == null) { if(log.isErrorEnabled()) log.error("sender of message is null"); return; } NakReceiverWindow win=xmit_table.get(sender); if(win == null) { // discard message if there is no entry for sender if(leaving) return; if(log.isWarnEnabled() && log_discard_msgs) log.warn(local_addr + ": dropped message " + hdr.seqno + " from " + sender + " (sender not in table " + xmit_table.keySet() +"), view=" + view); return; } num_messages_received++; boolean loopback=local_addr.equals(sender); boolean added=loopback || win.add(hdr.seqno, msg); if(added && log.isTraceEnabled()) log.trace(new StringBuilder().append(local_addr).append(": received ").append(sender).append('#').append(hdr.seqno)); if(added && msg.isFlagSet(Message.OOB)) { if(loopback) msg=win.get(hdr.seqno); // we *have* to get a message, because loopback means we didn't add it to win ! if(msg != null && msg.isFlagSet(Message.OOB)) { if(msg.setTransientFlagIfAbsent(Message.OOB_DELIVERED)) up_prot.up(new Event(Event.MSG, msg)); } } // Efficient way of checking whether another thread is already processing messages from 'sender'. // If that's the case, we return immediately and let the existing thread process our message // can be returned to the thread pool final AtomicBoolean processing=win.getProcessing(); if(!processing.compareAndSet(false, true)) { return; } boolean remove_msgs=discard_delivered_msgs && !loopback; boolean released_processing=false; try { while(true) { // we're removing a msg and set processing to false (if null) *atomically* (wrt to add()) List<Message> msgs=win.removeMany(processing, remove_msgs, max_msg_batch_size); if(msgs == null || msgs.isEmpty()) { released_processing=true; if(rebroadcasting) checkForRebroadcasts(); return; } for(final Message msg_to_deliver: msgs) { if(msg_to_deliver.isFlagSet(Message.OOB) && !msg_to_deliver.setTransientFlagIfAbsent(Message.OOB_DELIVERED)) continue; //msg_to_deliver.removeHeader(getName()); // Changed by bela Jan 29 2003: not needed (see above) try { up_prot.up(new Event(Event.MSG, msg_to_deliver)); } catch(Throwable t) { log.error("couldn't deliver message " + msg_to_deliver, t); } } } } finally { // processing is always set in win.remove(processing) above and never here ! This code is just a // 2nd line of defense should there be an exception before win.remove(processing) sets processing if(!released_processing) processing.set(false); } } /** * Retransmits messsages first_seqno to last_seqno from original_sender from xmit_table to xmit_requester, * called when XMIT_REQ is received. * @param xmit_requester The sender of the XMIT_REQ, we have to send the requested copy of the message to this address * @param first_seqno The first sequence number to be retransmitted (<= last_seqno) * @param last_seqno The last sequence number to be retransmitted (>= first_seqno) * @param original_sender The member who originally sent the messsage. Guaranteed to be non-null */ private void handleXmitReq(Address xmit_requester, long first_seqno, long last_seqno, Address original_sender) { if(first_seqno > last_seqno) return; if(log.isTraceEnabled()) { StringBuilder sb=new StringBuilder(); sb.append(local_addr).append(": received xmit request from ").append(xmit_requester).append(" for "); sb.append(original_sender).append(" [").append(first_seqno).append(" - ").append(last_seqno).append("]"); log.trace(sb.toString()); } if(stats) xmit_reqs_received.addAndGet(last_seqno - first_seqno +1); NakReceiverWindow win=xmit_table.get(original_sender); if(win == null) { if(log.isErrorEnabled()) { StringBuilder sb=new StringBuilder(); sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); sb.append(") ").append(original_sender).append(" not found in retransmission table"); // don't print the table unless we are in trace mode because it can be LARGE if (log.isTraceEnabled()) { sb.append(":\n").append(printMessages()); } if(print_stability_history_on_failed_xmit) { sb.append(" (stability history:\n").append(printStabilityHistory()); } log.error(sb.toString()); } return; } long diff=last_seqno - first_seqno +1; if(diff >= 10) { List<Message> msgs=win.get(first_seqno, last_seqno); if(msgs != null) { for(Message msg: msgs) sendXmitRsp(xmit_requester, msg); } } else { for(long i=first_seqno; i <= last_seqno; i++) { Message msg=win.get(i); if(msg == null) { if(log.isWarnEnabled() && log_not_found_msgs && !local_addr.equals(xmit_requester)) { StringBuilder sb=new StringBuilder(); sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); sb.append(") message ").append(original_sender).append("::").append(i); sb.append(" not found in retransmission table of ").append(original_sender).append(":\n").append(win); if(print_stability_history_on_failed_xmit) { sb.append(" (stability history:\n").append(printStabilityHistory()); } log.warn(sb.toString()); } continue; } sendXmitRsp(xmit_requester, msg); } } } private void cancelRebroadcasting() { rebroadcast_lock.lock(); try { rebroadcasting=false; rebroadcast_done.signalAll(); } finally { rebroadcast_lock.unlock(); } } /** * Sends a message msg to the requester. We have to wrap the original message into a retransmit message, as we need * to preserve the original message's properties, such as src, headers etc. * @param dest * @param msg */ private void sendXmitRsp(Address dest, Message msg) { if(msg == null) { if(log.isErrorEnabled()) log.error("message is null, cannot send retransmission"); return; } if(stats) xmit_rsps_sent.incrementAndGet(); if(msg.getSrc() == null) msg.setSrc(local_addr); if(use_mcast_xmit) { // we simply send the original multicast message down_prot.down(new Event(Event.MSG, msg)); return; } Message xmit_msg=msg.copy(true, true); // copy payload and headers xmit_msg.setDest(dest); NakAckHeader hdr=(NakAckHeader)xmit_msg.getHeader(id); hdr.type=NakAckHeader.XMIT_RSP; // change the type in the copy from MSG --> XMIT_RSP down_prot.down(new Event(Event.MSG, xmit_msg)); } private void handleXmitRsp(Message msg, NakAckHeader hdr) { if(msg == null) return; try { if(stats) xmit_rsps_received.incrementAndGet(); msg.setDest(null); hdr.type=NakAckHeader.MSG; // change the type back from XMIT_RSP --> MSG up(new Event(Event.MSG, msg)); if(rebroadcasting) checkForRebroadcasts(); } catch(Exception ex) { if(log.isErrorEnabled()) { log.error("failed reading retransmitted message", ex); } } } /** * Takes the argument highest_seqnos and compares it to the current digest. If the current digest has fewer messages, * then send retransmit messages for the missing messages. Return when all missing messages have been received. If * we're waiting for a missing message from P, and P crashes while waiting, we need to exclude P from the wait set. */ private void rebroadcastMessages() { Digest their_digest; long sleep=max_rebroadcast_timeout / NUM_REBROADCAST_MSGS; long wait_time=max_rebroadcast_timeout, start=System.currentTimeMillis(); while(wait_time > 0) { rebroadcast_digest_lock.lock(); try { if(rebroadcast_digest == null) break; their_digest=rebroadcast_digest.copy(); } finally { rebroadcast_digest_lock.unlock(); } Digest my_digest=getDigest(); boolean xmitted=false; for(Digest.DigestEntry entry: their_digest) { Address member=entry.getMember(); long[] my_entry=my_digest.get(member); if(my_entry == null) continue; long their_high=entry.getHighest(); // Cannot ask for 0 to be retransmitted because the first seqno in NAKACK and UNICAST(2) is always 1 ! // Also, we need to ask for retransmission of my_high+1, because we already *have* my_high, and don't // need it, so the retransmission range is [my_high+1 .. their_high]: *exclude* my_high, but *include* // their_high long my_high=Math.max(my_entry[0], my_entry[1]); if(their_high > my_high) { if(log.isTraceEnabled()) log.trace("[" + local_addr + "] fetching " + my_high + "-" + their_high + " from " + member); retransmit(my_high+1, their_high, member, true); // use multicast to send retransmit request xmitted=true; } } if(!xmitted) return; // we're done; no retransmissions are needed anymore. our digest is >= rebroadcast_digest rebroadcast_lock.lock(); try { try { my_digest=getDigest(); rebroadcast_digest_lock.lock(); try { if(!rebroadcasting || my_digest.isGreaterThanOrEqual(rebroadcast_digest)) return; } finally { rebroadcast_digest_lock.unlock(); } rebroadcast_done.await(sleep, TimeUnit.MILLISECONDS); wait_time-=(System.currentTimeMillis() - start); } catch(InterruptedException e) { } } finally { rebroadcast_lock.unlock(); } } } protected void checkForRebroadcasts() { Digest tmp=getDigest(); boolean cancel_rebroadcasting; rebroadcast_digest_lock.lock(); try { cancel_rebroadcasting=tmp.isGreaterThanOrEqual(rebroadcast_digest); } finally { rebroadcast_digest_lock.unlock(); } if(cancel_rebroadcasting) { cancelRebroadcasting(); } } /** * Remove old members from NakReceiverWindows. Essentially removes all entries from xmit_table that are not * in <code>members</code>. This method is not called concurrently multiple times */ private void adjustReceivers(List<Address> new_members) { for(Address member: xmit_table.keySet()) { if(!new_members.contains(member)) { if(local_addr != null && local_addr.equals(member)) continue; NakReceiverWindow win=xmit_table.remove(member); if(win != null) { win.destroy(); if(log.isDebugEnabled()) log.debug("removed " + member + " from xmit_table (not member anymore)"); } } } } /** * Returns a message digest: for each member P the highest delivered and received seqno is added */ public Digest getDigest() { final Map<Address,long[]> map=new HashMap<Address,long[]>(); for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) { Address sender=entry.getKey(); // guaranteed to be non-null (CCHM) NakReceiverWindow win=entry.getValue(); // guaranteed to be non-null (CCHM) long[] seqnos=win.getDigest(); map.put(sender, seqnos); } return new Digest(map); } public Digest getDigest(Address mbr) { if(mbr == null) return getDigest(); NakReceiverWindow win=xmit_table.get(mbr); if(win == null) return null; long[] seqnos=win.getDigest(); return new Digest(mbr, seqnos[0], seqnos[1]); } /** * Creates a NakReceiverWindow for each sender in the digest according to the sender's seqno. If NRW already exists, * reset it. */ private void setDigest(Digest digest) { setDigest(digest, false); } private void mergeDigest(Digest digest) { setDigest(digest, true); } /** * Overwrites existing entries, but does NOT remove entries not found in the digest * @param digest */ private void overwriteDigest(Digest digest) { if(digest == null) return; StringBuilder sb=new StringBuilder("\n[overwriteDigest()]\n"); sb.append("existing digest: " + getDigest()).append("\nnew digest: " + digest); for(Digest.DigestEntry entry: digest) { Address member=entry.getMember(); if(member == null) continue; long highest_delivered_seqno=entry.getHighestDeliveredSeqno(); NakReceiverWindow win=xmit_table.get(member); if(win != null) { if(local_addr.equals(member)) { win.setHighestDelivered(highest_delivered_seqno); continue; // don't destroy my own window } xmit_table.remove(member); win.destroy(); // stops retransmission } win=createNakReceiverWindow(member, highest_delivered_seqno); xmit_table.put(member, win); } sb.append("\n").append("resulting digest: " + getDigest()); digest_history.add(sb.toString()); if(log.isDebugEnabled()) log.debug(sb.toString()); } /** * Sets or merges the digest. If there is no entry for a given member in xmit_table, create a new NakReceiverWindow. * Else skip the existing entry, unless it is a merge. In this case, skip the existing entry if its seqno is * greater than or equal to the one in the digest, or reset the window and create a new one if not. * @param digest The digest * @param merge Whether to merge the new digest with our own, or not */ private void setDigest(Digest digest, boolean merge) { if(digest == null) return; StringBuilder sb=new StringBuilder(merge? "\n[" + local_addr + " mergeDigest()]\n" : "\n["+local_addr + " setDigest()]\n"); sb.append("existing digest: " + getDigest()).append("\nnew digest: " + digest); boolean set_own_seqno=false; for(Digest.DigestEntry entry: digest) { Address member=entry.getMember(); if(member == null) continue; long highest_delivered_seqno=entry.getHighestDeliveredSeqno(); NakReceiverWindow win=xmit_table.get(member); if(win != null) { // We only reset the window if its seqno is lower than the seqno shipped with the digest. Also, we if(!merge || (local_addr != null && local_addr.equals(member)) // never overwrite our own entry || win.getHighestDelivered() >= highest_delivered_seqno) // my seqno is >= digest's seqno for sender continue; xmit_table.remove(member); win.destroy(); // stops retransmission // to get here, merge must be false ! if(member.equals(local_addr)) { seqno.set(highest_delivered_seqno); set_own_seqno=true; } } win=createNakReceiverWindow(member, highest_delivered_seqno); xmit_table.put(member, win); } sb.append("\n").append("resulting digest: " + getDigest()); if(set_own_seqno) sb.append("\nnew seqno for " + local_addr + ": " + seqno); digest_history.add(sb.toString()); if(log.isDebugEnabled()) log.debug(sb.toString()); } private NakReceiverWindow createNakReceiverWindow(Address sender, long initial_seqno) { NakReceiverWindow win=new NakReceiverWindow(sender, this, initial_seqno, timer, use_range_based_retransmitter, xmit_table_num_rows, xmit_table_msgs_per_row, xmit_table_resize_factor, xmit_table_max_compaction_time, false); if(exponential_backoff > 0) win.setRetransmitTimeouts(new ExponentialInterval(exponential_backoff)); else win.setRetransmitTimeouts(new StaticInterval(retransmit_timeouts)); if(xmit_stagger_timeout > 0) win.setXmitStaggerTimeout(xmit_stagger_timeout); return win; } /** * Garbage collect messages that have been seen by all members. Update sent_msgs: for the sender P in the digest * which is equal to the local address, garbage collect all messages <= seqno at digest[P]. Update xmit_table: * for each sender P in the digest and its highest seqno seen SEQ, garbage collect all delivered_msgs in the * NakReceiverWindow corresponding to P which are <= seqno at digest[P]. */ private void stable(Digest digest) { NakReceiverWindow recv_win; long my_highest_rcvd; // highest seqno received in my digest for a sender P long stability_highest_rcvd; // highest seqno received in the stability vector for a sender P if(members == null || local_addr == null || digest == null) { if(log.isWarnEnabled()) log.warn("members, local_addr or digest are null !"); return; } if(log.isTraceEnabled()) { log.trace("received stable digest " + digest); } stability_msgs.add(digest); long high_seqno_delivered, high_seqno_received; for(Digest.DigestEntry entry: digest) { Address member=entry.getMember(); if(member == null) continue; high_seqno_delivered=entry.getHighestDeliveredSeqno(); high_seqno_received=entry.getHighestReceivedSeqno(); // check whether the last seqno received for a sender P in the stability vector is > last seqno // received for P in my digest. if yes, request retransmission (see "Last Message Dropped" topic // in DESIGN) recv_win=xmit_table.get(member); if(recv_win != null) { my_highest_rcvd=recv_win.getHighestReceived(); stability_highest_rcvd=high_seqno_received; if(stability_highest_rcvd >= 0 && stability_highest_rcvd > my_highest_rcvd) { if(log.isTraceEnabled()) { log.trace("my_highest_rcvd (" + my_highest_rcvd + ") < stability_highest_rcvd (" + stability_highest_rcvd + "): requesting retransmission of " + member + '#' + stability_highest_rcvd); } retransmit(stability_highest_rcvd, stability_highest_rcvd, member); } } if(high_seqno_delivered < 0) continue; if(log.isTraceEnabled()) log.trace("deleting msgs <= " + high_seqno_delivered + " from " + member); // delete *delivered* msgs that are stable if(recv_win != null) recv_win.stable(high_seqno_delivered); // delete all messages with seqnos <= seqno } } /** * Implementation of Retransmitter.RetransmitCommand. Called by retransmission thread when gap is detected. */ public void retransmit(long first_seqno, long last_seqno, Address sender) { if(first_seqno <= last_seqno) retransmit(first_seqno, last_seqno, sender, false); } protected void retransmit(long first_seqno, long last_seqno, final Address sender, boolean multicast_xmit_request) { NakAckHeader hdr; Message retransmit_msg; Address dest=sender; // to whom do we send the XMIT request ? if(multicast_xmit_request || this.use_mcast_xmit_req) { dest=null; } else { if(xmit_from_random_member && !local_addr.equals(sender)) { Address random_member=(Address)Util.pickRandomElement(members); if(random_member != null && !local_addr.equals(random_member)) { dest=random_member; if(log.isTraceEnabled()) log.trace("picked random member " + dest + " to send XMIT request to"); } } } hdr=NakAckHeader.createXmitRequestHeader(first_seqno, last_seqno, sender); retransmit_msg=new Message(dest, null, null); retransmit_msg.setFlag(Message.OOB); if(log.isTraceEnabled()) log.trace(local_addr + ": sending XMIT_REQ ([" + first_seqno + ", " + last_seqno + "]) to " + dest); retransmit_msg.putHeader(this.id, hdr); down_prot.down(new Event(Event.MSG, retransmit_msg)); if(stats) xmit_reqs_sent.addAndGet(last_seqno - first_seqno +1); } private void reset() { seqno.set(0); for(NakReceiverWindow win: xmit_table.values()) win.destroy(); xmit_table.clear(); } @ManagedOperation(description="Prints the contents of the receiver windows for all members") public String printMessages() { StringBuilder ret=new StringBuilder(local_addr + ":\n"); for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) { Address addr=entry.getKey(); NakReceiverWindow win=entry.getValue(); ret.append(addr).append(": ").append(win.toString()).append('\n'); } return ret.toString(); } // ProbeHandler interface public Map<String, String> handleProbe(String... keys) { Map<String,String> retval=new HashMap<String,String>(); for(String key: keys) { if(key.equals("digest-history")) retval.put(key, printDigestHistory()); if(key.equals("dump-digest")) retval.put(key, "\n" + printMessages()); } return retval; } // ProbeHandler interface public String[] supportedKeys() { return new String[]{"digest-history", "dump-digest"}; } }
package org.opennms.features.topology.app.internal.operations; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.opennms.features.topology.api.CheckedOperation; import org.opennms.features.topology.api.OperationContext; import org.opennms.features.topology.api.TopologyProvider; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class TopologySelector { private TopologyProvider m_activeTopologyProvider; private BundleContext m_bundleContext; private Map<TopologyProvider, TopologySelectorOperation> m_operations = new HashMap<TopologyProvider, TopologySelector.TopologySelectorOperation>(); private Map<TopologyProvider, ServiceRegistration> m_registrations = new HashMap<TopologyProvider, ServiceRegistration>(); private class TopologySelectorOperation implements CheckedOperation { private TopologyProvider m_topologyProvider; private Map m_metaData; public TopologySelectorOperation(TopologyProvider topologyProvider, Map metaData) { m_topologyProvider = topologyProvider; m_metaData = metaData; } public String getLabel() { return m_metaData.get("label") == null ? "No Label for Topology Provider" : (String)m_metaData.get("label"); } @Override public Undoer execute(List<Object> targets, OperationContext operationContext) { operationContext.getGraphContainer().setDataSource(m_topologyProvider); return null; } @Override public boolean display(List<Object> targets, OperationContext operationContext) { return true; } @Override public boolean enabled(List<Object> targets, OperationContext operationContext) { return true; } @Override public String getId() { return getLabel(); } @Override public boolean isChecked(List<Object> targets, OperationContext operationContext) { TopologyProvider activeTopologyProvider = operationContext.getGraphContainer().getDataSource(); System.err.println("Active Provider is " + activeTopologyProvider + ": Expected " + m_topologyProvider); return m_topologyProvider.equals(activeTopologyProvider); } } public void setBundleContext(BundleContext bundleContext) { m_bundleContext = bundleContext; } public void addTopologyProvider(TopologyProvider topologyProvider, Map metaData) { System.err.println("Adding Topology Provider " + topologyProvider); TopologySelectorOperation operation = new TopologySelectorOperation(topologyProvider, metaData); m_operations.put(topologyProvider, operation); Properties properties = new Properties(); properties.put("operation.menuLocation", "View|Topology"); properties.put("operation.label", operation.getLabel()); ServiceRegistration reg = m_bundleContext.registerService(CheckedOperation.class.getName(), operation, properties); m_registrations.put(topologyProvider, reg); } public void removeTopologyProvider(TopologyProvider topologyProvider, Map metaData) { System.err.println("Removing Topology Provider" + topologyProvider); m_operations.remove(topologyProvider); ServiceRegistration reg = m_registrations.remove(topologyProvider); if (reg != null) { reg.unregister(); } } }
// $Id: STABLE.java,v 1.45 2006/05/17 06:29:34 belaban Exp $ package org.jgroups.protocols.pbcast; import org.jgroups.*; import org.jgroups.stack.Protocol; import org.jgroups.util.Streamable; import org.jgroups.util.TimeScheduler; import org.jgroups.util.Util; import java.io.*; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Vector; /** * Computes the broadcast messages that are stable; i.e., have been received by all members. Sends * STABLE events up the stack when this is the case. This allows NAKACK to garbage collect messages that * have been seen by all members.<p> * Works as follows: periodically we mcast our highest seqnos (seen for each member) to the group. * A stability vector, which maintains the highest seqno for each member and initially contains no data, * is updated when such a message is received. The entry for a member P is computed set to * min(entry[P], digest[P]). When messages from all members have been received, a stability * message is mcast, which causes all members to send a STABLE event up the stack (triggering garbage collection * in the NAKACK layer).<p> * The stable task now terminates after max_num_gossips if no messages or view changes have been sent or received * in the meantime. It will resume when messages are received. This effectively suspends sending superfluous * STABLE messages in the face of no activity.<br/> * New: when <code>max_bytes</code> is exceeded (unless disabled by setting it to 0), * a STABLE task will be started (unless it is already running). * @author Bela Ban */ public class STABLE extends Protocol { Address local_addr=null; final Vector mbrs=new Vector(); final Digest digest=new Digest(10); // keeps track of the highest seqnos from all members final Digest latest_local_digest=new Digest(10); // keeps track of the latest digests received from NAKACK final Vector heard_from=new Vector(); // keeps track of who we already heard from (STABLE_GOSSIP msgs) /** Sends a STABLE gossip every 20 seconds on average. 0 disables gossipping of STABLE messages */ long desired_avg_gossip=20000; /** delay before we send STABILITY msg (give others a change to send first). This should be set to a very * small number (> 0 !) if <code>max_bytes</code> is used */ long stability_delay=6000; private StabilitySendTask stability_task=null; final Object stability_mutex=new Object(); // to synchronize on stability_task private volatile StableTask stable_task=null; // bcasts periodic STABLE message (added to timer below) final Object stable_task_mutex=new Object(); // to sync on stable_task TimeScheduler timer=null; // to send periodic STABLE msgs (and STABILITY messages) static final String name="STABLE"; /** Total amount of bytes from incoming messages (default = 0 = disabled). When exceeded, a STABLE * message will be broadcast and <code>num_bytes_received</code> reset to 0 . If this is > 0, then ideally * <code>stability_delay</code> should be set to a low number as well */ long max_bytes=0; /** The total number of bytes received from unicast and multicast messages */ long num_bytes_received=0; /** When true, don't take part in garbage collection protocol: neither send STABLE messages nor * handle STABILITY messages */ boolean suspended=false; boolean initialized=false; private ResumeTask resume_task=null; final Object resume_task_mutex=new Object(); /** Number of gossip messages */ int num_gossips=0; private static final long MAX_SUSPEND_TIME=200000; public String getName() { return name; } public long getDesiredAverageGossip() { return desired_avg_gossip; } public void setDesiredAverageGossip(long gossip_interval) { desired_avg_gossip=gossip_interval; } public long getMaxBytes() { return max_bytes; } public void setMaxBytes(long max_bytes) { this.max_bytes=max_bytes; } public int getNumberOfGossipMessages() {return num_gossips;} public void resetStats() { super.resetStats(); num_gossips=0; } public Vector requiredDownServices() { Vector retval=new Vector(); retval.addElement(new Integer(Event.GET_DIGEST_STABLE)); // NAKACK layer return retval; } public boolean setProperties(Properties props) { String str; super.setProperties(props); str=props.getProperty("digest_timeout"); if(str != null) { props.remove("digest_timeout"); log.error("digest_timeout has been deprecated; it will be ignored"); } str=props.getProperty("desired_avg_gossip"); if(str != null) { desired_avg_gossip=Long.parseLong(str); props.remove("desired_avg_gossip"); } str=props.getProperty("stability_delay"); if(str != null) { stability_delay=Long.parseLong(str); props.remove("stability_delay"); } str=props.getProperty("max_gossip_runs"); if(str != null) { props.remove("max_gossip_runs"); log.error("max_gossip_runs has been deprecated and will be ignored"); } str=props.getProperty("max_bytes"); if(str != null) { max_bytes=Long.parseLong(str); props.remove("max_bytes"); } str=props.getProperty("max_suspend_time"); if(str != null) { log.error("max_suspend_time is not supported any longer; please remove it (ignoring it)"); props.remove("max_suspend_time"); } if(props.size() > 0) { log.error("these properties are not recognized: " + props); return false; } return true; } private void suspend(long timeout) { if(!suspended) { suspended=true; if(log.isDebugEnabled()) log.debug("suspending message garbage collection"); } startResumeTask(timeout); // will not start task if already running } private void resume() { resetDigest(mbrs); // start from scratch suspended=false; if(log.isDebugEnabled()) log.debug("resuming message garbage collection"); stopResumeTask(); } public void start() throws Exception { if(stack != null && stack.timer != null) timer=stack.timer; else throw new Exception("timer cannot be retrieved from protocol stack"); if(desired_avg_gossip > 0) startStableTask(); } public void stop() { stopStableTask(); clearDigest(); } public void up(Event evt) { Message msg; StableHeader hdr; int type=evt.getType(); switch(type) { case Event.MSG: msg=(Message)evt.getArg(); // only if message counting is enabled, and only for multicast messages if(max_bytes > 0) { Address dest=msg.getDest(); if(dest != null && !dest.isMulticastAddress()) break; num_bytes_received+=(long)Math.max(msg.getLength(), 24); if(num_bytes_received >= max_bytes) { if(trace) { log.trace(new StringBuffer("max_bytes has been reached (").append(max_bytes). append(", bytes received=").append(num_bytes_received).append("): triggers stable msg")); } num_bytes_received=0; // asks the NAKACK protocol for the current digest, reply event is GET_DIGEST_STABLE_OK (arg=digest) passDown(new Event(Event.GET_DIGEST_STABLE)); } } hdr=(StableHeader)msg.removeHeader(name); if(hdr == null) break; switch(hdr.type) { case StableHeader.STABLE_GOSSIP: handleStableMessage(msg.getSrc(), hdr.stableDigest); break; case StableHeader.STABILITY: handleStabilityMessage(hdr.stableDigest, msg.getSrc()); break; default: if(log.isErrorEnabled()) log.error("StableHeader type " + hdr.type + " not known"); } return; // don't pass STABLE or STABILITY messages up the stack case Event.GET_DIGEST_STABLE_OK: Digest d=(Digest)evt.getArg(); synchronized(latest_local_digest) { latest_local_digest.replace(d); } if(trace) log.trace("setting latest_local_digest from NAKACK: " + d.printHighSeqnos()); sendStableMessage(d); break; case Event.VIEW_CHANGE: View view=(View)evt.getArg(); handleViewChange(view); break; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; } passUp(evt); } public void down(Event evt) { switch(evt.getType()) { case Event.VIEW_CHANGE: View v=(View)evt.getArg(); handleViewChange(v); break; case Event.SUSPEND_STABLE: long timeout=0; Object t=evt.getArg(); if(t != null && t instanceof Long) timeout=((Long)t).longValue(); suspend(timeout); break; case Event.RESUME_STABLE: resume(); break; } passDown(evt); } public void runMessageGarbageCollection() { Digest copy; synchronized(digest) { copy=digest.copy(); } sendStableMessage(copy); } private void handleViewChange(View v) { Vector tmp=v.getMembers(); mbrs.clear(); mbrs.addAll(tmp); adjustSenders(digest, tmp); adjustSenders(latest_local_digest, tmp); resetDigest(tmp); if(!initialized) initialized=true; } /** Digest and members are guaranteed to be non-null */ private static void adjustSenders(Digest d, Vector members) { synchronized(d) { // 1. remove all members from digest who are not in the view Iterator it=d.senders.keySet().iterator(); Address mbr; while(it.hasNext()) { mbr=(Address)it.next(); if(!members.contains(mbr)) it.remove(); } // 2. add members to digest which are in the new view but not in the digest for(int i=0; i < members.size(); i++) { mbr=(Address)members.get(i); if(!d.contains(mbr)) d.add(mbr, -1, -1); } } } private void clearDigest() { synchronized(digest) { digest.clear(); } } /** Update my own digest from a digest received by somebody else. Returns whether the update was successful. * Needs to be called with a lock on digest */ private boolean updateLocalDigest(Digest d, Address sender) { if(d == null || d.size() == 0) return false; if(!initialized) { if(trace) log.trace("STABLE message will not be handled as I'm not yet initialized"); return false; } if(!digest.sameSenders(d)) { if(trace) log.trace(new StringBuffer("received a digest ").append(d.printHighSeqnos()).append(" from "). append(sender).append(" which has different members than mine ("). append(digest.printHighSeqnos()).append("), discarding it and resetting heard_from list")); // to avoid sending incorrect stability/stable msgs, we simply reset our heard_from list, see DESIGN resetDigest(mbrs); return false; } StringBuffer sb=null; if(trace) sb=new StringBuffer("my [").append(local_addr).append("] digest before: ").append(digest). append("\ndigest from ").append(sender).append(": ").append(d); Address mbr; long highest_seqno, my_highest_seqno, new_highest_seqno; long highest_seen_seqno, my_highest_seen_seqno, new_highest_seen_seqno; Map.Entry entry; org.jgroups.protocols.pbcast.Digest.Entry val; for(Iterator it=d.senders.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); mbr=(Address)entry.getKey(); val=(org.jgroups.protocols.pbcast.Digest.Entry)entry.getValue(); highest_seqno=val.high_seqno; highest_seen_seqno=val.high_seqno_seen; // compute the minimum of the highest seqnos deliverable (for garbage collection) my_highest_seqno=digest.highSeqnoAt(mbr); // compute the maximum of the highest seqnos seen (for retransmission of last missing message) my_highest_seen_seqno=digest.highSeqnoSeenAt(mbr); new_highest_seqno=Math.min(my_highest_seqno, highest_seqno); new_highest_seen_seqno=Math.max(my_highest_seen_seqno, highest_seen_seqno); digest.setHighestDeliveredAndSeenSeqnos(mbr, new_highest_seqno, new_highest_seen_seqno); } if(trace) { sb.append("\nmy [").append(local_addr).append("] digest after: ").append(digest).append("\n"); log.trace(sb); } return true; } private void resetDigest(Vector new_members) { if(new_members == null || new_members.size() == 0) return; synchronized(heard_from) { heard_from.clear(); heard_from.addAll(new_members); } Digest copy_of_latest; synchronized(latest_local_digest) { copy_of_latest=latest_local_digest.copy(); } synchronized(digest) { digest.replace(copy_of_latest); if(trace) log.trace("resetting digest from NAKACK: " + copy_of_latest.printHighSeqnos()); } } /** * Removes mbr from heard_from and returns true if this was the last member, otherwise false. * Resets the heard_from list (populates with membership) * @param mbr */ private boolean removeFromHeardFromList(Address mbr) { synchronized(heard_from) { heard_from.remove(mbr); if(heard_from.size() == 0) { resetDigest(this.mbrs); return true; } } return false; } void startStableTask() { // Here, double-checked locking works: we don't want to synchronize if the task already runs (which is the case // 99% of the time). If stable_task gets nulled after the condition check, we return anyways, but just miss // 1 cycle: on the next message or view, we will start the task if(stable_task != null) return; synchronized(stable_task_mutex) { if(stable_task != null && stable_task.running()) { return; // already running } stable_task=new StableTask(); timer.add(stable_task, true); // fixed-rate scheduling } if(trace) log.trace("stable task started"); } void stopStableTask() { // contrary to startStableTask(), we don't need double-checked locking here because this method is not // called frequently synchronized(stable_task_mutex) { if(stable_task != null) { stable_task.stop(); stable_task=null; } } } void startResumeTask(long max_suspend_time) { max_suspend_time=(long)(max_suspend_time * 1.1); // little slack if(max_suspend_time <= 0) max_suspend_time=MAX_SUSPEND_TIME; synchronized(resume_task_mutex) { if(resume_task != null && resume_task.running()) { return; // already running } else { resume_task=new ResumeTask(max_suspend_time); timer.add(resume_task, true); // fixed-rate scheduling } } if(log.isDebugEnabled()) log.debug("resume task started, max_suspend_time=" + max_suspend_time); } void stopResumeTask() { synchronized(resume_task_mutex) { if(resume_task != null) { resume_task.stop(); resume_task=null; } } } void startStabilityTask(Digest d, long delay) { synchronized(stability_mutex) { if(stability_task != null && stability_task.running()) { } else { stability_task=new StabilitySendTask(d, delay); // runs only once timer.add(stability_task, true); } } } void stopStabilityTask() { synchronized(stability_mutex) { if(stability_task != null) { stability_task.stop(); stability_task=null; } } } /** Digest d contains (a) the highest seqnos <em>deliverable</em> for each sender and (b) the highest seqnos <em>seen</em> for each member. (Difference: with 1,2,4,5, the highest seqno seen is 5, whereas the highest seqno deliverable is 2). The minimum of all highest seqnos deliverable will be taken to send a stability message, which results in garbage collection of messages lower than the ones in the stability vector. The maximum of all seqnos will be taken to trigger possible retransmission of last missing seqno (see DESIGN for details). */ private void handleStableMessage(Address sender, Digest d) { if(d == null || sender == null) { if(log.isErrorEnabled()) log.error("digest or sender is null"); return; } if(!initialized) { if(trace) log.trace("STABLE message will not be handled as I'm not yet initialized"); return; } if(suspended) { if(trace) log.trace("STABLE message will not be handled as I'm suspended"); return; } if(trace) log.trace(new StringBuffer("received stable msg from ").append(sender).append(": ").append(d.printHighSeqnos())); if(!heard_from.contains(sender)) { // already received gossip from sender; discard it if(trace) log.trace("already received stable msg from " + sender); return; } Digest copy; synchronized(digest) { boolean success=updateLocalDigest(d, sender); if(!success) // we can only remove the sender from heard_from if *all* elements of my digest were updated return; copy=digest.copy(); } boolean was_last=removeFromHeardFromList(sender); if(was_last) { sendStabilityMessage(copy); } } /** * Bcasts a STABLE message of the current digest to all members. Message contains highest seqnos of all members * seen by this member. Highest seqnos are retrieved from the NAKACK layer below. * @param d A <em>copy</em> of this.digest */ private void sendStableMessage(Digest d) { if(suspended) { if(trace) log.trace("will not send STABLE message as I'm suspended"); return; } if(d != null && d.size() > 0) { if(trace) log.trace("sending stable msg " + d.printHighSeqnos()); Message msg=new Message(); // mcast message StableHeader hdr=new StableHeader(StableHeader.STABLE_GOSSIP, d); msg.putHeader(name, hdr); num_gossips++; passDown(new Event(Event.MSG, msg)); } } /** Schedules a stability message to be mcast after a random number of milliseconds (range 1-5 secs). The reason for waiting a random amount of time is that, in the worst case, all members receive a STABLE_GOSSIP message from the last outstanding member at the same time and would therefore mcast the STABILITY message at the same time too. To avoid this, each member waits random N msecs. If, before N elapses, some other member sent the STABILITY message, we just cancel our own message. If, during waiting for N msecs to send STABILITY message S1, another STABILITY message S2 is to be sent, we just discard S2. @param tmp A copy of te stability digest, so we don't need to copy it again */ void sendStabilityMessage(Digest tmp) { long delay; if(suspended) { if(trace) log.trace("STABILITY message will not be sent as I'm suspended"); return; } // give other members a chance to mcast STABILITY message. if we receive STABILITY by the end of // our random sleep, we will not send the STABILITY msg. this prevents that all mbrs mcast a // STABILITY msg at the same time delay=Util.random(stability_delay); startStabilityTask(tmp, delay); } void handleStabilityMessage(Digest d, Address sender) { if(d == null) { if(log.isErrorEnabled()) log.error("stability digest is null"); return; } if(!initialized) { if(trace) log.trace("STABLE message will not be handled as I'm not yet initialized"); return; } if(suspended) { if(log.isDebugEnabled()) { log.debug("stability message will not be handled as I'm suspended"); } return; } if(trace) log.trace(new StringBuffer("received stability msg from ").append(sender).append(": ").append(d.printHighSeqnos())); stopStabilityTask(); // we won't handle the gossip d, if d's members don't match the membership in my own digest, // this is part of the fix for the NAKACK problem (bugs #943480 and #938584) if(!this.digest.sameSenders(d)) { if(log.isDebugEnabled()) { log.debug("received digest (digest=" + d + ") which does not match my own digest ("+ this.digest + "): ignoring digest and re-initializing own digest"); } return; } resetDigest(mbrs); // pass STABLE event down the stack, so NAKACK can garbage collect old messages passDown(new Event(Event.STABLE, d)); } public static class StableHeader extends Header implements Streamable { public static final int STABLE_GOSSIP=1; public static final int STABILITY=2; int type=0; // Digest digest=new Digest(); // used for both STABLE_GOSSIP and STABILITY message Digest stableDigest=null; // changed by Bela April 4 2004 public StableHeader() { } // used for externalizable public StableHeader(int type, Digest digest) { this.type=type; this.stableDigest=digest; } static String type2String(int t) { switch(t) { case STABLE_GOSSIP: return "STABLE_GOSSIP"; case STABILITY: return "STABILITY"; default: return "<unknown>"; } } public String toString() { StringBuffer sb=new StringBuffer(); sb.append('['); sb.append(type2String(type)); sb.append("]: digest is "); sb.append(stableDigest); return sb.toString(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(type); if(stableDigest == null) { out.writeBoolean(false); return; } out.writeBoolean(true); stableDigest.writeExternal(out); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { type=in.readInt(); boolean digest_not_null=in.readBoolean(); if(digest_not_null) { stableDigest=new Digest(); stableDigest.readExternal(in); } } public long size() { long retval=Global.INT_SIZE + Global.BYTE_SIZE; // type + presence for digest if(stableDigest != null) retval+=stableDigest.serializedSize(); return retval; } public void writeTo(DataOutputStream out) throws IOException { out.writeInt(type); Util.writeStreamable(stableDigest, out); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type=in.readInt(); stableDigest=(Digest)Util.readStreamable(Digest.class, in); } } /** Mcast periodic STABLE message. Interval between sends varies. Terminates after num_gossip_runs is 0. However, UP or DOWN messages will reset num_gossip_runs to max_gossip_runs. This has the effect that the stable_send task terminates only after a period of time within which no messages were either sent or received */ private class StableTask implements TimeScheduler.Task { boolean stopped=false; public void stop() { stopped=true; } public boolean running() { // syntactic sugar return !stopped; } public boolean cancelled() { return stopped; } public long nextInterval() { long interval=computeSleepTime(); if(interval <= 0) return 10000; else return interval; } public void run() { if(suspended) { if(trace) log.trace("stable task will not run as suspended=" + suspended); return; } // asks the NAKACK protocol for the current digest, reply event is GET_DIGEST_STABLE_OK (arg=digest) passDown(new Event(Event.GET_DIGEST_STABLE)); } long computeSleepTime() { return getRandom((mbrs.size() * desired_avg_gossip * 2)); } long getRandom(long range) { return (long)((Math.random() * range) % range); } } /** * Multicasts a STABILITY message. */ private class StabilitySendTask implements TimeScheduler.Task { Digest d=null; boolean stopped=false; long delay=2000; StabilitySendTask(Digest d, long delay) { this.d=d; this.delay=delay; } public boolean running() { return !stopped; } public void stop() { stopped=true; } public boolean cancelled() { return stopped; } /** wait a random number of msecs (to give other a chance to send the STABILITY msg first) */ public long nextInterval() { return delay; } public void run() { Message msg; StableHeader hdr; if(suspended) { if(log.isDebugEnabled()) { log.debug("STABILITY message will not be sent as suspended=" + suspended); } stopped=true; return; } if(d != null && !stopped) { msg=new Message(); hdr=new StableHeader(StableHeader.STABILITY, d); msg.putHeader(STABLE.name, hdr); if(trace) log.trace("sending stability msg " + d.printHighSeqnos()); passDown(new Event(Event.MSG, msg)); d=null; } stopped=true; // run only once } } private class ResumeTask implements TimeScheduler.Task { boolean running=true; long max_suspend_time=0; ResumeTask(long max_suspend_time) { this.max_suspend_time=max_suspend_time; } void stop() { running=false; } public boolean running() { return running; } public boolean cancelled() { return running == false; } public long nextInterval() { return max_suspend_time; } public void run() { if(suspended) log.warn("ResumeTask resumed message garbage collection - this should be done by a RESUME_STABLE event; " + "check why this event was not received (or increase max_suspend_time for large state transfers)"); resume(); } } }
package ch.ntb.inf.deep.cgPPC; import ch.ntb.inf.deep.classItems.ICclassFileConsts; import ch.ntb.inf.deep.classItems.Method; import ch.ntb.inf.deep.cfg.*; import ch.ntb.inf.deep.ssa.*; import ch.ntb.inf.deep.ssa.instruction.*; import static org.junit.Assert.*; import ch.ntb.inf.deep.classItems.*; public class MachineCode implements SSAInstructionOpcs, SSAInstructionMnemonics, SSAValueType, InstructionOpcs, Registers, ICjvmInstructionOpcs, ICclassFileConsts { static final int maxNofParam = 32; private static final int defaultNofInstr = 16; private static final int defaultNofFixup = 8; private static final int arrayLenOffset = 6; private static final int arrayFirstOffset = 12; // Linker.getSizeOfObject() benutzen private static final int cppOffset = 24; private static final int constForDoubleConv = 32; private static int LRoffset; private static int GPRoffset; private static int FPRoffset; private static int localVarOffset; private static int tempStorageOffset; private static int paramOffset; private static int stackSize; static boolean tempStorage; private static int nofParam; private static int nofParamGPR, nofParamFPR; static int nofNonVolGPR, nofNonVolFPR; static int[] paramType = new int[maxNofParam]; static boolean[] paramHasNonVolReg = new boolean[maxNofParam]; static int[] paramRegNr = new int[maxNofParam]; // information about into which registers parameters of this method go private static int nofMoveGPR, nofMoveFPR; private static int[] moveGPR = new int[maxNofParam]; private static int[] moveFPR = new int[maxNofParam]; // information about into which registers parameters of a call to a method go private static int[] destGPR = new int[nofGPR]; private static int[] destFPR = new int[nofFPR]; private static SSAValue[] lastExitSet; private static SSA ssa; // reference to the SSA of a method int[] instructions; //contains machine instructions for the ssa of a method public int iCount; //nof instructions for this method Item[] fixups; // contains all references whose address has to be fixed by the linker int fCount; //nof fixups int lastFixup; // instr number where the last fixup is found public MachineCode(SSA ssa) { MachineCode.ssa = ssa; instructions = new int[defaultNofInstr]; fixups = new Item[defaultNofFixup]; nofParamGPR = 0; nofParamFPR = 0; nofNonVolGPR = 0; nofNonVolFPR = 0; nofMoveGPR = 0; nofMoveFPR = 0; tempStorage = false; // make local copy int maxStackSlots = ssa.cfg.method.maxStackSlots; int i = maxStackSlots; while ((i < ssa.isParam.length) && ssa.isParam[i]) { int type = ssa.paramType[i]; paramType[i - maxStackSlots] = type; paramHasNonVolReg[i - maxStackSlots] = false; if (type == tLong || type == tDouble) i++; i++; } nofParam = i - maxStackSlots; assert nofParam <= maxNofParam : "method has too many parameters"; System.out.println("build intervals for " + ssa.cfg.method.name); RegAllocator.buildIntervals(ssa); System.out.println("assign registers to parameters, nofParam = " + nofParam); SSANode b = (SSANode) ssa.cfg.rootNode; while (b.next != null) { b = (SSANode) b.next; } lastExitSet = b.exitSet; // determine, which parameters go into which register parseExitSet(lastExitSet, maxStackSlots); System.out.println("allocate registers"); RegAllocator.assignRegisters(this); ssa.print(0); stackSize = calcStackSize(); iCount = calcPrologSize(); SSANode node = (SSANode)ssa.cfg.rootNode; while (node != null) { node.codeStartAddr = iCount; translateSSA(node); node.codeEndAddr = iCount-1; node = (SSANode) node.next; } node = (SSANode)ssa.cfg.rootNode; while (node != null) { // resolve local branch targets if (node.nofInstr > 0) { if (node.instructions[node.nofInstr-1].ssaOpcode == sCbranch) { int code = this.instructions[node.codeEndAddr]; // System.out.println("target of branch instruction corrected: 0x" + Integer.toHexString(node.codeEndAddr*4)); CFGNode[] successors = node.successors; switch (code & 0xfc000000) { case ppcB: if ((code & 0xffff) != 0) { // switch int nofCases = (code & 0xffff) >> 2; int k; for (k = 0; k < nofCases; k++) { int branchOffset = ((SSANode)successors[k]).codeStartAddr - (node.codeEndAddr+1-(nofCases-k)*2); this.instructions[node.codeEndAddr+1-(nofCases-k)*2] |= (branchOffset << 2) & 0x3ffffff; } int branchOffset = ((SSANode)successors[k]).codeStartAddr - node.codeEndAddr; this.instructions[node.codeEndAddr] &= 0xfc000000; this.instructions[node.codeEndAddr] |= (branchOffset << 2) & 0x3ffffff; } else { // System.out.println("abs branch found"); int branchOffset = ((SSANode)successors[0]).codeStartAddr - node.codeEndAddr; this.instructions[node.codeEndAddr] |= (branchOffset << 2) & 0x3ffffff; } break; case ppcBc: // System.out.println("cond branch found"); int branchOffset = ((SSANode)successors[1]).codeStartAddr - node.codeEndAddr; this.instructions[node.codeEndAddr] |= (branchOffset << 2) & 0xffff; break; } } else if (node.instructions[node.nofInstr-1].ssaOpcode == sCreturn) { if (node.next != null) { int branchOffset = iCount - node.codeEndAddr; this.instructions[node.codeEndAddr] |= (branchOffset << 2) & 0x3ffffff; // System.out.println("return branch found, epilog start instr = " + iCount); } } } node = (SSANode) node.next; } insertEpilog(stackSize); insertProlog(); print(); } private static void parseExitSet(SSAValue[] exitSet, int maxStackSlots) { nofParamGPR = 0; nofParamFPR = 0; nofMoveGPR = 0; nofMoveFPR = 0; System.out.print("["); for (int i = 0; i < nofParam; i++) { int type = paramType[i]; System.out.print("(" + svNames[type] + ")"); if (type == tLong) { if (exitSet[i+maxStackSlots] != null) { // if null -> parameter is never used System.out.print("r"); if (paramHasNonVolReg[i]) { int reg = RegAllocator.reserveReg(gpr, true); int regLong = RegAllocator.reserveReg(gpr, true); moveGPR[nofMoveGPR] = nofParamGPR; moveGPR[nofMoveGPR+1] = nofParamGPR+1; nofMoveGPR += 2; paramRegNr[i] = reg; paramRegNr[i+1] = regLong; System.out.print(reg + ",r" + regLong); } else { RegAllocator.reserveReg(gpr, paramStartGPR + nofParamGPR); RegAllocator.reserveReg(gpr, paramStartGPR + nofParamGPR + 1); paramRegNr[i] = paramStartGPR + nofParamGPR; paramRegNr[i+1] = paramStartGPR + nofParamGPR + 1; System.out.print((paramStartGPR + nofParamGPR) + ",r" + (paramStartGPR + nofParamGPR + 1)); } } nofParamGPR += 2; i++; } else if (type == tFloat || type == tDouble) { if (exitSet[i+maxStackSlots] != null) { // if null -> parameter is never used System.out.print("fr"); if (paramHasNonVolReg[i]) { int reg = RegAllocator.reserveReg(fpr, true); moveFPR[nofMoveFPR] = nofParamFPR; nofMoveFPR++; paramRegNr[i] = reg; System.out.print(reg); } else { RegAllocator.reserveReg(fpr, paramStartFPR + nofParamFPR); paramRegNr[i] = paramStartFPR + nofParamFPR; System.out.print(paramStartFPR + nofParamFPR); } } nofParamFPR++; if (type == tDouble) i++; } else { if (exitSet[i+maxStackSlots] != null) { // if null -> parameter is never used System.out.print("r"); if (paramHasNonVolReg[i]) { int reg = RegAllocator.reserveReg(gpr, true); moveGPR[nofMoveGPR] = nofParamGPR; nofMoveGPR++; paramRegNr[i] = reg; System.out.print(reg); } else { RegAllocator.reserveReg(gpr, paramStartGPR + nofParamGPR); paramRegNr[i] = paramStartGPR + nofParamGPR; System.out.print(paramStartGPR + nofParamGPR); } } nofParamGPR++; } if (i < nofParam - 1) System.out.print(", "); } System.out.println("]"); } private static int calcStackSize() { int size = 16 + nofNonVolGPR * 4 + nofNonVolFPR * 8 + (tempStorage? 8 : 0); int padding = (16 - (size % 16)) % 16; size = size + padding; LRoffset = size - 4; GPRoffset = size - 12 - nofNonVolGPR * 4; FPRoffset = GPRoffset - nofNonVolFPR * 8; if (tempStorage) tempStorageOffset = FPRoffset - 8; else tempStorageOffset = FPRoffset; return size; } private static int calcPrologSize() { int size = 3; if (nofNonVolGPR > 0) size++; size = size + nofNonVolFPR + nofMoveGPR + nofMoveFPR; return size; } private void translateSSA (SSANode node) { SSAValue[] opds; int sReg1, sReg2, dReg, refReg, indexReg, valReg, bci, offset, type; for (int i = 0; i < node.nofInstr; i++) { SSAInstruction instr = node.instructions[i]; SSAValue res = instr.result; // System.out.println("ssa opcode = " + instr.scMnemonics[instr.ssaOpcode]); switch (instr.ssaOpcode) { case sCloadConst: opds = instr.getOperands(); dReg = res.reg; if (dReg >= 0) { // else immediate opd //System.out.println("dReg = " + dReg); switch (res.type) { case tByte: case tShort: case tInteger: int immVal = ((Constant)res.constant).valueH; loadConstant(immVal, dReg); break; case tLong: Constant constant = (Constant)res.constant; long immValLong = ((long)(constant.valueH)<<32) | (constant.valueL&0xFFFFFFFFL); // System.out.println("sdfsdge " + immValLong); loadConstant((int)(immValLong >> 32), res.regLong); loadConstant((int)immValLong, dReg); break; case tFloat: // load from const pool constant = (Constant)res.constant; if (constant.valueH == 0) { // 0.0 must be loaded directly as it's not in the cp createIrDrAsimm(ppcAddi, res.regAux1, 0, 0); createIrSrAd(ppcStw, res.regAux1, stackPtr, tempStorageOffset); createIrDrAd(ppcLfs, res.reg, stackPtr, tempStorageOffset); } else if (constant.valueH == 0x3f80) { createIrDrAsimm(ppcAddis, res.regAux1, 0, 0x3f80); createIrSrAd(ppcStw, res.regAux1, stackPtr, tempStorageOffset); createIrDrAd(ppcLfs, res.reg, stackPtr, tempStorageOffset); } else if (constant.valueH == 0x4000) { createIrDrAsimm(ppcAddis, res.regAux1, 0, 0x4000); createIrSrAd(ppcStw, res.regAux1, stackPtr, tempStorageOffset); createIrDrAd(ppcLfs, res.reg, stackPtr, tempStorageOffset); } else { loadConstantAndFixup(res.regAux1, constant); createIrDrAd(ppcLfs, res.reg, res.regAux1, cppOffset); } break; case tDouble: constant = (Constant)res.constant; if (constant.valueH == 0) { // 0.0 must be loaded directly as it's not in the cp createIrDrAsimm(ppcAddi, res.regAux1, 0, 0); createIrSrAd(ppcStw, res.regAux1, stackPtr, tempStorageOffset); createIrSrAd(ppcStw, res.regAux1, stackPtr, tempStorageOffset+4); createIrDrAd(ppcLfd, res.reg, stackPtr, tempStorageOffset); } else if (constant.valueH == 0x3ff0) { createIrDrAsimm(ppcAddis, res.regAux1, 0, 0x3ff0); createIrSrAd(ppcStw, res.regAux1, stackPtr, tempStorageOffset); createIrDrAsimm(ppcAddis, res.regAux1, 0, 0); createIrSrAd(ppcStw, res.regAux1, stackPtr, tempStorageOffset+4); createIrDrAd(ppcLfd, res.reg, stackPtr, tempStorageOffset); } else { loadConstantAndFixup(res.regAux1, constant); createIrDrAd(ppcLfd, res.reg, res.regAux1, cppOffset); } break; case tRef: // e.g. ref to const string loadConstantAndFixup(res.reg, res.constant); break; default: assert false : "cg: wrong type"; } } else break; // sCloadConst case sCloadLocal: break; // sCloadLocal case sCloadFromField: opds = instr.getOperands(); if (opds == null) { // getstatic sReg1 = instr.result.regAux1; Item field = ((NoOpndRef)instr).field; offset = field.offset; loadConstantAndFixup(sReg1, field); } else { // getfield sReg1 = opds[0].reg; offset = ((MonadicRef)instr).item.offset; createItrap(ppcTwi, TOifequal, opds[0].reg, 0); } switch (instr.result.type) { case tBoolean: case tByte: createIrDrAd(ppcLbz, instr.result.reg, sReg1, offset); createIrArS(ppcExtsb, instr.result.reg, instr.result.reg); break; case tShort: createIrDrAd(ppcLha, instr.result.reg, sReg1, offset); break; case tInteger: case tRef: case tAref: case tAboolean: case tAchar: case tAfloat: case tAdouble: case tAbyte: case tAshort: case tAinteger: case tAlong: createIrDrAd(ppcLwz, instr.result.reg, sReg1, offset); break; case tChar: assert false : "cg: type not implemented"; break; case tLong: createIrDrAd(ppcLwzu, instr.result.reg, sReg1, offset); createIrDrAd(ppcLwz, instr.result.regLong, sReg1, 4); break; case tFloat: createIrDrAd(ppcLfs, instr.result.reg, sReg1, offset); break; case tDouble: createIrDrAd(ppcLfd, instr.result.reg, sReg1, offset); break; default: assert false : "cg: wrong type"; } break; // sCloadFromField case sCloadFromArray: opds = instr.getOperands(); refReg = opds[0].reg; indexReg = opds[1].reg; createItrap(ppcTwi, TOifequal, refReg, 0); createIrDrAd(ppcLha, instr.result.regAux1, refReg, -arrayLenOffset); createItrap(ppcTw, TOifgeU, indexReg, instr.result.regAux1); switch (instr.result.type) { case tByte: case tBoolean: createIrDrAsimm(ppcAddi, instr.result.regAux2, refReg, arrayFirstOffset); createIrDrArB(ppcLbzx, instr.result.reg, instr.result.regAux2, indexReg); createIrArS(ppcExtsb, instr.result.reg, instr.result.reg); break; case tShort: createIrArSSHMBME(ppcRlwinm, instr.result.regAux1, indexReg, 1, 0, 30); createIrDrAsimm(ppcAddi, instr.result.regAux2, refReg, arrayFirstOffset); createIrDrArB(ppcLhax, instr.result.reg, instr.result.regAux1, instr.result.regAux2); break; case tInteger: case tRef: createIrArSSHMBME(ppcRlwinm, instr.result.regAux1, indexReg, 2, 0, 29); createIrDrAsimm(ppcAddi, instr.result.regAux2, refReg, arrayFirstOffset); createIrDrArB(ppcLwzx, instr.result.reg, instr.result.regAux1, instr.result.regAux2); break; case tLong: createIrArSSHMBME(ppcRlwinm, instr.result.regAux1, indexReg, 3, 0, 28); createIrDrAsimm(ppcAddi, instr.result.regAux2, refReg, arrayFirstOffset); createIrDrArB(ppcLwzux, instr.result.reg, instr.result.regAux1, instr.result.regAux2); createIrDrAd(ppcLwz, instr.result.regLong, instr.result.regAux1, 4); break; case tFloat: createIrArSSHMBME(ppcRlwinm, instr.result.regAux1, indexReg, 2, 0, 29); createIrDrAsimm(ppcAddi, instr.result.regAux2, refReg, arrayFirstOffset); createIrDrArB(ppcLfsx, instr.result.reg, instr.result.regAux1, instr.result.regAux2); break; case tDouble: createIrArSSHMBME(ppcRlwinm, instr.result.regAux1, indexReg, 3, 0, 28); createIrDrAsimm(ppcAddi, instr.result.regAux2, refReg, arrayFirstOffset); createIrDrArB(ppcLfdx, instr.result.reg, instr.result.regAux1, instr.result.regAux2); break; case tChar: assert false : "cg: type char not implemented"; break; default: assert false : "cg: type not implemented"; } break; // sCloadFromArray case sCstoreToField: opds = instr.getOperands(); if (opds.length == 1) { // putstatic sReg1 = opds[0].reg; sReg2 = opds[0].regLong; refReg = instr.result.regAux1; type = opds[0].type; Item item = ((MonadicRef)instr).item; offset = item.offset; loadConstantAndFixup(instr.result.regAux1, item); } else { // putfield refReg = opds[0].reg; sReg1 = opds[1].reg; sReg2 = opds[1].regLong; type = opds[1].type; offset = ((DyadicRef)instr).field.offset; createItrap(ppcTwi, TOifequal, refReg, 0); } switch (type) { case tBoolean: case tByte: createIrSrAd(ppcStb, sReg1, refReg, offset); break; case tShort: createIrSrAd(ppcSth, sReg1, refReg, offset); break; case tInteger: case tRef: case tAref: case tAboolean: case tAchar: case tAfloat: case tAdouble: case tAbyte: case tAshort: case tAinteger: case tAlong: createIrSrAd(ppcStw, sReg1, refReg, offset); break; case tChar: assert false : "cg: type not implemented"; break; case tLong: createIrSrAd(ppcStwu, sReg1, refReg, offset); createIrSrAd(ppcStw, sReg2, refReg, 4); break; case tFloat: createIrSrAd(ppcStfs, sReg1, refReg, offset); break; case tDouble: createIrSrAd(ppcStfd, sReg1, refReg, offset); break; default: assert false : "cg: wrong type"; } break; // sCstoreToField case sCstoreToArray: opds = instr.getOperands(); refReg = opds[0].reg; indexReg = opds[1].reg; valReg = opds[2].reg; createItrap(ppcTwi, TOifequal, refReg, 0); createIrDrAd(ppcLha, res.regAux1, refReg, -arrayLenOffset); createItrap(ppcTw, TOifgeU, indexReg, res.regAux1); switch (opds[2].type) { case tByte: createIrDrAsimm(ppcAddi, res.regAux2, refReg, arrayFirstOffset); createIrSrArB(ppcStbx, valReg, indexReg, res.regAux2); break; case tShort: createIrArSSHMBME(ppcRlwinm, res.regAux1, indexReg, 1, 0, 30); createIrDrAsimm(ppcAddi, res.regAux2, refReg, arrayFirstOffset); createIrSrArB(ppcSthx, valReg, res.regAux1, res.regAux2); break; case tInteger: case tRef: case tAref: case tAboolean: case tAchar: case tAfloat: case tAdouble: case tAbyte: case tAshort: case tAinteger: case tAlong: createIrArSSHMBME(ppcRlwinm, instr.result.regAux1, indexReg, 2, 0, 29); createIrDrAsimm(ppcAddi, instr.result.regAux2, refReg, arrayFirstOffset); createIrSrArB(ppcStwx, valReg, instr.result.regAux1, instr.result.regAux2); break; case tLong: createIrArSSHMBME(ppcRlwinm, instr.result.regAux1, indexReg, 3, 0, 28); createIrDrAsimm(ppcAddi, instr.result.regAux2, refReg, arrayFirstOffset); createIrSrArB(ppcStwux, valReg, instr.result.regAux1, instr.result.regAux2); createIrSrAd(ppcStw, opds[2].regLong, instr.result.regAux1, 4); break; case tFloat: createIrArSSHMBME(ppcRlwinm, instr.result.regAux1, indexReg, 2, 0, 29); createIrDrAsimm(ppcAddi, instr.result.regAux2, refReg, arrayFirstOffset); createIrSrArB(ppcStfsx, valReg, instr.result.regAux1, instr.result.regAux2); break; case tDouble: createIrArSSHMBME(ppcRlwinm, instr.result.regAux1, indexReg, 3, 0, 28); createIrDrAsimm(ppcAddi, instr.result.regAux2, refReg, arrayFirstOffset); createIrSrArB(ppcStfdx, valReg, instr.result.regAux1, instr.result.regAux2); break; case tChar: assert false : "cg: type char not implemented"; break; default: assert false : "cg: type not implemented"; } break; // sCstoreToArray case sCadd: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = res.reg; switch (res.type) { case tInteger: if (sReg1 < 0) { int immVal = ((Constant)opds[0].constant).valueH; createIrDrAsimm(ppcAddi, dReg, sReg2, immVal); } else if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueH; createIrDrAsimm(ppcAddi, dReg, sReg1, immVal); } else { createIrDrArB(ppcAdd, dReg, sReg1, sReg2); } break; case tLong: createIrDrArB(ppcAddc, dReg, sReg1, sReg2); createIrDrArB(ppcAdde, res.regLong, opds[0].regLong, opds[1].regLong); break; case tFloat: createIrDrArB(ppcFadds, dReg, sReg1, sReg2); break; case tDouble: createIrDrArB(ppcFadd, dReg, sReg1, sReg2); break; default: assert false : "cg: wrong type"; } break; case sCsub: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = res.reg; switch (res.type) { case tInteger: if (sReg1 < 0) { int immVal = ((Constant)opds[0].constant).valueH; createIrDrAsimm(ppcAddi, dReg, sReg2, -immVal); } else if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueH; createIrDrAsimm(ppcAddi, dReg, sReg1, -immVal); } else { createIrDrArB(ppcSubf, dReg, sReg2, sReg1); } break; case tLong: createIrDrArB(ppcSubfc, dReg, sReg2, sReg1); createIrDrArB(ppcSubfe, res.regLong, opds[1].regLong, opds[0].regLong); break; case tFloat: createIrDrArB(ppcFsubs, dReg, sReg1, sReg2); break; case tDouble: createIrDrArB(ppcFsub, dReg, sReg1, sReg2); break; default: assert false : "cg: wrong type"; } break; case sCmul: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = res.reg; switch (res.type) { case tInteger: if (sReg1 < 0) { int immVal = ((Constant)opds[0].constant).valueH; createIrDrAsimm(ppcMulli, dReg, sReg2, immVal); } else if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueH; createIrDrAsimm(ppcMulli, dReg, sReg1, immVal); } else { createIrDrArB(ppcMullw, dReg, sReg1, sReg2); } break; case tLong: createIrDrArB(ppcMullw, res.regAux1, opds[0].regLong, sReg2); createIrDrArB(ppcMullw, res.regAux2, sReg1, opds[1].regLong); createIrDrArB(ppcAdd, res.regAux1, res.regAux1, res.regAux2); createIrDrArB(ppcMulhwu, res.regAux2, sReg1, sReg2); createIrDrArB(ppcMullw, res.reg, sReg1, sReg2); createIrDrArB(ppcAdd, res.regLong, res.regAux1, res.regAux2); break; case tFloat: createIrDrArC(ppcFmuls, dReg, sReg1, sReg2); break; case tDouble: createIrDrArC(ppcFmul, dReg, sReg1, sReg2); break; default: assert false : "cg: wrong type"; } break; case sCdiv: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = instr.result.reg; switch (instr.result.type) { case tByte: case tShort: case tInteger: if (opds[0].index < 0) { // int immVal = (Integer)opds[0].constant; // if ((immVal >= -32768) && (immVal <= 32767)) { // createInstructionSDI(ppcAddi, sReg2, dReg, immVal); } else if (opds[1].index < 0) { // int immVal = (Integer)opds[1].constant; // if ((immVal >= -32768) && (immVal <= 32767)) { // createInstructionSDI(ppcAddi, sReg1, dReg, immVal); } else { // createInstructionSSD(ppcAdd, sReg1, sReg2, dReg); } assert false : "cg: type not implemented"; break; case tLong: assert false : "cg: type not implemented"; break; case tFloat: createIrDrArB(ppcFdivs, dReg, sReg1, sReg2); break; case tDouble: createIrDrArB(ppcFdiv, dReg, sReg1, sReg2); break; default: assert false : "cg: wrong type"; } break; case sCrem: break; case sCneg: opds = instr.getOperands(); sReg1 = opds[0].reg; dReg = res.reg; type = res.type; if (type == tInteger) createIrDrA(ppcNeg, dReg, sReg1); else if (type == tLong) { createIrDrAsimm(ppcSubfic, dReg, sReg1, 0); createIrDrA(ppcSubfze, res.regLong, opds[0].regLong); } else if (type == tFloat || type == tDouble) createIrDrB(ppcFneg, dReg, sReg1); else assert false : "cg: wrong type"; break; case sCshl: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = res.reg; type = res.type; if (type == tInteger) { if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueH % 32; createIrArSSHMBME(ppcRlwinm, dReg, sReg1, immVal, 0, 31-immVal); } else { createIrArSSHMBME(ppcRlwinm, 0, sReg2, 0, 27, 31); createIrArSrB(ppcSlw, dReg, sReg1, 0); } } else if (type == tLong) { if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueH % 64; if (immVal < 32) { createIrArSSHMBME(ppcRlwinm, res.regLong, sReg1, immVal, 32-immVal, 31); createIrArSSHMBME(ppcRlwimi, res.regLong, opds[0].regLong, immVal, 0, 31-immVal); createIrArSSHMBME(ppcRlwinm, dReg, sReg1, immVal, 0, 31-immVal); } else { createIrDrAsimm(ppcAddi, dReg, 0, 0); createIrArSSHMBME(ppcRlwinm, res.regLong, sReg1, immVal-32, 0, 63-immVal); } } else { // gibt Problem wenn shift > 32 createIrArSSHMBME(ppcRlwinm, 0, sReg2, 0, 26, 31); createIrArSrB(ppcSlw, res.regAux1, sReg1, 0); createIrArSrB(ppcSlw, res.regLong, opds[0].regLong, 0); createIrArSrB(ppcOr, res.regLong, res.regLong, res.regAux1); createIrArSrB(ppcSlw, dReg, sReg1, 0); } } else assert false : "cg: wrong type"; break; case sCshr: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = res.reg; type = res.type; if (type == tInteger) { if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueH % 32; createIrArSSH(ppcSrawi, dReg, sReg1, immVal); } else { createIrArSSHMBME(ppcRlwinm, 0, sReg2, 0, 27, 31); createIrArSrB(ppcSraw, dReg, sReg1, 0); } } else if (type == tLong) { if (sReg2 < 0) { // gibt Problem wenn shift > 32 int immVal = ((Constant)opds[1].constant).valueH % 64; createIrArSSHMBME(ppcRlwinm, dReg, sReg1, 32-immVal, immVal, 31); createIrArSSHMBME(ppcRlwimi, dReg, opds[0].regLong, 32-immVal, 0, immVal-1); createIrArSSH(ppcSrawi, res.regLong, opds[0].regLong, immVal); } else { createIrArSSHMBME(ppcRlwinm, 0, sReg2, 0, 27, 31); createIrArSrB(ppcSlw, res.regAux1, sReg1, 0); createIrArSrB(ppcSlw, res.regLong, opds[0].regLong, 0); createIrArSrB(ppcOr, res.regLong, res.regLong, res.regAux1); createIrArSrB(ppcSlw, dReg, sReg1, 0); } } else assert false : "cg: wrong type"; break; case sCushr: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = res.reg; type = res.type; if (type == tInteger) { if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueH % 32; createIrArSSHMBME(ppcRlwinm, dReg, sReg1, 32-immVal, immVal, 31); } else { createIrArSSHMBME(ppcRlwinm, 0, sReg2, 0, 27, 31); createIrArSrB(ppcSrw, dReg, sReg1, 0); } } else if (type == tLong) { if (sReg2 < 0) { // gibt Problem wenn shift > 32 int immVal = ((Constant)opds[1].constant).valueH % 64; createIrArSSHMBME(ppcRlwinm, dReg, sReg1, 32-immVal, immVal, 31); createIrArSSHMBME(ppcRlwimi, dReg, opds[0].regLong, 32-immVal, 0, immVal-1); createIrArSSH(ppcSrawi, res.regLong, opds[0].regLong, immVal); } else { createIrArSSHMBME(ppcRlwinm, 0, sReg2, 0, 27, 31); createIrArSrB(ppcSlw, res.regAux1, sReg1, 0); createIrArSrB(ppcSlw, res.regLong, opds[0].regLong, 0); createIrArSrB(ppcOr, res.regLong, res.regLong, res.regAux1); createIrArSrB(ppcSlw, dReg, sReg1, 0); } } else assert false : "cg: wrong type"; break; case sCand: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = res.reg; if (res.type == tInteger) { if (sReg1 < 0) { int immVal = ((Constant)opds[0].constant).valueH; createIrArSuimm(ppcAndi, dReg, sReg2, immVal); } else if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueH; createIrArSuimm(ppcAndi, dReg, sReg1, immVal); } else createIrArSrB(ppcAnd, dReg, sReg1, sReg2); } else if (res.type == tLong) { if (sReg1 < 0) { int immVal = ((Constant)opds[0].constant).valueL; createIrArSrB(ppcOr, res.regLong, opds[1].regLong, opds[1].regLong); createIrArSuimm(ppcAndi, dReg, sReg2, (int)immVal); } else if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueL; createIrArSrB(ppcOr, res.regLong, opds[0].regLong, opds[0].regLong); createIrArSuimm(ppcAndi, dReg, sReg1, (int)immVal); } else { createIrArSrB(ppcAnd, res.regLong, opds[0].regLong, opds[1].regLong); createIrArSrB(ppcAnd, dReg, sReg1, sReg2); } } else assert false : "cg: wrong type"; break; case sCor: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = res.reg; if (res.type == tInteger) { if (sReg1 < 0) { int immVal = ((Constant)opds[0].constant).valueH; createIrArSuimm(ppcOri, dReg, sReg2, immVal); } else if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueH; createIrArSuimm(ppcOri, dReg, sReg1, immVal); } else createIrArSrB(ppcOr, dReg, sReg1, sReg2); } else if (res.type == tLong) { if (sReg1 < 0) { int immVal = ((Constant)opds[0].constant).valueL; createIrArSrB(ppcOr, res.regLong, opds[1].regLong, opds[1].regLong); createIrArSuimm(ppcOri, dReg, sReg2, (int)immVal); } else if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueL; createIrArSrB(ppcOr, res.regLong, opds[0].regLong, opds[0].regLong); createIrArSuimm(ppcOri, dReg, sReg1, (int)immVal); } else { createIrArSrB(ppcOr, res.regLong, opds[0].regLong, opds[1].regLong); createIrArSrB(ppcOr, dReg, sReg1, sReg2); } } else assert false : "cg: wrong type"; break; case sCxor: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = res.reg; if (res.type == tInteger) { if (sReg1 < 0) { int immVal = ((Constant)opds[0].constant).valueH; createIrArSuimm(ppcXori, dReg, sReg2, immVal); } else if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueH; createIrArSuimm(ppcXori, dReg, sReg1, immVal); } else createIrArSrB(ppcXor, dReg, sReg1, sReg2); } else if (res.type == tLong) { if (sReg1 < 0) { int immVal = ((Constant)opds[0].constant).valueL; createIrArSrB(ppcOr, res.regLong, opds[1].regLong, opds[1].regLong); createIrArSuimm(ppcXori, dReg, sReg2, (int)immVal); } else if (sReg2 < 0) { int immVal = ((Constant)opds[1].constant).valueL; createIrArSrB(ppcOr, res.regLong, opds[0].regLong, opds[0].regLong); createIrArSuimm(ppcXori, dReg, sReg1, (int)immVal); } else { createIrArSrB(ppcXor, res.regLong, opds[0].regLong, opds[1].regLong); createIrArSrB(ppcXor, dReg, sReg1, sReg2); } } else assert false : "cg: wrong type"; break; case sCconvInt: // int -> other type opds = instr.getOperands(); sReg1 = opds[0].reg; dReg = res.reg; switch (res.type) { case tByte: createIrArS(ppcExtsb, dReg, sReg1); break; case tChar: createIrArSSHMBME(ppcRlwinm, dReg, sReg1, 0, 16, 31); break; case tShort: createIrArS(ppcExtsh, dReg, sReg1); break; case tLong: createIrArSrB(ppcOr, dReg, sReg1, sReg1); createIrArSSH(ppcSrawi, 0, sReg1, 31); createIrArSrB(ppcOr, res.regLong, 0, 0); break; case tFloat: createIrArSuimm(ppcXoris, 0, sReg1, 0x8000); createIrSrAd(ppcStw, 0, stackPtr, tempStorageOffset+4); Item item = null; // hier ref auf 2^52; loadConstantAndFixup(res.regAux1, item); createIrDrAd(ppcLfd, dReg, res.regAux1, constForDoubleConv); createIrDrAd(ppcLfd, 0, stackPtr, tempStorageOffset); createIrDrArB(ppcFsub, dReg, 0, dReg); createIrDrB(ppcFrsp, dReg, dReg); break; case tDouble: item = null; createIrArSuimm(ppcXoris, 0, sReg1, 0x8000); createIrSrAd(ppcStw, 0, stackPtr, tempStorageOffset+4); loadConstantAndFixup(res.regAux1, item); createIrDrAd(ppcLfd, dReg, res.regAux1, constForDoubleConv); createIrDrAd(ppcLfd, 0, stackPtr, tempStorageOffset); createIrDrArB(ppcFsub, dReg, 0, dReg); break; default: assert false : "cg: wrong type"; } break; case sCconvLong: // long -> other type opds = instr.getOperands(); sReg1 = opds[0].reg; dReg = res.reg; switch (res.type) { case tByte: createIrArS(ppcExtsb, dReg, sReg1); break; case tChar: createIrArSSHMBME(ppcRlwinm, dReg, sReg1, 0, 16, 31); break; case tShort: createIrArS(ppcExtsh, dReg, sReg1); break; case tInteger: createIrArSrB(ppcOr, dReg, sReg1, sReg1); break; case tFloat: // noch machen break; case tDouble: // noch machen break; default: assert false : "cg: wrong type"; } break; case sCconvFloat: // float -> other type opds = instr.getOperands(); sReg1 = opds[0].reg; dReg = res.reg; switch (res.type) { case tByte: createIrDrB(ppcFctiw, 0, sReg1); createIrSrAd(ppcStfd, 0, stackPtr, tempStorageOffset); createIrDrAd(ppcLwz, 0, stackPtr, tempStorageOffset + 4); createIrArS(ppcExtsb, dReg, 0); break; case tChar: createIrDrB(ppcFctiw, 0, sReg1); createIrSrAd(ppcStfd, 0, stackPtr, tempStorageOffset); createIrDrAd(ppcLwz, 0, stackPtr, tempStorageOffset + 4); createIrArSSHMBME(ppcRlwinm, dReg, 0, 0, 16, 31); break; case tShort: createIrDrB(ppcFctiw, 0, sReg1); createIrSrAd(ppcStfd, 0, stackPtr, tempStorageOffset); createIrDrAd(ppcLwz, 0, stackPtr, tempStorageOffset + 4); createIrArS(ppcExtsh, dReg, 0); break; case tInteger: createIrDrB(ppcFctiw, 0, sReg1); createIrSrAd(ppcStfd, 0, stackPtr, tempStorageOffset); createIrDrAd(ppcLwz, dReg, stackPtr, tempStorageOffset + 4); break; case tLong: // noch machen break; case tDouble: createIrDrB(ppcFmr, dReg, sReg1); break; default: assert false : "cg: wrong type"; } break; case sCconvDouble: // double -> other type opds = instr.getOperands(); sReg1 = opds[0].reg; dReg = res.reg; switch (res.type) { case tByte: createIrDrB(ppcFctiw, 0, sReg1); createIrSrAd(ppcStfd, 0, stackPtr, tempStorageOffset); createIrDrAd(ppcLwz, 0, stackPtr, tempStorageOffset + 4); createIrArS(ppcExtsb, dReg, 0); break; case tChar: createIrDrB(ppcFctiw, 0, sReg1); createIrSrAd(ppcStfd, 0, stackPtr, tempStorageOffset); createIrDrAd(ppcLwz, 0, stackPtr, tempStorageOffset + 4); createIrArSSHMBME(ppcRlwinm, dReg, 0, 0, 16, 31); break; case tShort: createIrDrB(ppcFctiw, 0, sReg1); createIrSrAd(ppcStfd, 0, stackPtr, tempStorageOffset); createIrDrAd(ppcLwz, 0, stackPtr, tempStorageOffset + 4); createIrArS(ppcExtsh, dReg, 0); break; case tInteger: createIrDrB(ppcFctiw, 0, sReg1); createIrSrAd(ppcStfd, 0, stackPtr, tempStorageOffset); createIrDrAd(ppcLwz, dReg, stackPtr, tempStorageOffset + 4); tempStorage = true; break; case tLong: // noch machen break; case tFloat: createIrDrB(ppcFrsp, dReg, sReg1); break; default: assert false : "cg: wrong type"; } break; case sCcmpl: opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; dReg = res.reg; type = opds[0].type; if (type == tLong) { // createIrDrArB(ppcSubfc, dReg, sReg2, sReg1); //createIrDrArB(ppcSubfe, dReg, opds[1].regLong, opds[0].regLong); // bit einfgen int sReg1L = opds[0].regLong; int sReg2L = opds[1].regLong; instr = node.instructions[i+1]; assert instr.ssaOpcode == sCbranch; opds = instr.getOperands(); bci = ssa.cfg.code[node.lastBCA] & 0xff; if (bci == bCifeq) { createICRFrArB(ppcCmp, CRF0, sReg1L, sReg2L); createIBOBIBD(ppcBc, BOtrue, (28-4*CRF1+EQ), 0); } else if (bci == bCifne) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF1+EQ), 0); else if (bci == bCiflt) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF1+LT), 0); else if (bci == bCifge) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF1+LT), 0); else if (bci == bCifgt) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF1+GT), 0); else if (bci == bCifle) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF1+GT), 0); else assert false : "wrong branch instruction after sCcompl"; } else if (type == tFloat || type == tDouble) { createICRFrArB(ppcFcmpu, CRF1, sReg1, sReg2); instr = node.instructions[i+1]; assert instr.ssaOpcode == sCbranch; opds = instr.getOperands(); createICRFrASimm(ppcCmpi, CRF0, sReg1, 0); bci = ssa.cfg.code[node.lastBCA] & 0xff; if (bci == bCifeq) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF1+EQ), 0); else if (bci == bCifne) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF1+EQ), 0); else if (bci == bCiflt) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF1+LT), 0); else if (bci == bCifge) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF1+LT), 0); else if (bci == bCifgt) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF1+GT), 0); else if (bci == bCifle) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF1+GT), 0); else assert false : "wrong branch instruction after sCcompl"; } else assert false : "cg: wrong type"; i++; break; case sCcmpg: assert false : "ssa instruction not implemented"; break; case sCinstanceof: break; case sCalength: opds = instr.getOperands(); refReg = opds[0].reg; createItrap(ppcTwi, TOifequal, refReg, 0); createIrDrAd(ppcLha, res.reg , refReg, -arrayLenOffset); break; case sCcall: // ref.accAndProb & opds = instr.getOperands(); Call call = (Call)instr; if (false) { //SYScall if (true) { //GET1 createIrDrAd(ppcLbz, res.reg, opds[0].reg, 0); createIrArS(ppcExtsb, res.reg, res.reg); } else if (true) { // GET2 createIrDrAd(ppcLha, res.reg, opds[0].reg, 0); } else if (true) { // GET4 createIrDrAd(ppcLwz, res.reg, opds[0].reg, 0); } } else if ((call.item.accAndPropFlags & (1<<apfStatic)) != 0) { // invokestatic loadConstantAndFixup(res.regAux1, call.item); // addr of method createIrSspr(ppcMtspr, LR, res.regAux1); } else { // invokevirtual and invokespecial and invokeinterface refReg = opds[0].reg; offset = call.item.offset; createItrap(ppcTwi, TOifequal, refReg, 0); createIrDrAd(ppcLwz, res.regAux1, refReg, -4); createIrDrAd(ppcLwz, res.regAux1, res.regAux1, -offset); createIrSspr(ppcMtspr, LR, res.regAux1); } for (int k = 0; k < nofGPR; k++) destGPR[k] = 0; for (int k = 0; k < nofGPR; k++) destFPR[k] = 0; for (int k = 0; k < opds.length; k++) { type = opds[k].type; if (type == tLong) { destGPR[opds[k].regLong] = k + paramStartGPR; destGPR[opds[k].reg] = k + 1 + paramStartGPR; } else if (type == tFloat || type == tDouble) { destFPR[opds[k].reg] = k + paramStartFPR; } else destGPR[opds[k].reg] = k + paramStartGPR; } // System.out.println("move before call"); // for (int k = 0; k < nofGPR; k++) System.out.println("destGPR["+k+"]="+destGPR[k]); for (int k = 0; k < nofGPR; k++) { if (destGPR[k] != 0 && destGPR[k] != k) { if (destGPR[destGPR[k]] == 0) { createIrArSrB(ppcOr, destGPR[k], k, k); destGPR[k] = 0; } else { createIrArSrB(ppcOr, 0, destGPR[destGPR[k]], destGPR[destGPR[k]]); createIrArSrB(ppcOr, destGPR[destGPR[k]], destGPR[k], destGPR[k]); createIrArSrB(ppcOr, destGPR[k], 0, 0); int temp = destGPR[k]; destGPR[k] = destGPR[destGPR[k]]; destGPR[destGPR[k]] = temp; } } } for (int k = 0; k < nofFPR; k++) { if (destFPR[k] != 0 && destFPR[k] != k) { if (destFPR[destFPR[k]] == 0) { createIrDrB(ppcFmr, destFPR[k], k); destGPR[k] = 0; } else { createIrDrB(ppcFmr, 0, destFPR[destFPR[k]]); createIrDrB(ppcFmr, destFPR[destFPR[k]], destFPR[k]); createIrDrB(ppcFmr, destFPR[k], 0); int temp = destFPR[k]; destFPR[k] = destFPR[destFPR[k]]; destFPR[destFPR[k]] = temp; } } } createIBOBI(ppcBclr, BOalways, 0); type = res.type; if (type == tLong) { createIrArSrB(ppcOr, res.reg, returnGPR1, returnGPR1); createIrArSrB(ppcOr, res.regLong, returnGPR1 + 1, returnGPR1 + 1); } else if (type == tFloat || type == tDouble) { createIrDrB(ppcFmr, res.reg, returnFPR); } else if (type == tVoid) { } else createIrArSrB(ppcOr, res.reg, returnGPR1, returnGPR1); break; case sCnew: opds = instr.getOperands(); if (opds.length == 1) { Item item = null;// item = ref switch (res.type) { case tRef: // bCnew loadConstantAndFixup(paramStartGPR, item); // addr of new createIrSspr(ppcMtspr, LR, paramStartGPR); loadConstantAndFixup(paramStartGPR, item); // ref createIBOBI(ppcBclr, BOalways, 0); createIrArSrB(ppcOr, instr.result.reg, returnGPR1, returnGPR1); break; case tAboolean: case tAchar: case tAfloat: case tAdouble: case tAbyte: case tAshort: case tAinteger: case tAlong: // bCnewarray opds = instr.getOperands(); createIrArSrB(ppcOr, paramStartGPR, opds[0].reg, opds[0].reg); // nof elems createItrapSimm(ppcTwi, TOifless, paramStartGPR, 0); loadConstantAndFixup(paramStartGPR + 1, item); // addr of newarray createIrSspr(ppcMtspr, LR, paramStartGPR + 1); createIrDrAsimm(ppcAddi, paramStartGPR + 1, 0, instr.result.type - 10); // type createIBOBI(ppcBclr, BOalways, 0); createIrArSrB(ppcOr, instr.result.reg, returnGPR1, returnGPR1); break; case tAref: // bCanewarray opds = instr.getOperands(); createIrArSrB(ppcOr, paramStartGPR, opds[0].reg, opds[0].reg); // nof elems createItrapSimm(ppcTwi, TOifless, paramStartGPR, 0); loadConstantAndFixup(paramStartGPR + 1, item); // addr of anewarray createIrSspr(ppcMtspr, LR, paramStartGPR + 1); loadConstantAndFixup(paramStartGPR + 1, item); // ref createIBOBI(ppcBclr, BOalways, 0); createIrArSrB(ppcOr, instr.result.reg, returnGPR1, returnGPR1); break; default: assert false : "cg: instruction not implemented"; } } else { // bCmultianewarray: // assert false : "cg: instruction not implemented"; } break; case sCreturn: opds = instr.getOperands(); bci = ssa.cfg.code[node.lastBCA] & 0xff; switch (bci) { case bCreturn: break; case bCireturn: case bCareturn: createIrArSrB(ppcOr, returnGPR1, opds[0].reg, opds[0].reg); break; case bClreturn: createIrArSrB(ppcOr, returnGPR1, opds[0].reg, opds[0].reg); createIrArSrB(ppcOr, returnGPR2, opds[0].regLong, opds[0].regLong); break; case bCfreturn: case bCdreturn: createIrDrB(ppcFmr, returnFPR, opds[0].reg); break; default: assert false : "cg: return instruction not implemented"; } if (node.next != null) // last node needs no branch createIli(ppcB, 0, false); break; case sCthrow: opds = instr.getOperands(); createIrArSrB(ppcOr, instr.result.reg, opds[0].reg, opds[0].reg); break; case sCbranch: bci = ssa.cfg.code[node.lastBCA] & 0xff; switch (bci) { case bCgoto: createIli(ppcB, 0, false); break; case bCif_acmpeq: assert false : "cg: branch not implemented"; break; case bCif_acmpne: assert false : "cg: branch not implemented"; break; case bCif_icmpeq: case bCif_icmpne: case bCif_icmplt: case bCif_icmpge: case bCif_icmpgt: case bCif_icmple: boolean inverted = false; opds = instr.getOperands(); sReg1 = opds[0].reg; sReg2 = opds[1].reg; // assertEquals("cg: wrong type", opds[0].type, tInteger); // assertEquals("cg: wrong type", opds[1].type, tInteger); if (sReg1 < 0) { if (opds[0].constant != null) { // System.out.println("constant is not null"); int immVal = ((Constant)opds[0].constant).valueH; if ((immVal >= -32768) && (immVal <= 32767)) createICRFrASimm(ppcCmpi, CRF0, sReg2, immVal); else createICRFrArB(ppcCmp, CRF0, sReg2, sReg1); } else createICRFrArB(ppcCmp, CRF0, sReg2, sReg1); } else if (sReg2 < 0) { if (opds[1].constant != null) { int immVal = ((Constant)opds[1].constant).valueH; if ((immVal >= -32768) && (immVal <= 32767)) { inverted = true; createICRFrASimm(ppcCmpi, CRF0, sReg1, immVal); } else createICRFrArB(ppcCmp, CRF0, sReg2, sReg1); } else createICRFrArB(ppcCmp, CRF0, sReg2, sReg1); } else { createICRFrArB(ppcCmp, CRF0, sReg2, sReg1); } if (!inverted) { if (bci == bCif_icmpeq) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+EQ), 0); else if (bci == bCif_icmpne) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF0+EQ), 0); else if (bci == bCif_icmplt) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+LT), 0); else if (bci == bCif_icmpge) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF0+LT), 0); else if (bci == bCif_icmpgt) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+GT), 0); else if (bci == bCif_icmple) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF0+GT), 0); } else { if (bci == bCif_icmpeq) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+EQ), 0); else if (bci == bCif_icmpne) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF0+EQ), 0); else if (bci == bCif_icmplt) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+GT), 0); else if (bci == bCif_icmpge) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF0+GT), 0); else if (bci == bCif_icmpgt) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+LT), 0); else if (bci == bCif_icmple) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF0+LT), 0); } break; case bCifeq: case bCifne: case bCiflt: case bCifge: case bCifgt: case bCifle: opds = instr.getOperands(); sReg1 = opds[0].reg; // assertEquals("cg: wrong type", opds[0].type, tInteger); createICRFrASimm(ppcCmpi, CRF0, sReg1, 0); if (bci == bCifeq) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+EQ), 0); else if (bci == bCifne) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF0+EQ), 0); else if (bci == bCiflt) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+LT), 0); else if (bci == bCifge) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF0+LT), 0); else if (bci == bCifgt) createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+GT), 0); else if (bci == bCifle) createIBOBIBD(ppcBc, BOfalse, (28-4*CRF0+GT), 0); break; case bCifnonnull: assert false : "cg: branch not implemented"; break; case bCifnull: assert false : "cg: branch not implemented"; break; case bCtableswitch: opds = instr.getOperands(); sReg1 = opds[0].reg; int addr = node.lastBCA + 1; addr = (addr + 3) & -4; // round to the next multiple of 4 addr += 4; // skip default offset int low = getInt(ssa.cfg.code, addr); int high = getInt(ssa.cfg.code, addr + 4); int nofCases = high - low + 1; for (int k = 0; k < nofCases; k++) { createICRFrASimm(ppcCmpi, CRF0, sReg1, low + k); createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+EQ), 0); } createIli(ppcB, nofCases, false); break; case bClookupswitch: opds = instr.getOperands(); sReg1 = opds[0].reg; addr = node.lastBCA + 1; addr = (addr + 3) & -4; // round to the next multiple of 4 addr += 4; // skip default offset int nofPairs = getInt(ssa.cfg.code, addr); for (int k = 0; k < nofPairs; k++) { int key = getInt(ssa.cfg.code, addr + 4 + k * 8); createICRFrASimm(ppcCmpi, CRF0, sReg1, key); createIBOBIBD(ppcBc, BOtrue, (28-4*CRF0+EQ), 0); } createIli(ppcB, nofPairs, true); break; default: // System.out.println(bci); assert false : "cg: no such branch instruction"; } break; case sCregMove: opds = instr.getOperands(); createIrArSrB(ppcOr, instr.result.reg, opds[0].reg, opds[0].reg); break; default: assert false : "cg: no code generated for " + instr.scMnemonics[instr.ssaOpcode] + " function"; } } } private static int getInt(byte[] bytes, int index){ return (((bytes[index]<<8) | (bytes[index+1]&0xFF))<<8 | (bytes[index+2]&0xFF))<<8 | (bytes[index+3]&0xFF); } private void createIrArS(int opCode, int rA, int rS) { instructions[iCount] = opCode | (rS << 21) | (rA << 16); incInstructionNum(); } private void createIrDrArB(int opCode, int rD, int rA, int rB) { instructions[iCount] = opCode | (rD << 21) | (rA << 16) | (rB << 11); incInstructionNum(); } private void createIrDrArC(int opCode, int rD, int rA, int rC) { instructions[iCount] = opCode | (rD << 21) | (rA << 16) | (rC << 6); incInstructionNum(); } private void createIrSrArB(int opCode, int rS, int rA, int rB) { instructions[iCount] = opCode | (rS << 21) | (rA << 16) | (rB << 11); incInstructionNum(); } private void createIrArSrB(int opCode, int rA, int rS, int rB) { if ((opCode == ppcOr) && (rA == rS) && (rA == rB)) return; // lr x,x makes no sense instructions[iCount] = opCode | (rS << 21) | (rA << 16) | (rB << 11); incInstructionNum(); } private void createIrDrAd(int opCode, int rD, int rA, int d) { instructions[iCount] = opCode | (rD << 21) | (rA << 16) | (d & 0xffff); incInstructionNum(); } private void createIrDrAsimm(int opCode, int rD, int rA, int simm) { instructions[iCount] = opCode | (rD << 21) | (rA << 16) | (simm & 0xffff); incInstructionNum(); } private void createIrArSuimm(int opCode, int rA, int rS, int uimm) { instructions[iCount] = opCode | (rA << 16) | (rS << 21) | (uimm & 0xffff); incInstructionNum(); } private void createIrSrASimm(int opCode, int rS, int rA, int simm) { instructions[iCount] = opCode | (rS << 21) | (rA << 16) | (simm & 0xffff); incInstructionNum(); } private void createIrSrAd(int opCode, int rS, int rA, int d) { instructions[iCount] = opCode | (rS << 21) | (rA << 16) | (d & 0xffff); incInstructionNum(); } private void createIrArSSH(int opCode, int rA, int rS, int SH) { instructions[iCount] = opCode | (rS << 21) | (rA << 16) | (SH << 11); incInstructionNum(); } private void createIrArSSHMBME(int opCode, int rA, int rS, int SH, int MB, int ME) { instructions[iCount] = opCode | (rS << 21) | (rA << 16) | (SH << 11) | (MB << 6) | (ME << 1); incInstructionNum(); } private void createItrap(int opCode, int TO, int rA, int rB) { instructions[iCount] = opCode | (TO << 21) | (rA << 16) | (rB << 11); incInstructionNum(); } private void createItrapSimm(int opCode, int TO, int rA, int imm) { instructions[iCount] = opCode | (TO << 21) | (rA << 16) | (imm & 0xffff); incInstructionNum(); } private void createIli(int opCode, int LI, boolean link) { instructions[iCount] = opCode | (LI << 2 | (link ? 1 : 0)); incInstructionNum(); } private void createIBOBIBD(int opCode, int BO, int BI, int BD) { instructions[iCount] = opCode | (BO << 21) | (BI << 16) | (BD << 2); incInstructionNum(); } private void createIBOBI(int opCode, int BO, int BI) { instructions[iCount] = opCode | (BO << 21) | (BI << 16); incInstructionNum(); } private void createICRFrArB(int opCode, int crfD, int rA, int rB) { instructions[iCount] = opCode | (crfD << 23) | (rA << 16) | (rB << 11); // System.out.println(InstructionDecoder.getMnemonic(instructions[iCount])); incInstructionNum(); } private void createICRFrASimm(int opCode, int crfD, int rA, int simm) { instructions[iCount] = opCode | (crfD << 23) | (rA << 16) | (simm & 0xffff); incInstructionNum(); } private void createIrDrA(int opCode, int rD, int rA) { instructions[iCount] = opCode | (rD << 21) | (rA << 16); incInstructionNum(); } private void createIrDrB(int opCode, int rD, int rB) { instructions[iCount] = opCode | (rD << 21) | (rB << 11); incInstructionNum(); } private void createIrSspr(int opCode, int spr, int rS) { instructions[iCount] = opCode | (spr << 11) | (rS << 21); incInstructionNum(); } private void loadConstant(int val, int reg) { int low = val & 0xffff; int high = (val >> 16) & 0xffff; if ((low >> 15) == 0) { if (low != 0) createIrDrAsimm(ppcAddi, reg, 0, low); if (high != 0) createIrDrAsimm(ppcAddis, reg, reg, high); if ((low == 0) && (high == 0)) createIrDrAsimm(ppcAddi, reg, 0, 0); } else { if (low != 0) createIrDrAsimm(ppcAddi, reg, 0, low); if (((high + 1) & 0xffff) != 0) createIrDrAsimm(ppcAddis, reg, reg, high + 1); } } private void loadConstantAndFixup(int reg, Item item) { assert lastFixup >= 0 && lastFixup <= 32768 : "fixup is out of range"; createIrDrAsimm(ppcAddi, reg, 0, lastFixup); createIrDrAsimm(ppcAddis, reg, reg, 0); lastFixup = iCount - 2; fixups[fCount] = item; fCount++; int len = fixups.length; if (fCount == len) { Item[] newFixups = new Item[2 * len]; for (int k = 0; k < len; k++) newFixups[k] = fixups[k]; fixups = newFixups; } } private void incInstructionNum() { iCount++; int len = instructions.length; if (iCount == len) { int[] newInstructions = new int[2 * len]; for (int k = 0; k < len; k++) newInstructions[k] = instructions[k]; instructions = newInstructions; } } private void insertProlog() { int count = iCount; iCount = 0; createIrSrASimm(ppcStwu, stackPtr, stackPtr, -stackSize); createIrSspr(ppcMfspr, LR, 0); createIrSrASimm(ppcStw, 0, stackPtr, LRoffset); if (nofNonVolGPR > 0) { createIrSrAd(ppcStmw, nofGPR-nofNonVolGPR, stackPtr, GPRoffset); } if (nofNonVolFPR > 0) { for (int i = 0; i < nofNonVolFPR; i++) createIrSrAd(ppcStfd, topFPR-i, stackPtr, FPRoffset + i * 8); } for (int i = 0; i < nofMoveGPR; i++) createIrArSrB(ppcOr, topGPR-i, moveGPR[i]+paramStartGPR, moveGPR[i]+paramStartGPR); for (int i = 0; i < nofMoveFPR; i++) createIrDrB(ppcFmr, topFPR-i, moveFPR[i]+paramStartFPR); iCount = count; } private void insertEpilog(int stackSize) { if (nofNonVolFPR > 0) { for (int i = 0; i < nofNonVolFPR; i++) createIrDrAd(ppcLfd, topFPR-i, stackPtr, FPRoffset + i * 8); } if (nofNonVolGPR > 0) createIrDrAd(ppcLmw, nofGPR - nofNonVolGPR, stackPtr, GPRoffset); createIrDrAd(ppcLwz, 0, stackPtr, LRoffset); createIrSspr(ppcMtspr, LR, 0); createIrDrAsimm(ppcAddi, stackPtr, stackPtr, stackSize); createIBOBI(ppcBclr, BOalways, 0); } public void print(){ // System.out.println("Method information for " + ssa.cfg.method.name); Method m = ssa.cfg.method; // System.out.println("Method has " + m.maxLocals + " locals where " + m.nofParams + " are parameters"); // System.out.println("stackSize = " + stackSize); // System.out.println("Method uses " + nofNonVolGPR + " GPR and " + nofNonVolFPR + " FPR for locals where " + nofParamGPR + " GPR and " + nofParamFPR + " FPR are for parameters"); // System.out.println(); System.out.println("Code for Method: " + ssa.cfg.method.name); for (int i = 0; i < iCount; i++){ System.out.print("\t" + Integer.toHexString(instructions[i])); System.out.print("\t[0x"); System.out.print(Integer.toHexString(i*4)); System.out.print("]\t" + InstructionDecoder.getMnemonic(instructions[i])); int opcode = (instructions[i] & 0xFC000000) >>> (31 - 5); if (opcode == 0x10) { int BD = (short)(instructions[i] & 0xFFFC); System.out.print(", [0x" + Integer.toHexString(BD + 4 * i) + "]\t"); } else if (opcode == 0x12) { int li = (instructions[i] & 0x3FFFFFC) << 6 >> 6; System.out.print(", [0x" + Integer.toHexString(li + 4 * i) + "]\t"); } System.out.println(); } } }
// $Id: AckReceiverWindow.java,v 1.4 2004/05/14 00:35:54 belaban Exp $ package org.jgroups.stack; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.Message; import java.util.HashMap; /** * Counterpart of AckSenderWindow. Every message received is ACK'ed (even duplicates) and added to a hashmap * keyed by seqno. The next seqno to be received is stored in <code>next_to_remove</code>. When a message with * a seqno less than next_to_remove is received, it will be discarded. The <code>remove()</code> method removes * and returns a message whose seqno is equal to next_to_remove, or null if not found.<br> * Change May 28 2002 (bela): replaced TreeSet with HashMap. Keys do not need to be sorted, and adding a key to * a sorted set incurs overhead. * * @author Bela Ban */ public class AckReceiverWindow { long initial_seqno=0, next_to_remove=0; HashMap msgs=new HashMap(); // keys: seqnos (Long), values: Messages static Log log=LogFactory.getLog(AckReceiverWindow.class); public AckReceiverWindow(long initial_seqno) { this.initial_seqno=initial_seqno; next_to_remove=initial_seqno; } public void add(long seqno, Message msg) { if(seqno < next_to_remove) { if(log.isTraceEnabled()) log.trace("discarded msg with seqno=" + seqno + " (next msg to receive is " + next_to_remove + ")"); return; } msgs.put(new Long(seqno), msg); } /** * Removes a message whose seqno is equal to <code>next_to_remove</code>, increments the latter. * Returns message that was removed, or null, if no message can be removed. Messages are thus * removed in order. */ public Message remove() { Message retval=(Message)msgs.remove(new Long(next_to_remove)); if(retval != null) next_to_remove++; return retval; } public void reset() { msgs.clear(); next_to_remove=initial_seqno; } public String toString() { return msgs.keySet().toString(); } public static void main(String[] args) { AckReceiverWindow win=new AckReceiverWindow(33); Message m=new Message(); win.add(37, m); System.out.println(win); while((win.remove()) != null) { System.out.println("Removed message, win is " + win); } win.add(35, m); System.out.println(win); win.add(36, m); System.out.println(win); while((win.remove()) != null) { System.out.println("Removed message, win is " + win); } win.add(33, m); System.out.println(win); win.add(34, m); System.out.println(win); win.add(38, m); System.out.println(win); while((win.remove()) != null) { System.out.println("Removed message, win is " + win); } win.add(35, m); System.out.println(win); win.add(332, m); System.out.println(win); } }
package org.jgroups.stack; import org.jgroups.Address; import org.jgroups.Message; import org.jgroups.annotations.GuardedBy; import org.jgroups.logging.Log; import org.jgroups.logging.LogFactory; import org.jgroups.util.TimeScheduler; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class NakReceiverWindow { public interface Listener { void missingMessageReceived(long seqno, Address original_sender); void messageGapDetected(long from, long to, Address src); } private final ReadWriteLock lock=new ReentrantReadWriteLock(); Address local_addr=null; private volatile boolean running=true; @GuardedBy("lock") private long low=0; /** The highest delivered seqno, updated on remove(). The next message to be removed is highest_delivered + 1 */ @GuardedBy("lock") private long highest_delivered=0; /** The highest received message, updated on add (if a new message is added, not updated e.g. if a missing msg * was received) */ @GuardedBy("lock") private long highest_received=0; /** ConcurrentMap<Long,Message>. Maintains messages keyed by (sorted) sequence numbers */ private final ConcurrentMap<Long,Message> xmit_table=new ConcurrentHashMap<Long,Message>(); /** * Messages that have been received in order are sent up the stack (= delivered to the application). Delivered * messages are removed from NakReceiverWindow.xmit_table and moved to NakReceiverWindow.delivered_msgs, where * they are later garbage collected (by STABLE). Since we do retransmits only from sent messages, never * received or delivered messages, we can turn the moving to delivered_msgs off, so we don't keep the message * around, and don't need to wait for garbage collection to remove them. */ private boolean discard_delivered_msgs=false; private final AtomicBoolean processing=new AtomicBoolean(false); /** If value is > 0, the retransmit buffer is bounded: only the max_xmit_buf_size latest messages are kept, * older ones are discarded when the buffer size is exceeded. A value <= 0 means unbounded buffers */ private int max_xmit_buf_size=0; /** if not set, no retransmitter thread will be started. Useful if * protocols do their own retransmission (e.g PBCAST) */ private Retransmitter retransmitter=null; private Listener listener=null; protected static final Log log=LogFactory.getLog(NakReceiverWindow.class); /** The highest stable() seqno received */ long highest_stability_seqno=0; /** The loss rate (70% of the new value and 30% of the old value) */ private double smoothed_loss_rate=0.0; /** * Creates a new instance with the given retransmit command * * @param sender The sender associated with this instance * @param cmd The command used to retransmit a missing message, will * be invoked by the table. If null, the retransmit thread will not be started * @param highest_delivered_seqno The next seqno to remove is highest_delivered_seqno +1 * @param lowest_seqno The low seqno purged * @param sched the external scheduler to use for retransmission * requests of missing msgs. If it's not provided or is null, an internal */ public NakReceiverWindow(Address sender, Retransmitter.RetransmitCommand cmd, long highest_delivered_seqno, long lowest_seqno, TimeScheduler sched) { this(null, sender, cmd, highest_delivered_seqno, lowest_seqno, sched); } public NakReceiverWindow(Address local_addr, Address sender, Retransmitter.RetransmitCommand cmd, long highest_delivered_seqno, long lowest_seqno, TimeScheduler sched) { this(local_addr, sender, cmd, highest_delivered_seqno, lowest_seqno, sched, true); } public NakReceiverWindow(Address local_addr, Address sender, Retransmitter.RetransmitCommand cmd, long highest_delivered_seqno, long lowest_seqno, TimeScheduler sched, boolean use_range_based_retransmitter) { this.local_addr=local_addr; highest_delivered=highest_delivered_seqno; highest_received=highest_delivered; low=Math.min(lowest_seqno, highest_delivered); if(sched == null) throw new IllegalStateException("timer has to be provided and cannot be null"); if(cmd != null) retransmitter=use_range_based_retransmitter? new RangeBasedRetransmitter(sender, cmd, sched) : new DefaultRetransmitter(sender, cmd, sched); } /** * Creates a new instance with the given retransmit command * * @param sender The sender associated with this instance * @param cmd The command used to retransmit a missing message, will * be invoked by the table. If null, the retransmit thread will not be started * @param highest_delivered_seqno The next seqno to remove is highest_delivered_seqno +1 * @param sched the external scheduler to use for retransmission * requests of missing msgs. If it's not provided or is null, an internal */ public NakReceiverWindow(Address sender, Retransmitter.RetransmitCommand cmd, long highest_delivered_seqno, TimeScheduler sched) { this(sender, cmd, highest_delivered_seqno, 0, sched); } public AtomicBoolean getProcessing() { return processing; } public void setRetransmitTimeouts(Interval timeouts) { retransmitter.setRetransmitTimeouts(timeouts); } public void setDiscardDeliveredMessages(boolean flag) { this.discard_delivered_msgs=flag; } public int getMaxXmitBufSize() { return max_xmit_buf_size; } public void setMaxXmitBufSize(int max_xmit_buf_size) { this.max_xmit_buf_size=max_xmit_buf_size; } public void setListener(Listener l) { this.listener=l; } public int getPendingXmits() { return retransmitter!= null? retransmitter.size() : 0; } /** * Returns the loss rate, which is defined as the number of pending retransmission requests / the total number of * messages in xmit_table * @return The loss rate */ public double getLossRate() { int total_msgs=size(); int pending_xmits=getPendingXmits(); if(pending_xmits == 0 || total_msgs == 0) return 0.0; return pending_xmits / (double)total_msgs; } public double getSmoothedLossRate() { return smoothed_loss_rate; } /** Set the new smoothed_loss_rate value to 70% of the new value and 30% of the old value */ private void setSmoothedLossRate() { double new_loss_rate=getLossRate(); if(smoothed_loss_rate == 0) { smoothed_loss_rate=new_loss_rate; } else { smoothed_loss_rate=smoothed_loss_rate * .3 + new_loss_rate * .7; } } /** * Adds a message according to its seqno (sequence number). * <p> * There are 4 cases where messages are added: * <ol> * <li>seqno is the next to be expected seqno: added to map * <li>seqno is <= highest_delivered: discard as we've already delivered it * <li>seqno is smaller than the next expected seqno: missing message, add it * <li>seqno is greater than the next expected seqno: add it to map and fill the gaps with null messages * for retransmission. Add the seqno to the retransmitter too * </ol> * @return True if the message was added successfully, false otherwise (e.g. duplicate message) */ public boolean add(final long seqno, final Message msg) { long old_next, next_to_add; int num_xmits=0; lock.writeLock().lock(); try { if(!running) return false; next_to_add=highest_received +1; old_next=next_to_add; // Case #1: we received the expected seqno: most common path if(seqno == next_to_add) { xmit_table.put(seqno, msg); return true; } // Case #2: we received a message that has already been delivered: discard it if(seqno <= highest_delivered) { if(log.isTraceEnabled()) log.trace("seqno " + seqno + " is smaller than " + next_to_add + "); discarding message"); return false; } // Case #3: we finally received a missing message. Case #2 handled seqno <= highest_delivered, so this // seqno *must* be between highest_delivered and next_to_add if(seqno < next_to_add) { Message tmp=xmit_table.putIfAbsent(seqno, msg); // only set message if not yet received (bela July 23 2003) if(tmp == null) { // key/value was not present num_xmits=retransmitter.remove(seqno); if(log.isTraceEnabled()) log.trace(new StringBuilder("added missing msg ").append(msg.getSrc()).append('#').append(seqno)); return true; } else { // key/value was present return false; } } // Case #4: we received a seqno higher than expected: add to Retransmitter if(seqno > next_to_add) { xmit_table.put(seqno, msg); retransmitter.add(old_next, seqno -1); // BUT: add only null messages to xmitter if(listener != null) { try {listener.messageGapDetected(next_to_add, seqno, msg.getSrc());} catch(Throwable t) {} } return true; } } finally { highest_received=Math.max(highest_received, seqno); lock.writeLock().unlock(); } if(listener != null && num_xmits > 0) { try {listener.missingMessageReceived(seqno, msg.getSrc());} catch(Throwable t) {} } return true; } public Message remove() { return remove(true); } public Message remove(boolean acquire_lock) { Message retval; if(acquire_lock) lock.writeLock().lock(); try { long next_to_remove=highest_delivered +1; retval=xmit_table.get(next_to_remove); if(retval != null) { // message exists and is ready for delivery if(discard_delivered_msgs) { Address sender=retval.getSrc(); if(!local_addr.equals(sender)) { // don't remove if we sent the message ! xmit_table.remove(next_to_remove); } } highest_delivered=next_to_remove; return retval; } // message has not yet been received (gap in the message sequence stream) // drop all messages that have not been received if(max_xmit_buf_size > 0 && xmit_table.size() > max_xmit_buf_size) { highest_delivered=next_to_remove; retransmitter.remove(next_to_remove); } return null; } finally { if(acquire_lock) lock.writeLock().unlock(); } } /** * Removes as many messages as possible * @return List<Message> A list of messages, or null if no available messages were found */ public List<Message> removeMany(final AtomicBoolean processing) { return removeMany(processing, 0); } public List<Message> removeMany(final AtomicBoolean processing, int max_results) { return removeMany(processing, false, max_results); } /** * Removes as many messages as possible * @param discard_own_msgs Removes messages from xmit_table even if we sent it * @param max_results Max number of messages to remove in one batch * @return List<Message> A list of messages, or null if no available messages were found */ public List<Message> removeMany(final AtomicBoolean processing, boolean discard_own_msgs, int max_results) { List<Message> retval=null; int num_results=0; lock.writeLock().lock(); try { while(true) { long next_to_remove=highest_delivered +1; Message msg=xmit_table.get(next_to_remove); if(msg != null) { // message exists and is ready for delivery if(discard_delivered_msgs) { Address sender=msg.getSrc(); if(discard_own_msgs || !local_addr.equals(sender)) { // don't remove if we sent the message ! xmit_table.remove(next_to_remove); } } highest_delivered=next_to_remove; if(retval == null) retval=new LinkedList<Message>(); retval.add(msg); if(max_results <= 0 || ++num_results < max_results) continue; } // message has not yet been received (gap in the message sequence stream) // drop all messages that have not been received if(max_xmit_buf_size > 0 && xmit_table.size() > max_xmit_buf_size) { highest_delivered=next_to_remove; retransmitter.remove(next_to_remove); continue; } if((retval == null || retval.isEmpty()) && processing != null) processing.set(false); return retval; } } finally { lock.writeLock().unlock(); } } public Message removeOOBMessage() { lock.writeLock().lock(); try { Message retval=xmit_table.get(highest_delivered +1); if(retval != null && retval.isFlagSet(Message.OOB)) { return remove(false); } return null; } finally { lock.writeLock().unlock(); } } /** Removes as many OOB messages as possible */ public List<Message> removeOOBMessages() { final List<Message> retval=new LinkedList<Message>(); lock.writeLock().lock(); try { while(true) { Message msg=xmit_table.get(highest_delivered +1); if(msg != null && msg.isFlagSet(Message.OOB)) { msg=remove(false); if(msg != null) retval.add(msg); } else break; } } finally { lock.writeLock().unlock(); } return retval; } public boolean hasMessagesToRemove() { lock.readLock().lock(); try { return xmit_table.get(highest_delivered + 1) != null; } finally { lock.readLock().unlock(); } } /** * Delete all messages <= seqno (they are stable, that is, have been received at all members). * Stop when a number > seqno is encountered (all messages are ordered on seqnos). */ public void stable(long seqno) { lock.writeLock().lock(); try { if(seqno > highest_delivered) { if(log.isWarnEnabled()) log.warn("seqno " + seqno + " is > highest_delivered (" + highest_delivered + ";) ignoring stability message"); return; } // we need to remove all seqnos *including* seqno if(!xmit_table.isEmpty()) { for(long i=low; i <= seqno; i++) { xmit_table.remove(i); } } // remove all seqnos below seqno from retransmission for(long i=low; i <= seqno; i++) { retransmitter.remove(i); } highest_stability_seqno=Math.max(highest_stability_seqno, seqno); low=Math.max(low, seqno); } finally { lock.writeLock().unlock(); } } /** * Destroys the NakReceiverWindow. After this method returns, no new messages can be added and a new * NakReceiverWindow should be used instead. Note that messages can still be <em>removed</em> though. */ public void destroy() { lock.writeLock().lock(); try { running=false; retransmitter.reset(); xmit_table.clear(); low=0; highest_delivered=0; // next (=first) to deliver will be 1 highest_received=0; highest_stability_seqno=0; } finally { lock.writeLock().unlock(); } } /** Returns the lowest, highest delivered and highest received seqnos */ public long[] getDigest() { lock.readLock().lock(); try { long[] retval=new long[3]; retval[0]=low; retval[1]=highest_delivered; retval[2]=highest_received; return retval; } finally { lock.readLock().unlock(); } } /** * @return the lowest sequence number of a message that has been * delivered or is a candidate for delivery (by the next call to * <code>remove()</code>) */ public long getLowestSeen() { lock.readLock().lock(); try { return low; } finally { lock.readLock().unlock(); } } /** Returns the highest sequence number of a message <em>consumed</em> by the application (by <code>remove()</code>). * Note that this is different from the highest <em>deliverable</em> seqno. E.g. in 23,24,26,27,29, the highest * <em>delivered</em> message may be 22, whereas the highest <em>deliverable</em> message may be 24 ! * @return the highest sequence number of a message consumed by the * application (by <code>remove()</code>) */ public long getHighestDelivered() { lock.readLock().lock(); try { return highest_delivered; } finally { lock.readLock().unlock(); } } /** * Returns the highest sequence number received so far (which may be * higher than the highest seqno <em>delivered</em> so far; e.g., for * 1,2,3,5,6 it would be 6. * * @see NakReceiverWindow#getHighestDelivered */ public long getHighestReceived() { lock.readLock().lock(); try { return highest_received; } finally { lock.readLock().unlock(); } } /** * Returns the message from xmit_table * @param seqno * @return Message from xmit_table */ public Message get(long seqno) { return xmit_table.get(seqno); } public int size() { return xmit_table.size(); } public String toString() { lock.readLock().lock(); try { return printMessages(); } finally { lock.readLock().unlock(); } } /** * Prints xmit_table. Requires read lock to be present * @return String */ protected String printMessages() { StringBuilder sb=new StringBuilder(); sb.append('[').append(low).append(" : ").append(highest_delivered).append(" (").append(highest_received).append(")"); if(xmit_table != null && !xmit_table.isEmpty()) { int non_received=0; for(Map.Entry<Long,Message> entry: xmit_table.entrySet()) { if(entry.getValue() == null) non_received++; } sb.append(" (size=").append(xmit_table.size()).append(", missing=").append(non_received). append(", highest stability=").append(highest_stability_seqno).append(')'); } sb.append(']'); return sb.toString(); } public String printLossRate() { StringBuilder sb=new StringBuilder(); int num_missing=getPendingXmits(); int num_received=size(); int total=num_missing + num_received; sb.append("total=").append(total).append(" (received=").append(num_received).append(", missing=") .append(num_missing).append("), loss rate=").append(getLossRate()) .append(", smoothed loss rate=").append(smoothed_loss_rate); return sb.toString(); } public String printRetransmitStats() { return retransmitter instanceof RangeBasedRetransmitter? ((RangeBasedRetransmitter)retransmitter).printStats() : "n/a"; } }
package org.usfirst.frc.team997.robot; import org.usfirst.frc.team997.robot.commands.AutoRedLeftGear; import org.usfirst.frc.team997.robot.commands.AutoRedRightGear; import org.usfirst.frc.team997.robot.commands.AutoRedStraightGEAR; import org.usfirst.frc.team997.robot.commands.AutoBlueLeftGear; import org.usfirst.frc.team997.robot.commands.AutoBlueRightGear; import org.usfirst.frc.team997.robot.commands.AutoBlueStraightGEAR; import org.usfirst.frc.team997.robot.commands.AutoStraightNOGEAR; import org.usfirst.frc.team997.robot.commands.AutoNullCommand; import org.usfirst.frc.team997.robot.commands.DriveToAngle; import org.usfirst.frc.team997.robot.subsystems.Arduino; import org.usfirst.frc.team997.robot.subsystems.Climber; import org.usfirst.frc.team997.robot.subsystems.DriveTrain; import org.usfirst.frc.team997.robot.subsystems.Elevator; import org.usfirst.frc.team997.robot.subsystems.Gatherer; import org.usfirst.frc.team997.robot.subsystems.UltraSonic; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStation.Alliance; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.PowerDistributionPanel; import edu.wpi.first.wpilibj.Preferences; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import java.util.ArrayList; import org.usfirst.frc.team997.robot.CustomDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static OI oi; public static DriveTrain driveTrain; public static Gatherer gatherer; public static DriveToAngle driveToAngleCommand; public static Climber climber; public static PowerDistributionPanel pdp; public static Elevator elevator; public static UltraSonic ultraSonic; public static Arduino arduino; public static ArrayList<Loggable> logList; public static Preferences prefs; public static UDPReceive udpReceive; final String defaultAuto = "Default"; final String customAuto = "My Auto"; Command autoSelected; SendableChooser<Command> chooser = new SendableChooser<>(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { logList = new ArrayList<Loggable>(); //try { driveTrain = new DriveTrain(); //driveToAngleCommand = new DriveToAngle(); /*} catch (Exception e){ e.printStackTrace(); }*/ try { gatherer = new Gatherer(); } catch (Exception e) { e.printStackTrace(); } elevator = new Elevator(); pdp = new PowerDistributionPanel(); climber = new Climber(); // Set up the Autonomous Chooser to select auto mode final String autoChoicesNumber = ""; chooser.addDefault("Null " + autoChoicesNumber, new AutoNullCommand()); chooser.addObject("Auto Straight (No Gear)", new AutoStraightNOGEAR()); chooser.addObject("Auto Red Straight (Gear)", new AutoRedStraightGEAR()); chooser.addObject("Auto Blue Straight (Gear)", new AutoBlueStraightGEAR()); chooser.addObject("Auto Red Left (Gear)", new AutoRedLeftGear()); chooser.addObject("Auto Red Right (Gear)", new AutoRedRightGear()); chooser.addObject("Auto Blue Left (Gear)", new AutoBlueLeftGear()); chooser.addObject("Auto Blue Right (Gear)", new AutoBlueRightGear()); chooser.addObject("Auto Blue Left (Gear)", new AutoBlueLeftGear()); chooser.addObject("Auto Blue Right (Gear)", new AutoBlueRightGear()); CustomDashboard.putData("Auto Choices " + autoChoicesNumber, chooser); udpReceive = new UDPReceive(); prefs = Preferences.getInstance(); pollPreferences(); ultraSonic = new UltraSonic(); try { arduino = new Arduino(); if(DriverStation.getInstance().getAlliance() == Alliance.Red) { arduino.sendRed(); } else { arduino.sendBlue(); } } catch (Exception e) { System.err.println("Arduino Failed. This shouldn't happen on Comp Bot"); e.printStackTrace(); } //OI INITIALIZATION MUST MUST MUST MUST BE LAST oi = new OI(); } private void pollPreferences() { } /** * This autonomous (along with the chooser code above) shows how to select * between different autonomous modes using the dashboard. The sendable * chooser code works with the Java CustomDashboard. If you prefer the * LabVIEW Dashboard, remove all of the chooser code and uncomment the * getString line to get the auto name from the text box below the Gyro * * You can add additional auto modes by adding additional comparisons to the * switch structure below with additional strings. If using the * SendableChooser make sure to add them to the chooser code above as well. */ @Override public void autonomousInit() { driveTrain.resetEncoders(); driveTrain.resetGyro(); autoSelected = (Command) chooser.getSelected(); autoSelected.start(); // autoSelected = CustomDashboard.getString("Auto Selector", // defaultAuto); System.out.println("Auto selected: " + autoSelected); pollPreferences(); } /** * This function is called periodically during autonomous */ @Override public void autonomousPeriodic() { /*switch (autoSelected) { case customAuto: // Put custom auto code here break; case defaultAuto: default: // Put default auto code here break; }*/ log(); Scheduler.getInstance().run(); } public void teleopInit() { chooser.getSelected().cancel(); //STOPS AUTO ROUTINE driveTrain.resetEncoders(); driveTrain.resetGyro(); pollPreferences(); } @Override public void teleopPeriodic() { log(); Scheduler.getInstance().run(); /* * CustomDashboard.putNumber("DriveTrain Left Current 1", pdp.getCurrent(RobotMap.PDP.leftDriveMotor[0])); * CustomDashboard.putNumber("DriveTrain Left Current 2", pdp.getCurrent(RobotMap.PDP.leftDriveMotor[1])); * CustomDashboard.putNumber("DriveTrain Left Current 3", pdp.getCurrent(RobotMap.PDP.leftDriveMotor[2])); * * CustomDashboard.putNumber("DriveTrain Right Voltage 1", pdp.getCurrent(RobotMap.PDP.rightDriveMotor[0])); * CustomDashboard.putNumber("DriveTrain Right Voltage 2", pdp.getCurrent(RobotMap.PDP.rightDriveMotor[1])); * CustomDashboard.putNumber("DriveTrain Right Voltage 3", pdp.getCurrent(RobotMap.PDP.rightDriveMotor[2])); */ } public void disabledPeriodic() { log(); } /** * This function is called periodically during test mode */ @Override public void testPeriodic() { CustomDashboard.putNumber("DriveTrain Yaw", Robot.driveTrain.ahrs.getYaw()); log(); } public static double deadband(double x) { if(Math.abs(x) < 0.05) { return 0; } return x; } private void log() { for(Loggable l : logList) { l.log(); } } public static double clamp(double x) { if(x > 1) { return 1; } else if(x < -1) { return -1; } return x; } public static double negSqRt(double x) { if(x > 0) { return Math.sqrt(x); } else { return -Math.sqrt(-x); } } public static double negSq(double x) { if(x > 0) { return (x*x); } else { return -(x*x); } } public static double cube(double x) { if(x > 0) { return (4*((x-0.5)*(x-0.5)*(x-0.5))) + 0.5; } else { return (4*((-x+0.5)*(-x+0.5)*(-x+0.5))) + 0.5; } } public static double averageCurrent(int[] ports) { double result = 0; if (ports.length != 0) { for (int i = 0; i != ports.length; ++i) { result += pdp.getCurrent(ports[i]); } result /= ports.length; } return result; } }
package org.innovateuk.ifs.project.grantofferletter.controller; import org.innovateuk.ifs.BaseControllerMockMVCTest; import org.innovateuk.ifs.commons.error.CommonFailureKeys; import org.innovateuk.ifs.file.resource.FileEntryResource; import org.innovateuk.ifs.grantofferletter.GrantOfferLetterService; import org.innovateuk.ifs.project.ProjectService; import org.innovateuk.ifs.project.grantofferletter.form.GrantOfferLetterForm; import org.innovateuk.ifs.project.grantofferletter.populator.GrantOfferLetterModelPopulator; import org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterStateResource; import org.innovateuk.ifs.project.grantofferletter.viewmodel.GrantOfferLetterModel; import org.innovateuk.ifs.project.resource.ProjectResource; import org.innovateuk.ifs.project.resource.ProjectUserResource; import org.junit.Ignore; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.springframework.core.io.ByteArrayResource; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MvcResult; import org.springframework.validation.FieldError; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static junit.framework.TestCase.assertFalse; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.file.builder.FileEntryResourceBuilder.newFileEntryResource; import static org.innovateuk.ifs.project.builder.ProjectResourceBuilder.newProjectResource; import static org.innovateuk.ifs.project.builder.ProjectUserResourceBuilder.newProjectUserResource; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterEvent.*; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterState.*; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterStateResource.stateInformationForNonPartnersView; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterStateResource.stateInformationForPartnersView; import static org.innovateuk.ifs.user.resource.Role.PROJECT_MANAGER; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; public class GrantOfferLetterControllerTest extends BaseControllerMockMVCTest<GrantOfferLetterController> { @Spy @InjectMocks @SuppressWarnings("unused") private GrantOfferLetterModelPopulator grantOfferLetterViewModelPopulator; @Mock private GrantOfferLetterService grantOfferLetterService; @Mock private ProjectService projectService; @Test public void testViewGrantOfferLetterPageWithSignedOfferAsProjectManager() throws Exception { long projectId = 123L; long userId = 1L; ProjectResource project = newProjectResource().withId(projectId).build(); setupSignedSentGrantOfferLetterExpectations(projectId, userId, project, true, stateInformationForNonPartnersView(READY_TO_APPROVE, GOL_SIGNED)); MvcResult result = mockMvc.perform(get("/project/{projectId}/offer", project.getId())). andExpect(status().isOk()). andExpect(view().name("project/grant-offer-letter")). andReturn(); GrantOfferLetterModel model = (GrantOfferLetterModel) result.getModelAndView().getModel().get("model"); // test the view model assertEquals(project.getId(), model.getProjectId()); assertEquals(project.getName(), model.getProjectName()); assertTrue(model.isOfferSigned()); assertFalse(model.isShowSubmitButton()); assertTrue(model.isSubmitted()); assertFalse(model.isGrantOfferLetterApproved()); assertFalse(model.isGrantOfferLetterRejected()); verifySignedSentGrantOfferLetterExpectations(projectId, userId); } @Test public void testViewGrantOfferLetterPageWithSignedOfferAsNonProjectManager() throws Exception { long projectId = 123L; long userId = 1L; ProjectResource project = newProjectResource().withId(projectId).build(); setupSignedSentGrantOfferLetterExpectations(projectId, userId, project, true, stateInformationForPartnersView(READY_TO_APPROVE, GOL_SIGNED)); MvcResult result = mockMvc.perform(get("/project/{projectId}/offer", project.getId())). andExpect(status().isOk()). andExpect(view().name("project/grant-offer-letter")). andReturn(); GrantOfferLetterModel model = (GrantOfferLetterModel) result.getModelAndView().getModel().get("model"); // test the view model assertEquals(project.getId(), model.getProjectId()); assertEquals(project.getName(), model.getProjectName()); assertTrue(model.isOfferSigned()); assertFalse(model.isShowSubmitButton()); assertTrue(model.isSubmitted()); assertFalse(model.isGrantOfferLetterApproved()); assertFalse(model.isGrantOfferLetterRejected()); verifySignedSentGrantOfferLetterExpectations(projectId, userId); } @Test public void testViewGrantOfferLetterPageWithApprovedOffer() throws Exception { long projectId = 123L; long userId = 1L; ProjectResource project = newProjectResource().withId(projectId).build(); setupSignedSentGrantOfferLetterExpectations(projectId, userId, project, false, stateInformationForNonPartnersView(APPROVED, SIGNED_GOL_APPROVED)); MvcResult result = mockMvc.perform(get("/project/{projectId}/offer", project.getId())). andExpect(status().isOk()). andExpect(view().name("project/grant-offer-letter")). andReturn(); GrantOfferLetterModel model = (GrantOfferLetterModel) result.getModelAndView().getModel().get("model"); // test the view model assertEquals(project.getId(), model.getProjectId()); assertEquals(project.getName(), model.getProjectName()); assertTrue(model.isOfferSigned()); assertFalse(model.isShowSubmitButton()); assertTrue(model.isSubmitted()); assertTrue(model.isGrantOfferLetterApproved()); assertFalse(model.isGrantOfferLetterRejected()); verifySignedSentGrantOfferLetterExpectations(projectId, userId); } @Test public void testViewGrantOfferLetterPageWithRejectedOfferAsProjectManager() throws Exception { long projectId = 123L; long userId = 1L; ProjectResource project = newProjectResource().withId(projectId).build(); setupSignedSentGrantOfferLetterExpectations(projectId, userId, project, true, stateInformationForNonPartnersView(SENT, SIGNED_GOL_REJECTED)); MvcResult result = mockMvc.perform(get("/project/{projectId}/offer", project.getId())). andExpect(status().isOk()). andExpect(view().name("project/grant-offer-letter")). andReturn(); GrantOfferLetterModel model = (GrantOfferLetterModel) result.getModelAndView().getModel().get("model"); // test the view model assertEquals(project.getId(), model.getProjectId()); assertEquals(project.getName(), model.getProjectName()); assertTrue(model.isOfferSigned()); assertTrue(model.isShowSubmitButton()); assertFalse(model.isSubmitted()); assertFalse(model.isGrantOfferLetterApproved()); assertTrue(model.isGrantOfferLetterRejected()); verifySignedSentGrantOfferLetterExpectations(projectId, userId); } @Test public void testViewGrantOfferLetterPageWithRejectedOfferAsNonProjectManager() throws Exception { long projectId = 123L; long userId = 1L; ProjectResource project = newProjectResource().withId(projectId).build(); setupSignedSentGrantOfferLetterExpectations(projectId, userId, project, false, stateInformationForPartnersView(SENT, SIGNED_GOL_REJECTED)); MvcResult result = mockMvc.perform(get("/project/{projectId}/offer", project.getId())). andExpect(status().isOk()). andExpect(view().name("project/grant-offer-letter")). andReturn(); GrantOfferLetterModel model = (GrantOfferLetterModel) result.getModelAndView().getModel().get("model"); // test the view model assertEquals(project.getId(), model.getProjectId()); assertEquals(project.getName(), model.getProjectName()); assertTrue(model.isOfferSigned()); assertFalse(model.isShowSubmitButton()); assertTrue(model.isSubmitted()); assertFalse(model.isGrantOfferLetterApproved()); assertFalse(model.isGrantOfferLetterRejected()); verifySignedSentGrantOfferLetterExpectations(projectId, userId); } @Test public void testDownloadUnsignedGrantOfferLetter() throws Exception { FileEntryResource fileDetails = newFileEntryResource().withName("A name").build(); ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes()); when(grantOfferLetterService.getGrantOfferFile(123L)). thenReturn(Optional.of(fileContents)); when(grantOfferLetterService.getGrantOfferFileDetails(123L)). thenReturn(Optional.of(fileDetails)); MvcResult result = mockMvc.perform(get("/project/{projectId}/offer/grant-offer-letter", 123L)). andExpect(status().isOk()). andReturn(); assertEquals("My content!", result.getResponse().getContentAsString()); assertEquals("inline; filename=\"" + fileDetails.getName() + "\"", result.getResponse().getHeader("Content-Disposition")); } @Test public void testDownloadSignedGrantOfferLetterByLead() throws Exception { FileEntryResource fileDetails = newFileEntryResource().withName("A name").build(); ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes()); when(grantOfferLetterService.getSignedGrantOfferLetterFile(123L)). thenReturn(Optional.of(fileContents)); when(grantOfferLetterService.getSignedGrantOfferLetterFileDetails(123L)). thenReturn(Optional.of(fileDetails)); when(projectService.isUserLeadPartner(123L, 1L)).thenReturn(true); MvcResult result = mockMvc.perform(get("/project/{projectId}/offer/signed-grant-offer-letter", 123L)). andExpect(status().isOk()). andReturn(); assertEquals("My content!", result.getResponse().getContentAsString()); assertEquals("inline; filename=\"" + fileDetails.getName() + "\"", result.getResponse().getHeader("Content-Disposition")); } @Test @Ignore public void testDownloadSignedGrantOfferLetterByNonLead() throws Exception { mockMvc.perform(get("/project/{projectId}/offer/signed-grant-offer-letter", 123L)). andExpect(status().isInternalServerError()); } @Test public void testDownloadAdditionalContract() throws Exception { FileEntryResource fileDetails = newFileEntryResource().withName("A name").build(); ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes()); when(grantOfferLetterService.getAdditionalContractFile(123L)). thenReturn(Optional.of(fileContents)); when(grantOfferLetterService.getAdditionalContractFileDetails(123L)). thenReturn(Optional.of(fileDetails)); MvcResult result = mockMvc.perform(get("/project/{projectId}/offer/additional-contract", 123L)). andExpect(status().isOk()). andReturn(); assertEquals("My content!", result.getResponse().getContentAsString()); assertEquals("inline; filename=\"" + fileDetails.getName() + "\"", result.getResponse().getHeader("Content-Disposition")); } @Test public void testUploadSignedGrantOfferLetter() throws Exception { FileEntryResource createdFileDetails = newFileEntryResource().withName("A name").build(); MockMultipartFile uploadedFile = new MockMultipartFile("signedGrantOfferLetter", "filename.txt", "text/plain", "My content!".getBytes()); ProjectResource project = newProjectResource().withId(123L).build(); List<ProjectUserResource> pmUser = newProjectUserResource(). withRole(PROJECT_MANAGER). withUser(loggedInUser.getId()). build(1); when(projectService.getById(123L)).thenReturn(project); when(projectService.getProjectUsersForProject(123L)).thenReturn(pmUser); when(grantOfferLetterService.getGrantOfferFileDetails(123L)).thenReturn(Optional.of(createdFileDetails)); when(grantOfferLetterService.addSignedGrantOfferLetter(123L, "text/plain", 11, "filename.txt", "My content!".getBytes())). thenReturn(serviceSuccess(createdFileDetails)); mockMvc.perform( fileUpload("/project/123/offer"). file(uploadedFile). param("uploadSignedGrantOfferLetterClicked", "")). andExpect(status().is3xxRedirection()). andExpect(view().name("redirect:/project/123/offer")); } @Test public void testUploadSignedGrantOfferLetterGolNotSent() throws Exception { FileEntryResource createdFileDetails = newFileEntryResource().withName("A name").build(); MockMultipartFile uploadedFile = new MockMultipartFile("signedGrantOfferLetter", "filename.txt", "text/plain", "My content!".getBytes()); ProjectResource project = newProjectResource().withId(123L).build(); ProjectUserResource pmUser = newProjectUserResource().withRole(PROJECT_MANAGER).withUser(loggedInUser.getId()).build(); List<ProjectUserResource> puRes = new ArrayList<ProjectUserResource>(Arrays.asList(pmUser)); when(projectService.getById(123L)).thenReturn(project); when(projectService.getProjectUsersForProject(123L)).thenReturn(puRes); when(grantOfferLetterService.getSignedGrantOfferLetterFileDetails(123L)).thenReturn(Optional.empty()); when(grantOfferLetterService.getGrantOfferFileDetails(123L)).thenReturn(Optional.of(createdFileDetails)); when(grantOfferLetterService.getAdditionalContractFileDetails(123L)).thenReturn(Optional.empty()); when(grantOfferLetterService.addSignedGrantOfferLetter(123L, "text/plain", 11, "filename.txt", "My content!".getBytes())). thenReturn(serviceFailure(CommonFailureKeys.GRANT_OFFER_LETTER_MUST_BE_SENT_BEFORE_UPLOADING_SIGNED_COPY)); when(grantOfferLetterService.getGrantOfferLetterState(123L)).thenReturn(serviceSuccess(stateInformationForNonPartnersView(READY_TO_APPROVE, GOL_SIGNED))); MvcResult mvcResult = mockMvc.perform( fileUpload("/project/123/offer"). file(uploadedFile). param("uploadSignedGrantOfferLetterClicked", "")). andExpect(status().isOk()). andExpect(view().name("project/grant-offer-letter")).andReturn(); GrantOfferLetterForm form = (GrantOfferLetterForm) mvcResult.getModelAndView().getModel().get("form"); assertEquals(1, form.getObjectErrors().size()); assertEquals(form.getObjectErrors(), form.getBindingResult().getFieldErrors("signedGrantOfferLetter")); assertTrue(form.getObjectErrors().get(0) instanceof FieldError); } @Test public void testUploadSignedGrantOfferLetterGolRejected() throws Exception { FileEntryResource createdFileDetails = newFileEntryResource().withName("A name").build(); MockMultipartFile uploadedFile = new MockMultipartFile("signedGrantOfferLetter", "filename.txt", "text/plain", "My content!".getBytes()); ProjectResource project = newProjectResource().withId(123L).build(); List<ProjectUserResource> pmUser = newProjectUserResource(). withRole(PROJECT_MANAGER). withUser(loggedInUser.getId()). build(1); when(projectService.getById(123L)).thenReturn(project); when(projectService.getProjectUsersForProject(123L)).thenReturn(pmUser); when(grantOfferLetterService.getSignedGrantOfferLetterFileDetails(123L)).thenReturn(Optional.empty()); when(grantOfferLetterService.getGrantOfferFileDetails(123L)).thenReturn(Optional.of(createdFileDetails)); when(grantOfferLetterService.getAdditionalContractFileDetails(123L)).thenReturn(Optional.empty()); when(grantOfferLetterService.addSignedGrantOfferLetter(123L, "text/plain", 11, "filename.txt", "My content!".getBytes())). thenReturn(serviceFailure(CommonFailureKeys.GRANT_OFFER_LETTER_MUST_BE_SENT_BEFORE_UPLOADING_SIGNED_COPY)); when(grantOfferLetterService.getGrantOfferLetterState(123L)).thenReturn(serviceSuccess(stateInformationForNonPartnersView(SENT, SIGNED_GOL_REJECTED))); MvcResult mvcResult = mockMvc.perform( fileUpload("/project/123/offer"). file(uploadedFile). param("uploadSignedGrantOfferLetterClicked", "")). andExpect(status().isOk()). andExpect(view().name("project/grant-offer-letter")).andReturn(); GrantOfferLetterForm form = (GrantOfferLetterForm) mvcResult.getModelAndView().getModel().get("form"); assertEquals(1, form.getObjectErrors().size()); assertEquals(form.getObjectErrors(), form.getBindingResult().getFieldErrors("signedGrantOfferLetter")); assertTrue(form.getObjectErrors().get(0) instanceof FieldError); } @Test public void testConfirmationView() throws Exception { mockMvc.perform(get("/project/123/offer/confirmation")). andExpect(status().isOk()). andExpect(view().name("project/grant-offer-letter-confirmation")); } @Test public void testSubmitOfferLetter() throws Exception { long projectId = 123L; when(grantOfferLetterService.submitGrantOfferLetter(projectId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/" + projectId + "/offer"). param("confirmSubmit", "")). andExpect(status().is3xxRedirection()); verify(grantOfferLetterService).submitGrantOfferLetter(projectId); } @Test public void testRemoveSignedGrantOfferLetter() throws Exception { when(grantOfferLetterService.removeSignedGrantOfferLetter(123L)). thenReturn(serviceSuccess()); mockMvc.perform( post("/project/123/offer"). param("removeSignedGrantOfferLetterClicked", "")). andExpect(status().is3xxRedirection()). andExpect(view().name("redirect:/project/123/offer")); } private void setupSignedSentGrantOfferLetterExpectations(long projectId, long userId, ProjectResource project, boolean projectManager, GrantOfferLetterStateResource state) { FileEntryResource grantOfferLetter = newFileEntryResource().build(); FileEntryResource signedGrantOfferLetter = newFileEntryResource().build(); FileEntryResource additionalContractFile = newFileEntryResource().build(); when(projectService.getById(projectId)).thenReturn(project); when(projectService.isProjectManager(userId, projectId)).thenReturn(projectManager); when(projectService.isUserLeadPartner(projectId, userId)).thenReturn(true); when(grantOfferLetterService.getSignedGrantOfferLetterFileDetails(projectId)).thenReturn(Optional.of(signedGrantOfferLetter)); when(grantOfferLetterService.getGrantOfferFileDetails(projectId)).thenReturn(Optional.of(grantOfferLetter)); when(grantOfferLetterService.getAdditionalContractFileDetails(projectId)).thenReturn(Optional.of(additionalContractFile)); when(grantOfferLetterService.getGrantOfferLetterState(projectId)).thenReturn(serviceSuccess(state)); } private void verifySignedSentGrantOfferLetterExpectations(long projectId, long userId) { verify(projectService).getById(projectId); verify(projectService).isProjectManager(userId, projectId); verify(projectService).isUserLeadPartner(projectId, userId); verify(grantOfferLetterService).getSignedGrantOfferLetterFileDetails(projectId); verify(grantOfferLetterService).getGrantOfferFileDetails(projectId); verify(grantOfferLetterService).getAdditionalContractFileDetails(projectId); verify(grantOfferLetterService).getGrantOfferLetterState(projectId); } @Override protected GrantOfferLetterController supplyControllerUnderTest() { return new GrantOfferLetterController(); } }
package org.apereo.cas.configuration.model.support.pac4j.oidc; import org.apereo.cas.configuration.support.RequiresModule; import lombok.Getter; import lombok.Setter; /** * This is {@link Pac4jAzureOidcClientProperties}. * * @author Misagh Moayyed * @since 6.0.0 */ @RequiresModule(name = "cas-server-support-pac4j-webflow") @Getter @Setter public class Pac4jAzureOidcClientProperties extends BasePac4jOidcClientProperties { private static final long serialVersionUID = 1259382317533639638L; /** * Azure AD tenant name. * After tenant is configured, `discoveryUri` properties will be overrided. * <p> * Azure AD tenant name can take 4 different values: * <ul> * <li>{@code common}: Users with both a personal Microsoft account and a work or * school account from Azure AD can sign in. </li> * <li>{@code organizations}: Only users with work or school accounts from Azure * AD can sign in.</li> * <li>{@code consumers}: Only users with a personal Microsoft account can sign * in.</li> * <li>Specific tenant domain name or ID: Only user with account under that the * specified tenant can login</li> * </ul> */ private String tenant; }
//$HeadURL$ package org.deegree.feature.persistence.postgis; import static org.deegree.commons.utils.JDBCUtils.close; import static org.deegree.feature.persistence.postgis.PostGISFeatureStoreProvider.CONFIG_JAXB_PACKAGE; import static org.deegree.feature.persistence.postgis.PostGISFeatureStoreProvider.CONFIG_SCHEMA; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; import org.deegree.commons.config.DeegreeWorkspace; import org.deegree.commons.config.ResourceInitException; import org.deegree.commons.jdbc.ConnectionManager; import org.deegree.commons.jdbc.ResultSetIterator; import org.deegree.commons.tom.primitive.PrimitiveValue; import org.deegree.commons.tom.primitive.SQLValueMangler; import org.deegree.commons.utils.JDBCUtils; import org.deegree.commons.xml.jaxb.JAXBUtils; import org.deegree.cs.coordinatesystems.ICRS; import org.deegree.feature.Feature; import org.deegree.feature.Features; import org.deegree.feature.i18n.Messages; import org.deegree.feature.persistence.FeatureStore; import org.deegree.feature.persistence.FeatureStoreException; import org.deegree.feature.persistence.FeatureStoreGMLIdResolver; import org.deegree.feature.persistence.FeatureStoreTransaction; import org.deegree.feature.persistence.postgis.jaxb.PostGISFeatureStoreJAXB; import org.deegree.feature.persistence.query.CombinedResultSet; import org.deegree.feature.persistence.query.FeatureResultSet; import org.deegree.feature.persistence.query.FilteredFeatureResultSet; import org.deegree.feature.persistence.query.IteratorResultSet; import org.deegree.feature.persistence.query.MemoryFeatureResultSet; import org.deegree.feature.persistence.query.Query; import org.deegree.feature.persistence.sql.AbstractSQLFeatureStore; import org.deegree.feature.persistence.sql.BBoxTableMapping; import org.deegree.feature.persistence.sql.FeatureBuilder; import org.deegree.feature.persistence.sql.FeatureTypeMapping; import org.deegree.feature.persistence.sql.MappedApplicationSchema; import org.deegree.feature.persistence.sql.blob.BlobCodec; import org.deegree.feature.persistence.sql.blob.BlobMapping; import org.deegree.feature.persistence.sql.blob.FeatureBuilderBlob; import org.deegree.feature.persistence.sql.config.MappedSchemaBuilderGML; import org.deegree.feature.persistence.sql.expressions.JoinChain; import org.deegree.feature.persistence.sql.id.FIDMapping; import org.deegree.feature.persistence.sql.id.IdAnalysis; import org.deegree.feature.persistence.sql.rules.FeatureBuilderRelational; import org.deegree.feature.persistence.sql.rules.GeometryMapping; import org.deegree.feature.persistence.sql.rules.Mapping; import org.deegree.feature.persistence.sql.rules.Mappings; import org.deegree.feature.types.ApplicationSchema; import org.deegree.feature.types.FeatureType; import org.deegree.feature.types.property.FeaturePropertyType; import org.deegree.feature.types.property.GeometryPropertyType; import org.deegree.feature.types.property.PropertyType; import org.deegree.feature.types.property.SimplePropertyType; import org.deegree.filter.Filter; import org.deegree.filter.FilterEvaluationException; import org.deegree.filter.IdFilter; import org.deegree.filter.OperatorFilter; import org.deegree.filter.sort.SortProperty; import org.deegree.filter.sql.DBField; import org.deegree.filter.sql.Join; import org.deegree.filter.sql.MappingExpression; import org.deegree.filter.sql.PropertyNameMapping; import org.deegree.filter.sql.expression.SQLLiteral; import org.deegree.filter.sql.postgis.PostGISWhereBuilder; import org.deegree.geometry.Envelope; import org.deegree.geometry.Geometry; import org.deegree.geometry.GeometryTransformer; import org.deegree.geometry.standard.DefaultEnvelope; import org.deegree.geometry.standard.primitive.DefaultPoint; import org.deegree.gml.GMLObject; import org.postgis.LineString; import org.postgis.LinearRing; import org.postgis.PGboxbase; import org.postgis.PGgeometry; import org.postgis.Point; import org.postgis.Polygon; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link FeatureStore} implementation that uses a PostGIS/PostgreSQL database as backend. * * TODO always ensure that autocommit is false and fetch size is set for (possibly) large SELECTS * * @see FeatureStore * * @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class PostGISFeatureStore extends AbstractSQLFeatureStore { static final Logger LOG = LoggerFactory.getLogger( PostGISFeatureStore.class ); private TransactionManager taManager; // if true, use old-style for spatial predicates (e.g "intersects" instead of "ST_Intersects") private boolean useLegacyPredicates; private Map<String, String> nsContext; private final DeegreeWorkspace workspace; private PostGISFeatureStoreJAXB config; private final URL configURL; /** * Creates a new {@link PostGISFeatureStore} for the given {@link ApplicationSchema}. * * @param config * jaxb configuration object * @param configURL * configuration systemid * @param workspace * deegree workspace, must not be <code>null</code> */ protected PostGISFeatureStore( PostGISFeatureStoreJAXB config, URL configURL, DeegreeWorkspace workspace ) { this.config = config; this.configURL = configURL; this.workspace = workspace; } @Override public FeatureStoreTransaction acquireTransaction() throws FeatureStoreException { return taManager.acquireTransaction(); } protected Envelope getEnvelope( FeatureTypeMapping ftMapping ) throws FeatureStoreException { LOG.trace( "Determining BBOX for feature type '{}' (relational mode)", ftMapping.getFeatureType() ); String column = null; FeatureType ft = getSchema().getFeatureType( ftMapping.getFeatureType() ); GeometryPropertyType pt = ft.getDefaultGeometryPropertyDeclaration(); if ( pt == null ) { return null; } GeometryMapping propMapping = (GeometryMapping) ftMapping.getMapping( pt.getName() ); MappingExpression me = propMapping.getMapping(); if ( me == null || !( me instanceof DBField ) ) { String msg = "Cannot determine BBOX for feature type '" + ft.getName() + "' (relational mode)."; LOG.warn( msg ); return null; } column = ( (DBField) me ).getColumn(); Envelope env = null; StringBuilder sql = new StringBuilder( "SELECT " ); if ( useLegacyPredicates ) { sql.append( "extent" ); } else { sql.append( "ST_Extent" ); } sql.append( "(" ); sql.append( column ); sql.append( ")::BOX2D FROM " ); sql.append( ftMapping.getFtTable() ); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = ConnectionManager.getConnection( getConnId() ); stmt = conn.createStatement(); rs = stmt.executeQuery( sql.toString() ); rs.next(); PGboxbase pgBox = (PGboxbase) rs.getObject( 1 ); if ( pgBox != null ) { ICRS crs = propMapping.getCRS(); org.deegree.geometry.primitive.Point min = buildPoint( pgBox.getLLB(), crs ); org.deegree.geometry.primitive.Point max = buildPoint( pgBox.getURT(), crs ); env = new DefaultEnvelope( null, crs, null, min, max ); } } catch ( SQLException e ) { LOG.debug( e.getMessage(), e ); throw new FeatureStoreException( e.getMessage(), e ); } finally { close( rs, stmt, conn, LOG ); } return env; } private Envelope getEnvelope( QName ftName, BBoxTableMapping bboxMapping ) throws FeatureStoreException { LOG.trace( "Determining BBOX for feature type '{}' (BBOX table mode)", ftName ); Envelope env = null; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = ConnectionManager.getConnection( getConnId() ); stmt = conn.createStatement(); StringBuilder sql = new StringBuilder( "SELECT Box2D(" ); sql.append( bboxMapping.getBBoxColumn() ); sql.append( ") FROM " ); sql.append( bboxMapping.getTable() ); sql.append( " WHERE " ); sql.append( bboxMapping.getFTNameColumn() ); sql.append( "='" ); sql.append( ftName.toString() ); sql.append( "'" ); rs = stmt.executeQuery( sql.toString() ); if ( rs.next() ) { PGboxbase pgBox = (PGboxbase) rs.getObject( 1 ); if ( pgBox != null ) { ICRS crs = bboxMapping.getCRS(); org.deegree.geometry.primitive.Point min = buildPoint( pgBox.getLLB(), crs ); org.deegree.geometry.primitive.Point max = buildPoint( pgBox.getURT(), crs ); env = new DefaultEnvelope( null, bboxMapping.getCRS(), null, min, max ); } } } catch ( SQLException e ) { LOG.debug( e.getMessage(), e ); throw new FeatureStoreException( e.getMessage(), e ); } finally { close( rs, stmt, conn, LOG ); } return env; } protected Envelope getEnvelope( QName ftName, BlobMapping blobMapping ) throws FeatureStoreException { LOG.debug( "Determining BBOX for feature type '{}' (BLOB mode)", ftName ); int ftId = getFtId( ftName ); String column = blobMapping.getBBoxColumn(); Envelope env = null; StringBuilder sql = new StringBuilder( "SELECT " ); if ( useLegacyPredicates ) { sql.append( "extent" ); } else { sql.append( "ST_Extent" ); } sql.append( "(" ); sql.append( column ); sql.append( ")::BOX2D FROM " ); sql.append( blobMapping.getTable() ); sql.append( " WHERE " ); sql.append( blobMapping.getTypeColumn() ); sql.append( "=" ); sql.append( ftId ); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = ConnectionManager.getConnection( getConnId() ); stmt = conn.createStatement(); rs = stmt.executeQuery( sql.toString() ); rs.next(); PGboxbase pgBox = (PGboxbase) rs.getObject( 1 ); if ( pgBox != null ) { ICRS crs = blobMapping.getCRS(); org.deegree.geometry.primitive.Point min = buildPoint( pgBox.getLLB(), crs ); org.deegree.geometry.primitive.Point max = buildPoint( pgBox.getURT(), crs ); env = new DefaultEnvelope( null, blobMapping.getCRS(), null, min, max ); } } catch ( SQLException e ) { LOG.debug( e.getMessage(), e ); throw new FeatureStoreException( e.getMessage(), e ); } finally { close( rs, stmt, conn, LOG ); } return env; } private org.deegree.geometry.primitive.Point buildPoint( org.postgis.Point p, ICRS crs ) { double[] coords = new double[p.getDimension()]; coords[0] = p.getX(); coords[1] = p.getY(); if ( p.getDimension() > 2 ) { coords[2] = p.getZ(); } return new DefaultPoint( null, crs, null, coords ); } @Override protected GMLObject getObjectByIdRelational( String id ) throws FeatureStoreException { GMLObject result = null; IdAnalysis idAnalysis = getSchema().analyzeId( id ); if ( !idAnalysis.isFid() ) { String msg = "Fetching of geometries by id (relational mode) is not implemented yet."; throw new UnsupportedOperationException( msg ); } FeatureType ft = idAnalysis.getFeatureType(); FeatureTypeMapping mapping = getSchema().getFtMapping( ft.getName() ); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { StringBuilder sql = new StringBuilder( "SELECT " ); sql.append( mapping.getFidMapping().getColumn() ); for ( PropertyType pt : ft.getPropertyDeclarations() ) { // append every (mapped) property to SELECT list // TODO columns in related tables with 1:1 relation Mapping mapping2 = mapping.getMapping( pt.getName() ); MappingExpression column = mapping2 == null ? null : Mappings.getMappingExpression( mapping2 ); if ( column != null ) { sql.append( ',' ); if ( column instanceof JoinChain ) { JoinChain jc = (JoinChain) column; sql.append( jc.getFields().get( 0 ) ); } else { if ( pt instanceof SimplePropertyType ) { sql.append( column ); } else if ( pt instanceof GeometryPropertyType ) { if ( useLegacyPredicates ) { sql.append( "AsBinary(" ); } else { sql.append( "ST_AsBinary(" ); } sql.append( column ); sql.append( ')' ); } else if ( pt instanceof FeaturePropertyType ) { sql.append( column ); } else { LOG.warn( "Skipping property '" + pt.getName() + "' -- type '" + pt.getClass() + "' not handled in PostGISFeatureStore#getObjectByIdRelational()." ); } } } } sql.append( " FROM " ); sql.append( mapping.getFtTable() ); sql.append( " WHERE " ); sql.append( mapping.getFidMapping().getColumn() ); sql.append( "=?" ); LOG.debug( "Preparing SELECT: " + sql ); conn = ConnectionManager.getConnection( getConnId() ); stmt = conn.prepareStatement( sql.toString() ); // TODO proper SQL type handling stmt.setInt( 1, Integer.parseInt( idAnalysis.getIdKernel() ) ); rs = stmt.executeQuery(); if ( rs.next() ) { result = new FeatureBuilderRelational( this, ft, mapping, conn ).buildFeature( rs ); } } catch ( Exception e ) { String msg = "Error retrieving object by id (relational mode): " + e.getMessage(); LOG.error( msg, e ); throw new FeatureStoreException( msg, e ); } finally { close( rs, stmt, conn, LOG ); } return result; } @Override protected GMLObject getObjectByIdBlob( String id, BlobMapping blobMapping ) throws FeatureStoreException { GMLObject geomOrFeature = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { StringBuilder sql = new StringBuilder( "SELECT " ); sql.append( blobMapping.getDataColumn() ); sql.append( " FROM " ); sql.append( blobMapping.getTable() ); sql.append( " WHERE " ); sql.append( blobMapping.getGMLIdColumn() ); sql.append( "=?" ); conn = ConnectionManager.getConnection( getConnId() ); stmt = conn.prepareStatement( sql.toString() ); stmt.setString( 1, id ); rs = stmt.executeQuery(); if ( rs.next() ) { LOG.debug( "Recreating object '" + id + "' from bytea." ); BlobCodec codec = blobMapping.getCodec(); geomOrFeature = codec.decode( rs.getBinaryStream( 1 ), getNamespaceContext(), getSchema(), blobMapping.getCRS(), new FeatureStoreGMLIdResolver( this ) ); getCache().add( geomOrFeature ); } } catch ( Exception e ) { String msg = "Error retrieving object by id (BLOB mode): " + e.getMessage(); LOG.debug( msg, e ); throw new FeatureStoreException( msg, e ); } finally { close( rs, stmt, conn, LOG ); } return geomOrFeature; } @Override public void init( DeegreeWorkspace workspace ) throws ResourceInitException { LOG.debug( "init" ); MappedApplicationSchema schema; try { schema = MappedSchemaBuilderGML.build( configURL.toString(), config ); } catch ( Throwable t ) { LOG.error( t.getMessage(), t ); throw new ResourceInitException( t.getMessage(), t ); } String jdbcConnId = config.getJDBCConnId(); init( schema, jdbcConnId ); // lockManager = new DefaultLockManager( this, "LOCK_DB" ); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = ConnectionManager.getConnection( getConnId() ); useLegacyPredicates = JDBCUtils.useLegayPostGISPredicates( conn, LOG ); } catch ( SQLException e ) { LOG.debug( e.getMessage(), e ); throw new ResourceInitException( e.getMessage(), e ); } finally { close( rs, stmt, conn, LOG ); } taManager = new TransactionManager( this, getConnId() ); } private PostGISFeatureStoreJAXB parseConfig( URL configURL ) throws ResourceInitException { try { return (PostGISFeatureStoreJAXB) JAXBUtils.unmarshall( CONFIG_JAXB_PACKAGE, CONFIG_SCHEMA, configURL, workspace ); } catch ( JAXBException e ) { String msg = Messages.getMessage( "STORE_MANAGER_STORE_SETUP_ERROR", e.getMessage() ); throw new ResourceInitException( msg, e ); } } @Override public FeatureResultSet query( Query query ) throws FeatureStoreException, FilterEvaluationException { if ( query.getTypeNames() == null || query.getTypeNames().length > 1 ) { String msg = "Join queries between multiple feature types are currently not supported by the PostGISFeatureStore."; throw new UnsupportedOperationException( msg ); } FeatureResultSet result = null; Filter filter = query.getFilter(); if ( query.getTypeNames().length == 1 && ( filter == null || filter instanceof OperatorFilter ) ) { QName ftName = query.getTypeNames()[0].getFeatureTypeName(); FeatureType ft = getSchema().getFeatureType( ftName ); if ( ft == null ) { String msg = "Feature type '" + ftName + "' is not served by this feature store."; throw new FeatureStoreException( msg ); } result = queryByOperatorFilter( query, ftName, (OperatorFilter) filter ); } else { // must be an id filter based query if ( query.getFilter() == null || !( query.getFilter() instanceof IdFilter ) ) { String msg = "Invalid query. If no type names are specified, it must contain an IdFilter."; throw new FilterEvaluationException( msg ); } result = queryByIdFilter( (IdFilter) filter, query.getSortProperties() ); } return result; } private FeatureResultSet queryByIdFilter( IdFilter filter, SortProperty[] sortCrit ) throws FeatureStoreException { if ( blobMapping != null ) { return queryByIdFilterBlob( filter, sortCrit ); } return queryByIdFilterRelational( filter, sortCrit ); } private FeatureResultSet queryByIdFilterBlob( IdFilter filter, SortProperty[] sortCrit ) throws FeatureStoreException { FeatureResultSet result = null; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = ConnectionManager.getConnection( getConnId() ); // create temp table with ids stmt = conn.createStatement(); stmt.executeUpdate( "CREATE TEMP TABLE temp_ids (fid TEXT)" ); stmt.close(); // fill temp table PreparedStatement insertFid = conn.prepareStatement( "INSERT INTO temp_ids (fid) VALUES (?)" ); for ( String fid : filter.getMatchingIds() ) { insertFid.setString( 1, fid ); insertFid.addBatch(); } insertFid.executeBatch(); stmt = conn.createStatement(); rs = stmt.executeQuery( "SELECT gml_id,binary_object FROM " + blobMapping.getTable() + " A, temp_ids B WHERE A.gml_id=b.fid" ); FeatureBuilder builder = new FeatureBuilderBlob( this, blobMapping ); result = new IteratorResultSet( new PostGISResultSetIterator( builder, rs, conn, stmt ) ); } catch ( Exception e ) { close( rs, stmt, conn, LOG ); String msg = "Error performing id query: " + e.getMessage(); LOG.debug( msg, e ); throw new FeatureStoreException( msg, e ); } finally { if ( conn != null ) { try { // drop temp table stmt = conn.createStatement(); stmt.executeUpdate( "DROP TABLE temp_ids " ); stmt.close(); } catch ( SQLException e ) { String msg = "Error dropping temp table."; LOG.debug( msg, e ); } } } // sort features if ( sortCrit.length > 0 ) { result = new MemoryFeatureResultSet( Features.sortFc( result.toCollection(), sortCrit ) ); } return result; } private FeatureResultSet queryByIdFilterRelational( IdFilter filter, SortProperty[] sortCrit ) throws FeatureStoreException { LinkedHashMap<QName, List<String>> ftNameToIdKernels = new LinkedHashMap<QName, List<String>>(); try { for ( String fid : filter.getMatchingIds() ) { IdAnalysis analysis = getSchema().analyzeId( fid ); FeatureType ft = analysis.getFeatureType(); String idKernel = analysis.getIdKernel(); List<String> idKernels = ftNameToIdKernels.get( ft.getName() ); if ( idKernels == null ) { idKernels = new ArrayList<String>(); ftNameToIdKernels.put( ft.getName(), idKernels ); } idKernels.add( idKernel ); } } catch ( IllegalArgumentException e ) { throw new FeatureStoreException( e.getMessage(), e ); } if ( ftNameToIdKernels.size() != 1 ) { throw new FeatureStoreException( "Currently, only relational id queries are supported that target single feature types." ); } QName ftName = ftNameToIdKernels.keySet().iterator().next(); FeatureType ft = getSchema().getFeatureType( ftName ); FeatureTypeMapping ftMapping = getSchema().getFtMapping( ftName ); FIDMapping fidMapping = ftMapping.getFidMapping(); List<String> idKernels = ftNameToIdKernels.get( ftName ); StringBuilder sql = new StringBuilder( "SELECT " ); sql.append( fidMapping.getColumn() ); for ( PropertyType pt : ft.getPropertyDeclarations() ) { // append every (mapped) property to SELECT list // TODO columns in related tables Mapping mapping = ftMapping.getMapping( pt.getName() ); MappingExpression column = mapping == null ? null : Mappings.getMappingExpression( mapping ); if ( column != null ) { sql.append( ',' ); if ( column instanceof JoinChain ) { JoinChain jc = (JoinChain) column; sql.append( jc.getFields().get( 0 ) ); } else { if ( pt instanceof SimplePropertyType ) { sql.append( column ); } else if ( pt instanceof GeometryPropertyType ) { if ( useLegacyPredicates ) { sql.append( "AsBinary(" ); } else { sql.append( "ST_AsBinary(" ); } sql.append( column ); sql.append( ')' ); } else if ( pt instanceof FeaturePropertyType ) { sql.append( column ); } else { LOG.warn( "Skipping property '" + pt.getName() + "' -- type '" + pt.getClass() + "' not handled in PostGISFeatureStore." ); } } } } sql.append( " FROM " ); sql.append( ftMapping.getFtTable() ); sql.append( " WHERE " ); sql.append( fidMapping.getColumn() ); sql.append( " IN (?" ); for ( int i = 1; i < idKernels.size(); i++ ) { sql.append( ",?" ); } sql.append( ")" ); LOG.debug( "SQL: {}", sql ); FeatureResultSet result = null; PreparedStatement stmt = null; ResultSet rs = null; Connection conn = null; try { long begin = System.currentTimeMillis(); conn = ConnectionManager.getConnection( getConnId() ); stmt = conn.prepareStatement( sql.toString() ); LOG.debug( "Preparing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); int i = 1; for ( String idKernel : idKernels ) { PrimitiveValue value = new PrimitiveValue( idKernel, fidMapping.getColumnType() ); Object sqlValue = SQLValueMangler.internalToSQL( value ); stmt.setObject( i++, sqlValue ); } begin = System.currentTimeMillis(); rs = stmt.executeQuery(); LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); FeatureBuilder builder = new FeatureBuilderRelational( this, ft, ftMapping, conn ); result = new IteratorResultSet( new PostGISResultSetIterator( builder, rs, conn, stmt ) ); } catch ( Exception e ) { close( rs, stmt, conn, LOG ); String msg = "Error performing query by id filter (relational mode): " + e.getMessage(); LOG.error( msg, e ); throw new FeatureStoreException( msg, e ); } return result; } /** * @param conn * @param query * @param ftName * @param filter * @return * @throws FeatureStoreException */ FeatureResultSet queryByOperatorFilter( Query query, QName ftName, OperatorFilter filter ) throws FeatureStoreException { LOG.debug( "Performing query by operator filter" ); PostGISWhereBuilder wb = null; Connection conn = null; FeatureResultSet result = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionManager.getConnection( getConnId() ); // TODO where to put this? conn.setAutoCommit( false ); FeatureType ft = getSchema().getFeatureType( ftName ); FeatureTypeMapping ftMapping = getMapping( ftName ); FeatureBuilder builder = null; if ( getSchema().getBlobMapping() != null ) { builder = new FeatureBuilderBlob( this, getSchema().getBlobMapping() ); } else { builder = new FeatureBuilderRelational( this, ft, ftMapping, conn ); } List<String> columns = builder.getInitialSelectColumns(); PostGISFeatureMapping pgMapping = new PostGISFeatureMapping( getSchema(), ft, ftMapping, this ); wb = new PostGISWhereBuilder( pgMapping, filter, query.getSortProperties(), useLegacyPredicates ); LOG.debug( "WHERE clause: " + wb.getWhere() ); LOG.debug( "ORDER BY clause: " + wb.getOrderBy() ); BlobMapping blobMapping = getSchema().getBlobMapping(); String ftTableAlias = wb.getAliasManager().getRootTableAlias(); String blobTableAlias = wb.getAliasManager().generateNew(); String tableAlias = ftTableAlias; if ( blobMapping != null ) { tableAlias = blobTableAlias; } StringBuilder sql = new StringBuilder( "SELECT " ); sql.append( tableAlias ); sql.append( '.' ); sql.append( columns.get( 0 ) ); for ( int i = 1; i < columns.size(); i++ ) { sql.append( ',' ); // TODO if ( !columns.get( i ).contains( "(" ) ) { sql.append( tableAlias ); sql.append( '.' ); } sql.append( columns.get( i ) ); } sql.append( " FROM " ); if ( blobMapping == null ) { // pure relational query sql.append( ftMapping.getFtTable() ); sql.append( " AS " ); sql.append( ftTableAlias ); } else if ( wb.getWhere() == null && wb.getOrderBy() == null ) { // pure BLOB query sql.append( blobMapping.getTable() ); sql.append( " AS " ); sql.append( blobTableAlias ); } else { // hybrid query sql.append( blobMapping.getTable() ); sql.append( " AS " ); sql.append( blobTableAlias ); sql.append( " LEFT OUTER JOIN " ); sql.append( ftMapping.getFtTable() ); sql.append( " AS " ); sql.append( ftTableAlias ); sql.append( " ON " ); sql.append( blobTableAlias ); sql.append( "." ); sql.append( blobMapping.getInternalIdColumn() ); sql.append( "=" ); sql.append( ftTableAlias ); sql.append( "." ); sql.append( ftMapping.getFidMapping().getColumn() ); } for ( PropertyNameMapping mappedPropName : wb.getMappedPropertyNames() ) { String currentAlias = ftTableAlias; for ( Join join : mappedPropName.getJoins() ) { DBField from = join.getFrom(); DBField to = join.getTo(); sql.append( " LEFT OUTER JOIN " ); sql.append( to.getTable() ); sql.append( " AS " ); sql.append( to.getAlias() ); sql.append( " ON " ); sql.append( currentAlias ); sql.append( "." ); sql.append( from.getColumn() ); sql.append( "=" ); currentAlias = to.getAlias(); sql.append( currentAlias ); sql.append( "." ); sql.append( to.getColumn() ); } } if ( blobMapping != null ) { sql.append( " WHERE " ); sql.append( blobTableAlias ); sql.append( "." ); sql.append( blobMapping.getTypeColumn() ); sql.append( "=?" ); if ( query.getPrefilterBBox() != null ) { sql.append( " AND " ); sql.append( blobTableAlias ); sql.append( "." ); sql.append( blobMapping.getBBoxColumn() ); sql.append( " && ?" ); } } if ( wb.getWhere() != null ) { if ( blobMapping != null ) { sql.append( " AND " ); } else { sql.append( " WHERE " ); } sql.append( wb.getWhere().getSQL() ); } if ( wb.getOrderBy() != null ) { sql.append( " ORDER BY " ); sql.append( wb.getOrderBy().getSQL() ); } LOG.debug( "SQL: {}", sql ); long begin = System.currentTimeMillis(); stmt = conn.prepareStatement( sql.toString() ); LOG.debug( "Preparing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); int i = 1; if ( blobMapping != null ) { stmt.setShort( i++, getSchema().getFtId( ftName ) ); if ( query.getPrefilterBBox() != null ) { Envelope env = (Envelope) getCompatibleGeometry( query.getPrefilterBBox(), blobMapping.getCRS() ); stmt.setObject( i++, toPGPolygon( env, -1 ) ); } } if ( wb.getWhere() != null ) { for ( SQLLiteral o : wb.getWhere().getLiterals() ) { stmt.setObject( i++, o.getValue() ); } } if ( wb.getOrderBy() != null ) { for ( SQLLiteral o : wb.getOrderBy().getLiterals() ) { stmt.setObject( i++, o.getValue() ); } } begin = System.currentTimeMillis(); // TODO make this configurable? stmt.setFetchSize( 1 ); rs = stmt.executeQuery(); LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); result = new IteratorResultSet( new PostGISResultSetIterator( builder, rs, conn, stmt ) ); } catch ( Exception e ) { close( rs, stmt, conn, LOG ); String msg = "Error performing query by operator filter: " + e.getMessage(); LOG.error( msg, e ); throw new FeatureStoreException( msg, e ); } if ( wb.getPostFilter() != null ) { LOG.debug( "Applying in-memory post-filtering." ); result = new FilteredFeatureResultSet( result, wb.getPostFilter() ); } if ( wb.getPostSortCriteria() != null ) { LOG.debug( "Applying in-memory post-sorting." ); result = new MemoryFeatureResultSet( Features.sortFc( result.toCollection(), wb.getPostSortCriteria() ) ); } return result; } private FeatureResultSet queryMultipleFts( Query[] queries, Envelope looseBBox ) throws FeatureStoreException { FeatureResultSet result = null; short[] ftId = new short[queries.length]; for ( int i = 0; i < ftId.length; i++ ) { Query query = queries[i]; if ( query.getTypeNames() == null || query.getTypeNames().length > 1 ) { String msg = "Join queries between multiple feature types are currently not supported."; throw new UnsupportedOperationException( msg ); } ftId[i] = getFtId( query.getTypeNames()[0].getFeatureTypeName() ); } Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionManager.getConnection( getConnId() ); StringBuffer sql = new StringBuffer( "SELECT gml_id,binary_object FROM " + blobMapping.getTable() + " WHERE " ); if ( looseBBox != null ) { sql.append( "gml_bounded_by && ? AND " ); } sql.append( "ft_type IN(?" ); for ( int i = 1; i < ftId.length; i++ ) { sql.append( ",?" ); } sql.append( ") ORDER BY position('['||ft_type||']' IN ?)" ); stmt = conn.prepareStatement( sql.toString() ); int firstFtArg = 1; if ( looseBBox != null ) { stmt.setObject( 1, toPGPolygon( (Envelope) getCompatibleGeometry( looseBBox, blobMapping.getCRS() ), -1 ) ); firstFtArg++; } StringBuffer orderString = new StringBuffer(); for ( int i = 0; i < ftId.length; i++ ) { stmt.setShort( i + firstFtArg, ftId[i] ); orderString.append( "[" ); orderString.append( "" + ftId[i] ); orderString.append( "]" ); } stmt.setString( ftId.length + firstFtArg, orderString.toString() ); LOG.debug( "Query {}", stmt ); rs = stmt.executeQuery(); FeatureBuilder builder = new FeatureBuilderBlob( this, blobMapping ); result = new IteratorResultSet( new PostGISResultSetIterator( builder, rs, conn, stmt ) ); } catch ( Exception e ) { close( rs, stmt, conn, LOG ); String msg = "Error performing query: " + e.getMessage(); LOG.debug( msg, e ); throw new FeatureStoreException( msg, e ); } return result; } // private FeatureResultSet queryMultipleFts2( Query[] queries, Envelope looseBBox ) // throws FeatureStoreException { // FeatureResultSet result = null; // short[] ftId = new short[queries.length]; // for ( int i = 0; i < ftId.length; i++ ) { // Query query = queries[i]; // if ( query.getTypeNames() == null || query.getTypeNames().length > 1 ) { // String msg = "Join queries between multiple feature types are currently not supported."; // throw new UnsupportedOperationException( msg ); // ftId[i] = getFtId( query.getTypeNames()[0].getFeatureTypeName() ); // Connection conn = null; // PreparedStatement stmt = null; // ResultSet rs = null; // try { // conn = ConnectionManager.getConnection( jdbcConnId ); // StringBuffer sql = new StringBuffer(); // if ( queries.length == 1 ) { // sql.append( "SELECT gml_id,binary_object FROM " + qualifyTableName( "gml_objects" ) + " WHERE " ); // if ( looseBBox != null ) { // sql.append( "gml_bounded_by && ? AND " ); // sql.append( "ft_type=?" ); // } else { // sql.append( "(SELECT gml_id,binary_object FROM " + qualifyTableName( "gml_objects" ) + " WHERE " ); // if ( looseBBox != null ) { // sql.append( "gml_bounded_by && ? AND " ); // sql.append( "ft_type=?)" ); // for ( int i = 1; i < queries.length; i++ ) { // sql.append( "UNION (SELECT gml_id,binary_object FROM " + qualifyTableName( "gml_objects" ) // + " WHERE " ); // if ( looseBBox != null ) { // sql.append( "gml_bounded_by && ? AND " ); // sql.append( "ft_type=?)" ); // stmt = conn.prepareStatement( sql.toString() ); // int i = 1; // for ( Query query : queries ) { // if ( looseBBox != null ) { // stmt.setObject( i++, toPGPolygon( (Envelope) getCompatibleGeometry( looseBBox, storageSRS ), -1 ) ); // stmt.setShort( i++, getFtId( query.getTypeNames()[0].getFeatureTypeName() ) ); // StringBuffer orderString = new StringBuffer(); // stmt.setString( ftId.length + 2, orderString.toString() ); // LOG.info( "Query {}", stmt ); // rs = stmt.executeQuery(); // result = new IteratorResultSet( new FeatureResultSetIterator( rs, conn, stmt, // new FeatureStoreGMLIdResolver( this ) ) ); // } catch ( Exception e ) { // closeSafely( conn, stmt, rs ); // String msg = "Error performing query: " + e.getMessage(); // LOG.debug( msg, e ); // throw new FeatureStoreException( msg, e ); // return result; @Override public FeatureResultSet query( final Query[] queries ) throws FeatureStoreException, FilterEvaluationException { // check for most common case: multiple featuretypes, same bbox (WMS), no filter boolean wmsStyleQuery = false; Envelope env = (Envelope) queries[0].getPrefilterBBox(); if ( getSchema().getBlobMapping() != null && queries[0].getFilter() == null && queries[0].getSortProperties().length == 0 ) { wmsStyleQuery = true; for ( int i = 1; i < queries.length; i++ ) { Envelope queryBBox = (Envelope) queries[i].getPrefilterBBox(); if ( queryBBox != env && queries[i].getFilter() != null && queries[i].getSortProperties() != null ) { wmsStyleQuery = false; break; } } } if ( wmsStyleQuery ) { return queryMultipleFts( queries, env ); } Iterator<FeatureResultSet> rsIter = new Iterator<FeatureResultSet>() { int i = 0; @Override public boolean hasNext() { return i < queries.length; } @Override public FeatureResultSet next() { if ( !hasNext() ) { throw new NoSuchElementException(); } FeatureResultSet rs; try { rs = query( queries[i++] ); } catch ( Exception e ) { LOG.debug( e.getMessage(), e ); throw new RuntimeException( e.getMessage(), e ); } return rs; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new CombinedResultSet( rsIter ); } @Override public String[] getDDL() { return new PostGISDDLCreator( getSchema() ).getDDL(); } /** * Returns a transformed version of the given {@link Geometry} in the specified CRS. * * @param literal * @param crs * @return transformed version of the geometry, never <code>null</code> * @throws FilterEvaluationException */ Geometry getCompatibleGeometry( Geometry literal, ICRS crs ) throws FilterEvaluationException { Geometry transformedLiteral = literal; if ( literal != null ) { ICRS literalCRS = literal.getCoordinateSystem(); if ( literalCRS != null && !( crs.equals( literalCRS ) ) ) { LOG.debug( "Need transformed literal geometry for evaluation: " + literalCRS.getAlias() + " -> " + crs.getAlias() ); try { GeometryTransformer transformer = new GeometryTransformer( crs ); transformedLiteral = transformer.transform( literal ); } catch ( Exception e ) { throw new FilterEvaluationException( e.getMessage() ); } } } return transformedLiteral; } short getFtId( QName ftName ) { return getSchema().getFtId( ftName ); } PGgeometry toPGPolygon( Envelope envelope, int srid ) { PGgeometry pgGeometry = null; if ( envelope != null ) { double minX = envelope.getMin().get0(); double minY = envelope.getMin().get1(); double maxX = envelope.getMax().get0(); double maxY = envelope.getMax().get1(); if ( envelope.getMin().equals( envelope.getMax() ) ) { Point point = new Point( envelope.getMin().get0(), envelope.getMin().get1() ); // TODO point.setSrid( srid ); pgGeometry = new PGgeometry( point ); } else if ( minX == maxX || minY == maxY ) { LineString line = new LineString( new Point[] { new Point( minX, minY ), new Point( maxX, maxY ) } ); // TODO line.setSrid( srid ); pgGeometry = new PGgeometry( line ); } else { Point[] points = new Point[] { new Point( minX, minY ), new Point( maxX, minY ), new Point( maxX, maxY ), new Point( minX, maxY ), new Point( minX, minY ) }; LinearRing outer = new LinearRing( points ); Polygon polygon = new Polygon( new LinearRing[] { outer } ); // TODO polygon.setSrid( srid ); pgGeometry = new PGgeometry( polygon ); } } return pgGeometry; } String getWKBParamTemplate( String srid ) { StringBuilder sb = new StringBuilder(); if ( useLegacyPredicates ) { sb.append( "SetSRID(GeomFromWKB(?)," ); } else { sb.append( "SetSRID(ST_GeomFromWKB(?)," ); } sb.append( srid ); sb.append( ")" ); return sb.toString(); } private class PostGISResultSetIterator extends ResultSetIterator<Feature> { private final FeatureBuilder builder; public PostGISResultSetIterator( FeatureBuilder builder, ResultSet rs, Connection conn, Statement stmt ) { super( rs, conn, stmt ); this.builder = builder; } @Override protected Feature createElement( ResultSet rs ) throws SQLException { return builder.buildFeature( rs ); } } }
package cs201.gui; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.List; import javax.swing.JPanel; import javax.swing.Timer; import cs201.agents.PassengerTestAgent; import cs201.agents.transit.BusAgent; import cs201.agents.transit.CarAgent; import cs201.agents.transit.TruckAgent; import cs201.gui.CityPanel.DrivingDirection; import cs201.gui.transit.BusGui; import cs201.gui.transit.CarGui; import cs201.gui.transit.PassengerGui; import cs201.gui.transit.VehicleGui; import cs201.helper.CityDirectory; import cs201.helper.transit.BusRoute; import cs201.roles.marketRoles.MarketManagerRole.ItemRequest; import cs201.roles.transit.PassengerRole; import cs201.structures.Structure; import cs201.structures.residence.Residence; import cs201.structures.transit.BusStop; public class CityPanel extends JPanel implements MouseListener, ActionListener { public static final int GRID_SIZE = 25; public static CityPanel INSTANCE = null; List<Structure> buildings; List<Gui> guis; public enum DrivingDirection { None,North,South,East,West,Turn; public DrivingDirection turnRight() { if(this == North) { return East; } else if(this == East) { return South; } else if(this == South) { return West; } else if(this == West) { return North; } return this; } public boolean isValid() { return ordinal() > 0; } public boolean isVertical() { return this == North || this == South; } public boolean isHorizontal() { return this == West || this == East; } public static boolean opposites(DrivingDirection drivingDirection, DrivingDirection drivingDirection2) { return (drivingDirection == West && drivingDirection2 == East) || (drivingDirection == East && drivingDirection2 == West) || (drivingDirection == South && drivingDirection2 == North) || (drivingDirection == North && drivingDirection2 == South); } }; public enum WalkingDirection { None,North,South,East,West,Turn; public WalkingDirection turnRight() { if(this == North) { return East; } else if(this == East) { return South; } else if(this == South) { return West; } else if(this == West) { return North; } return this; } public boolean isValid() { return ordinal() > 0; } public boolean isVertical() { return this == North || this == South; } public boolean isHorizontal() { return this == West || this == East; } public static boolean opposites(WalkingDirection drivingDirection, WalkingDirection drivingDirection2) { return (drivingDirection == West && drivingDirection2 == East) || (drivingDirection == East && drivingDirection2 == West) || (drivingDirection == South && drivingDirection2 == North) || (drivingDirection == North && drivingDirection2 == South); } }; private String[][] cityGrid = { {"G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G"},{"G","ST","8","ST","8","8","ST","8","ST","8","8","ST","8","ST","8","8","ST","8","ST","8","8","ST","8","ST","G"},{"G","7","T","47","4","4","45","T","47","4","4","45","T","47","4","4","45","T","47","4","4","45","T","5","G"},{"G","ST","38","ST","8","8","ST","38","ST","8","8","ST","18","ST","8","8","ST","38","ST","8","8","ST","18","ST","G"},{"G","7","3","7","G","G","5","3","7","G","G","5","1","7","G","G","5","3","7","G","G","5","1","5","G"},{"G","7","3","7","G","G","5","3","7","G","G","5","1","7","G","G","5","3","7","G","G","5","1","5","G"},{"G","ST","36","ST","6","6","ST","36","ST","6","6","ST","16","ST","6","6","ST","36","6","6","6","ST","16","ST","G"},{"G","7","T","27","2","2","25","T","27","2","2","25","T","27","2","2","25","T","27","2","2","25","T","5","G"},{"G","ST","18","ST","8","8","ST","18","ST","8","8","ST","38","ST","8","8","ST","18","ST","8","8","ST","38","ST","G"},{"G","7","1","7","G","G","5","1","7","G","G","5","3","7","G","G","5","1","7","G","G","5","3","5","G"},{"G","7","1","7","G","G","5","1","7","G","G","5","3","7","G","G","5","1","7","G","G","5","3","5","G"},{"G","ST","16","ST","6","6","ST","16","ST","6","6","ST","36","ST","6","6","ST","16","ST","6","6","ST","36","ST","G"},{"G","7","T","47","4","4","45","T","47","4","4","45","T","47","4","4","45","T","47","4","4","45","T","5","G"},{"G","ST","6","ST","6","6","ST","6","ST","6","6","ST","6","ST","6","6","ST","6","ST","6","6","ST","6","ST","G"},{"G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G","G"}, }; private List<BusStop> stops; private static final boolean SHOW_DEBUG = true; public CityPanel() { Timer timer = new Timer(1000/240,this); buildings = Collections.synchronizedList(new ArrayList<Structure>()); guis = Collections.synchronizedList(new ArrayList<Gui>()); stops = new ArrayList<BusStop>(); if(INSTANCE == null) { INSTANCE = this; } addMouseListener(this); populateDrivingMap(); //Testing Hacks stops.add(new BusStop(22*25,13*25,25,25,1, null)); stops.add(new BusStop(12*25,13*25,25,25,2, null)); stops.add(new BusStop(2*25,13*25,25,25,3, null)); stops.add(new BusStop(22*25,1*25,25,25,4, null)); stops.add(new BusStop(12*25,1*25,25,25,5, null)); stops.add(new BusStop(2*25,1*25,25,25,6, null)); for(BusStop stop : stops) { buildings.add(stop); stop.setParkingLocation(new Point((int)stop.x,((int)stop.y==25?2*25:12*25))); stop.setEntranceLocation(new Point((int)stop.x,(int)stop.y)); } BusAgent bus = new BusAgent(new BusRoute(stops),0); VehicleGui busG; guis.add(busG = new BusGui(bus,this,(int)stops.get(0).getParkingLocation().x,(int)stops.get(0).getParkingLocation().y)); bus.setGui(busG); bus.startThread(); /* BusAgent bus2 = new BusAgent(new BusRoute(stops),2); VehicleGui busG2; guis.add(busG2 = new VehicleGui(bus2,this,(int)stops.get(2).x,(int)stops.get(2).y)); bus2.setGui(busG2); bus2.startThread(); Structure startLoc = new BusStop(18*25,2*25,25,25,1, null); Structure endLoc = new BusStop(50,50,25,25,2, null); PassengerRole pass = new PassengerRole(stops.get(0)); pass.setBusStops(stops); PassengerGui pgui = new PassengerGui(pass,this); pass.setGui(pgui); guis.add(pgui); PassengerTestAgent passAgent = new PassengerTestAgent(pass); pass.msgGoTo(stops.get(5)); CarAgent car = new CarAgent(); VehicleGui gui; guis.add(gui = new CarGui(car,this)); pass.addCar(car); car.setGui(gui); car.startThread(); passAgent.startThread(); TruckAgent truck = new TruckAgent(stops.get(0)); truck.msgMakeDeliveryRun(new ArrayList<ItemRequest>(), stops.get(1),1); truck.msgMakeDeliveryRun(new ArrayList<ItemRequest>(), stops.get(2),1); truck.startThread();*/ timer.start(); } public void addGui(Gui gui) { guis.add(gui); } private void populateDrivingMap() { drivingMap = new DrivingDirection[cityGrid.length][cityGrid[0].length]; walkingMap = new WalkingDirection[cityGrid.length][cityGrid[0].length]; for(int y = 0; y < cityGrid.length; y++) { for(int x = 0; x < cityGrid[y].length; x++) { DrivingDirection dir = DrivingDirection.None; WalkingDirection wDir = WalkingDirection.None; if(Character.isDigit(cityGrid[y][x].charAt(0))) { int val = Integer.parseInt(cityGrid[y][x].substring(0,1)); switch(val) { case 1:dir = DrivingDirection.North;break; case 2:dir = DrivingDirection.East;break; case 3:dir = DrivingDirection.South;break; case 4:dir = DrivingDirection.West;break; default:dir = DrivingDirection.None;break; } if(cityGrid[y][x].length() == 2) { if(Character.isDigit(cityGrid[y][x].charAt(1))) { val = Integer.parseInt(cityGrid[y][x].substring(1)); } } switch(val) { case 5:wDir = WalkingDirection.North;break; case 6:wDir = WalkingDirection.East;break; case 7:wDir = WalkingDirection.South;break; case 8:wDir = WalkingDirection.West;break; default:wDir = WalkingDirection.None;break; } } else { if(cityGrid[y][x].equals("T")) { dir = DrivingDirection.Turn; wDir = WalkingDirection.None; } else if(cityGrid[y][x].equals("ST")) { dir = DrivingDirection.None; wDir = WalkingDirection.Turn; } else { dir = DrivingDirection.None; wDir = WalkingDirection.None; } } drivingMap[y][x] = dir; walkingMap[y][x] = wDir; } } } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; Dimension bounds = getPreferredSize(); g2.setColor(Color.LIGHT_GRAY.brighter().brighter()); g2.fillRect(0,0,(int)bounds.getWidth(),(int)bounds.getHeight()); for(int y = 0; y < cityGrid.length; y++) { for(int x = 0; x < cityGrid[y].length; x++) { if(cityGrid[y][x].equals("G")) { g2.setColor(Color.GREEN); } else if(cityGrid[y][x].equals("R")) { g2.setColor(Color.GRAY.darker()); } else if(cityGrid[y][x].equals("ST") || Character.isDigit(cityGrid[y][x].charAt(0)) && Integer.parseInt(cityGrid[y][x].substring(0,1)) > 4) { g2.setColor(Color.GRAY.brighter().brighter().brighter().brighter()); } else if(cityGrid[y][x].equals("T") || Character.isDigit(cityGrid[y][x].charAt(0))) { g2.setColor(Color.GRAY.darker()); } g2.fillRect(x*GRID_SIZE, y*GRID_SIZE, GRID_SIZE, GRID_SIZE); if(cityGrid[y][x].length() == 2 && Character.isDigit(cityGrid[y][x].charAt(1))) { g2.setColor(Color.GRAY.brighter()); for(int i = 0; i < 5 ; i++) { if(i % 2 == 0) { if(drivingMap[y][x].isVertical()) { g2.fillRect(x*GRID_SIZE+i*5,y*GRID_SIZE,5,GRID_SIZE); } else { g2.fillRect(x*GRID_SIZE,y*GRID_SIZE+i*5,GRID_SIZE,5); } } } } if(SHOW_DEBUG) { if(drivingMap[y][x].isValid()) { if(drivingMap[y][x] == DrivingDirection.North) { g2.setColor(Color.BLACK); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.25)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y+.75)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.25)*GRID_SIZE), (int)((1.0*x)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.25)*GRID_SIZE), (int)((1.0*x+1)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); } else if(drivingMap[y][x] == DrivingDirection.South) { g2.setColor(Color.BLACK); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.25)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y+.75)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.75)*GRID_SIZE), (int)((1.0*x)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.75)*GRID_SIZE), (int)((1.0*x+1)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); } else if(drivingMap[y][x] == DrivingDirection.West) { g2.setColor(Color.BLACK); g2.drawLine((int)((1.0*x+.25)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.75)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.25)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y+1)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.25)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y)*GRID_SIZE)); } else if(drivingMap[y][x] == DrivingDirection.East) { g2.setColor(Color.BLACK); g2.drawLine((int)((1.0*x+.25)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.75)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.75)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y+1)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.75)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y)*GRID_SIZE)); } } if(walkingMap[y][x].isValid()) { if(walkingMap[y][x] == WalkingDirection.North) { g2.setColor(Color.BLACK); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.25)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y+.75)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.25)*GRID_SIZE), (int)((1.0*x)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.25)*GRID_SIZE), (int)((1.0*x+1)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); } else if(walkingMap[y][x] == WalkingDirection.South) { g2.setColor(Color.BLACK); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.25)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y+.75)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.75)*GRID_SIZE), (int)((1.0*x)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.5)*GRID_SIZE),(int)((1.0*y+.75)*GRID_SIZE), (int)((1.0*x+1)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); } else if(walkingMap[y][x] == WalkingDirection.West) { g2.setColor(Color.BLACK); g2.drawLine((int)((1.0*x+.25)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.75)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.25)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y+1)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.25)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y)*GRID_SIZE)); } else if(walkingMap[y][x] == WalkingDirection.East) { g2.setColor(Color.BLACK); g2.drawLine((int)((1.0*x+.25)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.75)*GRID_SIZE), (int)((1.0*y+.5)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.75)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y+1)*GRID_SIZE)); g2.drawLine((int)((1.0*x+.75)*GRID_SIZE),(int)((1.0*y+.5)*GRID_SIZE), (int)((1.0*x+.5)*GRID_SIZE), (int)((1.0*y)*GRID_SIZE)); } } } } } if(SHOW_DEBUG) { g2.setColor(Color.BLACK); for(int x = 0; x < cityGrid[0].length; x++) { for(int y = 0; y < cityGrid.length; y++) { g2.drawRect(x*GRID_SIZE, y*GRID_SIZE, GRID_SIZE, GRID_SIZE); if(y == 1) { g2.drawString(""+x,x*GRID_SIZE,y*GRID_SIZE); } if(x == 0) { g2.drawString(""+y, x, (y+1)*GRID_SIZE); } } } } for (int i = 0; i < buildings.size(); i++) { g2.setColor(Color.BLACK); Structure s = buildings.get(i); g2.fill(s); g2.setColor(Color.WHITE); g2.drawString(""+s.getId(),(int)s.x,(int)(s.y + s.height)); if(SHOW_DEBUG) { g2.setColor(Color.BLUE); g2.fill(new Rectangle(s.getParkingLocation().x,s.getParkingLocation().y,GRID_SIZE,GRID_SIZE)); g2.fill(new Rectangle(s.getEntranceLocation().x,s.getEntranceLocation().y,GRID_SIZE,GRID_SIZE)); g2.setColor(Color.WHITE); g2.drawString("P",s.getParkingLocation().x,s.getParkingLocation().y+25); g2.drawString("E",s.getEntranceLocation().x,s.getEntranceLocation().y+25); } } try { for(Gui gui: guis) { if(gui.isPresent()) { gui.updatePosition(); gui.draw(g2); } } } catch(ConcurrentModificationException e) { } g2.setColor(Color.BLACK); g2.drawString(CityDirectory.getInstance().getTime().toString(), bounds.width / 2, bounds.height - bounds.height / 10); } public void addStructure(Structure s) { //testing hacks buildings.add(s); Point location = new Point(); location.x = (int)s.getX(); location.y = (int)s.getY(); //Calculating street entrance int leftX = location.x/GRID_SIZE - 2; int rightX = (int)((1.0*location.x+s.width)/GRID_SIZE) + 1; int upY = location.y/GRID_SIZE - 2; int downY = (int)((1.0*location.y+s.height)/GRID_SIZE) + 1; if(downY < drivingMap.length && drivingMap[downY][location.x/GRID_SIZE].isValid()) { location.y = downY*GRID_SIZE; s.setParkingLocation(location); } else if(leftX >= 0 && drivingMap[location.y/GRID_SIZE][leftX].isValid()) { location.x = leftX*GRID_SIZE; s.setParkingLocation(location); } else if(rightX < drivingMap[0].length && drivingMap[location.y/GRID_SIZE][rightX].isValid()) { location.x = rightX*GRID_SIZE; s.setParkingLocation(location); } else if(upY >= 0 && drivingMap[upY][location.x/GRID_SIZE].isValid()) { location.y = upY*GRID_SIZE; s.setParkingLocation(location); } location = new Point(); location.x = (int)s.getX(); location.y = (int)s.getY(); //Calculating sidewalk entrance leftX = location.x/GRID_SIZE - 1; rightX = (int)((1.0*location.x+s.width)/GRID_SIZE); upY = location.y/GRID_SIZE - 1; downY = (int)((1.0*location.y+s.height)/GRID_SIZE); if(downY < walkingMap.length && walkingMap[downY][location.x/GRID_SIZE].isValid()) { location.y = downY*GRID_SIZE; s.setEntranceLocation(location); } else if(leftX >= 0 && walkingMap[location.y/GRID_SIZE][leftX].isValid()) { location.x = leftX*GRID_SIZE; s.setParkingLocation(location); } else if(rightX < walkingMap[0].length && walkingMap[location.y/GRID_SIZE][rightX].isValid()) { location.x = rightX*GRID_SIZE; s.setParkingLocation(location); } else if(upY >= 0 && walkingMap[upY][location.x/GRID_SIZE].isValid()) { location.y = upY*GRID_SIZE; s.setParkingLocation(location); } /* CarAgent car = new CarAgent(); VehicleGui gui; guis.add(gui = new CarGui(car,this)); car.setGui(gui); car.startThread(); PassengerRole role = new PassengerRole(stops.get(1)); PassengerTestAgent agent = new PassengerTestAgent(role); role.setBusStops(stops); //role.addCar(car); PassengerGui pgui = new PassengerGui(role,this); role.setGui(pgui); guis.add(pgui); role.msgGoTo(s); agent.startThread();*/ } public void addStructure(Structure s, Point parking,Point entrance) { buildings.add(s); s.setParkingLocation(parking); s.setEntranceLocation(entrance); } public List<Structure> getStructures() { return buildings; } @Override public void mouseClicked(MouseEvent arg0) { for (int i = 0; i < buildings.size(); i++) { Structure s = buildings.get(i); if (s.contains(arg0.getX(), arg0.getY())) { s.displayStructure(); } } } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } public DrivingDirection[][] drivingMap; public WalkingDirection[][] walkingMap; public DrivingDirection[][] getDrivingMap() { return drivingMap; } public WalkingDirection[][] getWalkingMap() { return walkingMap; } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub repaint(); } }
package org.ovirt.engine.ui.webadmin.section.main.view.popup.vm; import java.util.ArrayList; import java.util.List; import org.ovirt.engine.core.common.businessentities.Cluster; import org.ovirt.engine.core.common.businessentities.OriginType; import org.ovirt.engine.core.common.businessentities.Quota; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.network.VmInterfaceType; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.businessentities.network.VnicProfileView; import org.ovirt.engine.core.common.businessentities.profiles.CpuProfile; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.businessentities.storage.VolumeType; import org.ovirt.engine.ui.common.CommonApplicationTemplates; import org.ovirt.engine.ui.common.idhandler.WithElementId; import org.ovirt.engine.ui.common.uicommon.model.DetailModelProvider; import org.ovirt.engine.ui.common.view.popup.AbstractModelBoundPopupView; import org.ovirt.engine.ui.common.widget.Align; import org.ovirt.engine.ui.common.widget.dialog.SimpleDialogPanel; import org.ovirt.engine.ui.common.widget.editor.ListModelListBoxEditor; import org.ovirt.engine.ui.common.widget.editor.ListModelListBoxOnlyEditor; import org.ovirt.engine.ui.common.widget.editor.ListModelObjectCellTable; import org.ovirt.engine.ui.common.widget.editor.generic.EntityModelCheckBoxEditor; import org.ovirt.engine.ui.common.widget.renderer.EnumRenderer; import org.ovirt.engine.ui.common.widget.renderer.NullSafeRenderer; import org.ovirt.engine.ui.common.widget.renderer.StorageDomainFreeSpaceRenderer; import org.ovirt.engine.ui.common.widget.renderer.StringRenderer; import org.ovirt.engine.ui.common.widget.table.column.AbstractCheckboxColumn; import org.ovirt.engine.ui.common.widget.table.column.AbstractDiskSizeColumn; import org.ovirt.engine.ui.common.widget.table.column.AbstractEnumColumn; import org.ovirt.engine.ui.common.widget.table.column.AbstractImageResourceColumn; import org.ovirt.engine.ui.common.widget.table.column.AbstractTextColumn; import org.ovirt.engine.ui.common.widget.table.header.ImageResourceHeader; import org.ovirt.engine.ui.common.widget.uicommon.disks.DisksViewColumns; import org.ovirt.engine.ui.uicommonweb.models.HasEntity; import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel; import org.ovirt.engine.ui.uicommonweb.models.vms.ImportEntityData; import org.ovirt.engine.ui.uicommonweb.models.vms.ImportNetworkData; import org.ovirt.engine.ui.uicommonweb.models.vms.ImportSource; import org.ovirt.engine.ui.uicommonweb.models.vms.ImportVmData; import org.ovirt.engine.ui.uicommonweb.models.vms.ImportVmFromExternalProviderModel; import org.ovirt.engine.ui.uicommonweb.models.vms.ImportVmModel; import org.ovirt.engine.ui.uicommonweb.models.vms.VmImportGeneralModel; import org.ovirt.engine.ui.uicompat.Event; import org.ovirt.engine.ui.uicompat.IEventListener; import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs; import org.ovirt.engine.ui.webadmin.ApplicationConstants; import org.ovirt.engine.ui.webadmin.ApplicationResources; import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.vm.ImportVmFromExternalProviderPopupPresenterWidget; import org.ovirt.engine.ui.webadmin.section.main.view.popup.storage.backup.ImportVmGeneralSubTabView; import org.ovirt.engine.ui.webadmin.widget.table.cell.CustomSelectionCell; import org.ovirt.engine.ui.webadmin.widget.table.column.VmTypeColumn; import com.google.gwt.cell.client.FieldUpdater; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.editor.client.SimpleBeanEditorDriver; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.shared.EventBus; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.SplitLayoutPanel; import com.google.gwt.user.client.ui.TabLayoutPanel; import com.google.gwt.view.client.NoSelectionModel; import com.google.gwt.view.client.SelectionChangeEvent; import com.google.gwt.view.client.SelectionChangeEvent.Handler; import com.google.gwt.view.client.SingleSelectionModel; import com.google.inject.Inject; public class ImportVmFromExternalProviderPopupView extends AbstractModelBoundPopupView<ImportVmFromExternalProviderModel> implements ImportVmFromExternalProviderPopupPresenterWidget.ViewDef { interface Driver extends SimpleBeanEditorDriver<ImportVmFromExternalProviderModel, ImportVmFromExternalProviderPopupView> { } interface ViewUiBinder extends UiBinder<SimpleDialogPanel, ImportVmFromExternalProviderPopupView> { ViewUiBinder uiBinder = GWT.create(ViewUiBinder.class); } @UiField WidgetStyle style; @UiField(provided = true) @Path(value = "cluster.selectedItem") ListModelListBoxEditor<Cluster> destClusterEditor; @UiField(provided = true) @Path(value = "cpuProfiles.selectedItem") ListModelListBoxEditor<CpuProfile> cpuProfileEditor; @UiField(provided = true) @Path(value = "clusterQuota.selectedItem") ListModelListBoxEditor<Quota> destClusterQuotaEditor; @UiField(provided = true) @Path(value = "storage.selectedItem") ListModelListBoxEditor<StorageDomain> destStorageEditor; @UiField(provided = true) @Path(value = "allocation.selectedItem") ListModelListBoxEditor<VolumeType> disksAllocationEditor; @UiField(provided = true) @Path(value = "iso.selectedItem") @WithElementId("iso") public ListModelListBoxOnlyEditor<String> cdImageEditor; @UiField(provided = true) @Path(value = "attachDrivers.entity") @WithElementId("attachDrivers") public EntityModelCheckBoxEditor attachDriversEditor; @UiField SplitLayoutPanel splitLayoutPanel; @UiField @Ignore Label message; @Ignore protected ListModelObjectCellTable<ImportVmData, ImportVmFromExternalProviderModel> table; @Ignore private ListModelObjectCellTable<DiskImage, SearchableListModel> diskTable; @Ignore private ListModelObjectCellTable<VmNetworkInterface, SearchableListModel> nicTable; @Ignore protected TabLayoutPanel subTabLayoutPanel = null; boolean firstSelection = false; private ImportVmGeneralSubTabView generalView; private CustomSelectionCell customSelectionCellNetwork; protected ImportVmFromExternalProviderModel importModel; private final Driver driver = GWT.create(Driver.class); protected final ApplicationConstants constants; protected final ApplicationResources resources; @Inject public ImportVmFromExternalProviderPopupView(EventBus eventBus, ApplicationResources resources, ApplicationConstants constants) { super(eventBus); this.constants = constants; this.resources = resources; initListBoxEditors(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); applyStyles(); localize(constants); initTables(); driver.initialize(this); } protected void applyStyles() { attachDriversEditor.addContentWidgetContainerStyleName(style.cdAttachedLabelWidth()); } private void initTables() { initMainTable(); initNicsTable(); initDiskTable(); } protected void initMainTable() { this.table = new ListModelObjectCellTable<>(); AbstractCheckboxColumn<ImportVmData> cloneVMColumn = new AbstractCheckboxColumn<ImportVmData>(new FieldUpdater<ImportVmData, Boolean>() { @Override public void update(int index, ImportVmData model, Boolean value) { ((ImportVmData) model).getClone().setEntity(value); table.asEditor().edit(importModel); } }) { @Override public Boolean getValue(ImportVmData model) { return (Boolean) ((ImportVmData) model).getClone().getEntity(); } @Override protected boolean canEdit(ImportVmData model) { return ((ImportVmData) model).getClone().getIsChangable(); } @Override protected String getDisabledMessage(ImportVmData model) { return ((ImportVmData) model).getClone().getChangeProhibitionReason(); } }; table.addColumn(cloneVMColumn, constants.cloneVM(), "50px"); //$NON-NLS-1$ AbstractTextColumn<ImportVmData> nameColumn = new AbstractTextColumn<ImportVmData>() { @Override public String getValue(ImportVmData object) { return object.getName(); } }; table.addColumn(nameColumn, constants.nameVm(), "150px"); //$NON-NLS-1$ AbstractTextColumn<ImportVmData> originColumn = new AbstractEnumColumn<ImportVmData, OriginType>() { @Override protected OriginType getRawValue(ImportVmData object) { return ((ImportVmData) object).getVm().getOrigin(); } }; table.addColumn(originColumn, constants.originVm(), "100px"); //$NON-NLS-1$ table.addColumn( new AbstractImageResourceColumn<ImportVmData>() { @Override public com.google.gwt.resources.client.ImageResource getValue(ImportVmData object) { return new VmTypeColumn().getValue(((ImportVmData) object).getVm()); } }, constants.empty(), "30px"); //$NON-NLS-1$ AbstractTextColumn<ImportVmData> memoryColumn = new AbstractTextColumn<ImportVmData>() { @Override public String getValue(ImportVmData object) { return String.valueOf(((ImportVmData) object).getVm().getVmMemSizeMb()) + " MB"; //$NON-NLS-1$ } }; table.addColumn(memoryColumn, constants.memoryVm(), "100px"); //$NON-NLS-1$ AbstractTextColumn<ImportVmData> cpuColumn = new AbstractTextColumn<ImportVmData>() { @Override public String getValue(ImportVmData object) { return String.valueOf(((ImportVmData) object).getVm().getNumOfCpus()); } }; table.addColumn(cpuColumn, constants.cpusVm(), "50px"); //$NON-NLS-1$ AbstractTextColumn<ImportVmData> archColumn = new AbstractTextColumn<ImportVmData>() { @Override public String getValue(ImportVmData object) { return String.valueOf(((ImportVmData) object).getVm().getClusterArch()); } }; table.addColumn(archColumn, constants.architectureVm(), "50px"); //$NON-NLS-1$ AbstractTextColumn<ImportVmData> diskColumn = new AbstractTextColumn<ImportVmData>() { @Override public String getValue(ImportVmData object) { return String.valueOf(((ImportVmData) object).getVm().getDiskMap().size()); } }; table.addColumn(diskColumn, constants.disksVm(), "50px"); //$NON-NLS-1$ ScrollPanel sp = new ScrollPanel(); sp.add(table); splitLayoutPanel.add(sp); table.getElement().getStyle().setPosition(Position.RELATIVE); } private void localize(ApplicationConstants constants) { destClusterEditor.setLabel(constants.importVm_destCluster()); destClusterQuotaEditor.setLabel(constants.importVm_destClusterQuota()); destStorageEditor.setLabel(constants.storageDomainDisk()); cpuProfileEditor.setLabel(constants.cpuProfileLabel()); disksAllocationEditor.setLabel(constants.allocationDisk()); attachDriversEditor.setLabel(constants.attachVirtioDrivers()); } private void initListBoxEditors() { destClusterEditor = new ListModelListBoxEditor<>(new NullSafeRenderer<Cluster>() { @Override public String renderNullSafe(Cluster object) { return object.getName(); } }); destClusterQuotaEditor = new ListModelListBoxEditor<>(new NullSafeRenderer<Quota>() { @Override public String renderNullSafe(Quota object) { return object.getQuotaName(); } }); destStorageEditor = new ListModelListBoxEditor<>(new StorageDomainFreeSpaceRenderer()); cpuProfileEditor = new ListModelListBoxEditor<>(new NullSafeRenderer<CpuProfile>() { @Override protected String renderNullSafe(CpuProfile object) { return object.getName(); } }); disksAllocationEditor = new ListModelListBoxEditor<>(new NullSafeRenderer<VolumeType>() { @Override protected String renderNullSafe(VolumeType object) { return new EnumRenderer<VolumeType>().render(object); } }); attachDriversEditor = new EntityModelCheckBoxEditor(Align.LEFT); cdImageEditor = new ListModelListBoxOnlyEditor<>(new StringRenderer<String>()); } @Override public void edit(final ImportVmFromExternalProviderModel importModel) { this.importModel = importModel; table.asEditor().edit(importModel); importModel.getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if (args.propertyName.equals(importModel.ON_DISK_LOAD)) { table.asEditor().edit(table.asEditor().flush()); } else if (args.propertyName.equals("Message")) { ////$NON-NLS-1$ message.setText(importModel.getMessage()); } } }); SingleSelectionModel<Object> selectionModel = (SingleSelectionModel<Object>) table.getSelectionModel(); selectionModel.addSelectionChangeHandler(new Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { if (!firstSelection) { importModel.setActiveDetailModel((HasEntity<?>) importModel.getDetailModels().get(0)); setGeneralViewSelection(((ImportEntityData) importModel.getSelectedItem()).getEntity()); firstSelection = true; } splitLayoutPanel.clear(); splitLayoutPanel.addSouth(subTabLayoutPanel, 230); ScrollPanel sp = new ScrollPanel(); sp.add(table); splitLayoutPanel.add(sp); table.getElement().getStyle().setPosition(Position.RELATIVE); } }); initSubTabLayoutPanel(); nicTable.asEditor().edit((SearchableListModel) importModel.getDetailModels().get(1)); diskTable.asEditor().edit((SearchableListModel) importModel.getDetailModels().get(2)); driver.edit(importModel); } private void addNetworkColumn() { customSelectionCellNetwork = new CustomSelectionCell(new ArrayList<String>()); customSelectionCellNetwork.setStyle(style.cellSelectBox()); Column<VmNetworkInterface, String> networkColumn = new Column<VmNetworkInterface, String>(customSelectionCellNetwork) { @Override public String getValue(VmNetworkInterface iface) { ImportNetworkData importNetworkData = importModel.getNetworkImportData(iface); List<String> networkNames = importNetworkData.getNetworkNames(); ((CustomSelectionCell) getCell()).setOptions(networkNames); if (networkNames.isEmpty()) { return ""; //$NON-NLS-1$ } String selectedNetworkName = importNetworkData.getSelectedNetworkName(); return selectedNetworkName != null ? selectedNetworkName : networkNames.get(0); } }; networkColumn.setFieldUpdater(new FieldUpdater<VmNetworkInterface, String>() { @Override public void update(int index, VmNetworkInterface iface, String value) { importModel.getNetworkImportData(iface).setSelectedNetworkName(value); nicTable.asEditor().edit(importModel.getImportNetworkInterfaceListModel()); } }); nicTable.addColumn(networkColumn, constants.networkNameInterface(), "150px"); //$NON-NLS-1$ } private void addNetworkProfileColumn() { customSelectionCellNetwork = new CustomSelectionCell(new ArrayList<String>()); customSelectionCellNetwork.setStyle(style.cellSelectBox()); Column<VmNetworkInterface, String> profileColumn = new Column<VmNetworkInterface, String>(customSelectionCellNetwork) { @Override public String getValue(VmNetworkInterface iface) { ImportNetworkData importNetworkData = importModel.getNetworkImportData(iface); List<String> networkProfileNames = new ArrayList<>(); for (VnicProfileView networkProfile : importNetworkData.getFilteredNetworkProfiles()) { networkProfileNames.add(networkProfile.getName()); } ((CustomSelectionCell) getCell()).setOptions(networkProfileNames); if (networkProfileNames.isEmpty()) { return ""; //$NON-NLS-1$ } VnicProfileView selectedNetworkProfile = importModel.getNetworkImportData(iface).getSelectedNetworkProfile(); return selectedNetworkProfile != null ? selectedNetworkProfile.getName() : networkProfileNames.get(0); } }; profileColumn.setFieldUpdater(new FieldUpdater<VmNetworkInterface, String>() { @Override public void update(int index, VmNetworkInterface iface, String value) { importModel.getNetworkImportData(iface).setSelectedNetworkProfile(value); } }); nicTable.addColumn(profileColumn, constants.profileNameInterface(), "150px"); //$NON-NLS-1$ } protected void setGeneralViewSelection(Object selectedItem) { generalView.setMainTabSelectedItem((VM) selectedItem); } private void initSubTabLayoutPanel() { if (subTabLayoutPanel == null) { subTabLayoutPanel = new TabLayoutPanel(CommonApplicationTemplates.TAB_BAR_HEIGHT, Unit.PX); subTabLayoutPanel.addSelectionHandler(new SelectionHandler<Integer>() { @Override public void onSelection(SelectionEvent<Integer> event) { subTabLayoutPanelSelectionChanged(event.getSelectedItem()); } }); initGeneralSubTabView(); ScrollPanel nicPanel = new ScrollPanel(); nicPanel.add(nicTable); subTabLayoutPanel.add(nicPanel, constants.importVmNetworkIntefacesSubTabLabel()); ScrollPanel diskPanel = new ScrollPanel(); diskPanel.add(diskTable); subTabLayoutPanel.add(diskPanel, constants.importVmDisksSubTabLabel()); } } protected void subTabLayoutPanelSelectionChanged(Integer selectedItem) { if (importModel != null) { importModel.setActiveDetailModel((HasEntity<?>) importModel.getDetailModels().get(selectedItem)); } } protected void initGeneralSubTabView() { ScrollPanel generalPanel = new ScrollPanel(); DetailModelProvider<ImportVmModel, VmImportGeneralModel> modelProvider = new DetailModelProvider<ImportVmModel, VmImportGeneralModel>() { @Override public VmImportGeneralModel getModel() { VmImportGeneralModel model = (VmImportGeneralModel) importModel.getDetailModels().get(0); model.setSource(ImportSource.VMWARE); return model; } @Override public void onSubTabSelected() { } @Override public void onSubTabDeselected() { } }; generalView = new ImportVmGeneralSubTabView(modelProvider); generalPanel.add(generalView); subTabLayoutPanel.add(generalPanel, constants.importVmGeneralSubTabLabel()); } @Override public ImportVmFromExternalProviderModel flush() { return driver.flush(); } private void initNicsTable() { nicTable = new ListModelObjectCellTable<>(); nicTable.enableColumnResizing(); AbstractTextColumn<VmNetworkInterface> nameColumn = new AbstractTextColumn<VmNetworkInterface>() { @Override public String getValue(VmNetworkInterface object) { return object.getName(); } }; nicTable.addColumn(nameColumn, constants.nameInterface(), "125px"); //$NON-NLS-1$ AbstractTextColumn<VmNetworkInterface> originalNetworkNameColumn = new AbstractTextColumn<VmNetworkInterface>() { @Override public String getValue(VmNetworkInterface object) { return object.getRemoteNetworkName(); } }; nicTable.addColumn(originalNetworkNameColumn, constants.originalNetworkNameInterface(), "160px"); //$NON-NLS-1$ addNetworkColumn(); addNetworkProfileColumn(); AbstractTextColumn<VmNetworkInterface> typeColumn = new AbstractEnumColumn<VmNetworkInterface, VmInterfaceType>() { @Override protected VmInterfaceType getRawValue(VmNetworkInterface object) { return VmInterfaceType.forValue(object.getType()); } }; nicTable.addColumn(typeColumn, constants.typeInterface(), "150px"); //$NON-NLS-1$ AbstractTextColumn<VmNetworkInterface> macColumn = new AbstractTextColumn<VmNetworkInterface>() { @Override public String getValue(VmNetworkInterface object) { return object.getMacAddress(); } }; nicTable.addColumn(macColumn, constants.macInterface(), "150px"); //$NON-NLS-1$ nicTable.getElement().getStyle().setPosition(Position.RELATIVE); nicTable.setSelectionModel(new NoSelectionModel<VmNetworkInterface>()); } private void initDiskTable() { diskTable = new ListModelObjectCellTable<>(); diskTable.enableColumnResizing(); AbstractTextColumn<DiskImage> aliasColumn = new AbstractTextColumn<DiskImage>() { @Override public String getValue(DiskImage object) { return object.getDiskAlias(); } }; diskTable.addColumn(aliasColumn, constants.aliasDisk(), "300px"); //$NON-NLS-1$ AbstractImageResourceColumn<DiskImage> bootableDiskColumn = new AbstractImageResourceColumn<DiskImage>() { @Override public ImageResource getValue(DiskImage object) { return object.isBoot() ? getDefaultImage() : null; } @Override public ImageResource getDefaultImage() { return resources.bootableDiskIcon(); } @Override public SafeHtml getTooltip(DiskImage object) { if (object.isBoot()) { return SafeHtmlUtils.fromSafeConstant(constants.bootableDisk()); } return null; } }; diskTable.addColumn(bootableDiskColumn, new ImageResourceHeader(DisksViewColumns.bootableDiskColumn.getDefaultImage(), SafeHtmlUtils.fromSafeConstant(constants.bootableDisk())), "30px"); //$NON-NLS-1$ AbstractDiskSizeColumn<DiskImage> sizeColumn = new AbstractDiskSizeColumn<DiskImage>() { @Override protected Long getRawValue(DiskImage object) { return object.getSize(); } }; diskTable.addColumn(sizeColumn, constants.provisionedSizeDisk(), "130px"); //$NON-NLS-1$ AbstractDiskSizeColumn<DiskImage> actualSizeColumn = new AbstractDiskSizeColumn<DiskImage>() { @Override protected Long getRawValue(DiskImage object) { return object.getActualSizeInBytes(); } }; diskTable.addColumn(actualSizeColumn, constants.sizeDisk(), "130px"); //$NON-NLS-1$ diskTable.setSelectionModel(new NoSelectionModel<DiskImage>()); diskTable.getElement().getStyle().setPosition(Position.RELATIVE); } interface WidgetStyle extends CssResource { String cellSelectBox(); String cdAttachedLabelWidth(); } }
package org.apereo.cas.token.authentication.principal; import org.apereo.cas.CasProtocolConstants; import org.apereo.cas.authentication.principal.Service; import org.apereo.cas.authentication.principal.WebApplicationService; import org.apereo.cas.authentication.principal.WebApplicationServiceResponseBuilder; import org.apereo.cas.services.RegisteredService; import org.apereo.cas.services.RegisteredServiceAccessStrategyUtils; import org.apereo.cas.services.RegisteredServiceProperty; import org.apereo.cas.services.ServicesManager; import org.apereo.cas.token.TokenTicketBuilder; import java.util.Map; /** * This is {@link TokenWebApplicationServiceResponseBuilder}. * * @author Misagh Moayyed * @since 5.1.0 */ public class TokenWebApplicationServiceResponseBuilder extends WebApplicationServiceResponseBuilder { private static final long serialVersionUID = -2863268279032438778L; private final TokenTicketBuilder tokenTicketBuilder; public TokenWebApplicationServiceResponseBuilder(final ServicesManager servicesManager, final TokenTicketBuilder tokenTicketBuilder) { super(servicesManager); this.tokenTicketBuilder = tokenTicketBuilder; } @Override protected WebApplicationService buildInternal(final WebApplicationService service, final Map<String, String> parameters) { final RegisteredService registeredService = this.servicesManager.findServiceBy(service); RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(service, registeredService); final boolean tokenAsResponse = RegisteredServiceProperty.RegisteredServiceProperties.TOKEN_AS_SERVICE_TICKET.isAssignedTo(registeredService); if (!tokenAsResponse) { return super.buildInternal(service, parameters); } final String jwt = generateToken(service, parameters); final TokenWebApplicationService jwtService = new TokenWebApplicationService(service.getId(), service.getOriginalUrl(), service.getArtifactId()); jwtService.setFormat(service.getFormat()); jwtService.setLoggedOutAlready(service.isLoggedOutAlready()); parameters.put(CasProtocolConstants.PARAMETER_TICKET, jwt); return jwtService; } /** * Generate token string. * * @param service the service * @param parameters the parameters * @return the jwt */ protected String generateToken(final Service service, final Map<String, String> parameters) { try { final String ticketId = parameters.get(CasProtocolConstants.PARAMETER_TICKET); return this.tokenTicketBuilder.build(ticketId, service); } catch (final Exception e) { throw new RuntimeException(e.getMessage(), e); } } }
// This source code is available under agreement available at // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France package org.talend.components.snowflake; import java.util.Properties; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.talend.components.snowflake.SnowflakeTestBase.MockRuntimeSourceOrSinkTestFixture; import org.talend.components.snowflake.tsnowflakeconnection.TSnowflakeConnectionDefinition; import org.talend.daikon.i18n.GlobalI18N; import org.talend.daikon.i18n.I18nMessages; import org.talend.daikon.properties.ValidationResult; import org.talend.daikon.properties.ValidationResult.Result; import org.talend.daikon.properties.presentation.Form; /** * Unit-tests for {@link SnowflakeConnectionProperties} class */ public class SnowflakeConnectionPropertiesTest { private static final Logger LOGGER = LoggerFactory.getLogger(SnowflakeConnectionPropertiesTest.class); private static final String NAME = "name"; private static final String ACCOUNT = "snowflakeAccount"; private static final String PASSWORD = "password"; private static final String WAREHOUSE = "warehouse"; private static final String DB = "db"; private static final String SCHEMA = "schema"; private static final String ROLE = "role"; private static final SnowflakeRegion AZURE_REGION = SnowflakeRegion.AZURE_EAST_US_2; private static final String TALEND_PRODUCT_VERSION = "0.0"; private static final String NO_PROXY = ".amazonaws.com"; private SnowflakeConnectionProperties snowflakeConnectionProperties; @Rule public ErrorCollector errorCollector = new ErrorCollector(); @Before public void setUp() throws Exception { snowflakeConnectionProperties = new SnowflakeConnectionProperties(NAME); snowflakeConnectionProperties.setupProperties(); snowflakeConnectionProperties.account.setValue(ACCOUNT); snowflakeConnectionProperties.userPassword.password.setValue(PASSWORD); snowflakeConnectionProperties.warehouse.setValue(WAREHOUSE); snowflakeConnectionProperties.db.setValue(DB); snowflakeConnectionProperties.schemaName.setValue(SCHEMA); snowflakeConnectionProperties.role.setValue(ROLE); snowflakeConnectionProperties.talendProductVersion = TALEND_PRODUCT_VERSION; } private void setUpAzureRegion() { snowflakeConnectionProperties.regionID.setValue(AZURE_REGION.getRegionID()); } private void setAdditionalJDBCParameters() { snowflakeConnectionProperties.jdbcParameters.setValue("no_proxy=.amazonaws.com"); } private void setAdditionalJDBCParametersToNull() { snowflakeConnectionProperties.jdbcParameters.setValue(null); } /** * Checks {@link SnowflakeConnectionProperties#getConnectionUrl()} returns {@link java.lang.String} snowflake url * when all params are valid */ @Test public void testGetConnectionUrlValidParams() throws Exception { StringBuilder builder = new StringBuilder(); String expectedUrl = builder.append("jdbc:snowflake://").append(ACCOUNT).append(".").append("snowflakecomputing.com/") .append("?").append("warehouse=").append(WAREHOUSE).append("&").append("db=").append(DB).append("&") .append("schema=").append(SCHEMA).append("&").append("role=").append(ROLE) .append("&").append("application=Talend-").append(TALEND_PRODUCT_VERSION) .toString(); String resultUrl = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url: " + resultUrl); Assert.assertEquals(expectedUrl, resultUrl); } /** * Checks {@link SnowflakeConnectionProperties#getConnectionUrl()} returns {@link java.lang.String} snowflake url * when all params are valid */ @Test public void testGetConnectionUrlValidParamsAzure() throws Exception { setUpAzureRegion(); StringBuilder builder = new StringBuilder(); String expectedUrl = builder.append("jdbc:snowflake://").append(ACCOUNT).append(".").append(AZURE_REGION.getRegionID()).append(".").append("snowflakecomputing.com/") .append("?").append("warehouse=").append(WAREHOUSE).append("&").append("db=").append(DB).append("&") .append("schema=").append(SCHEMA).append("&").append("role=").append(ROLE) .append("&").append("application=Talend-").append(TALEND_PRODUCT_VERSION) .toString(); String resultUrl = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url: " + resultUrl); Assert.assertEquals(expectedUrl, resultUrl); } /** * Checks {@link SnowflakeConnectionProperties#getConnectionUrl()} returns {@link java.lang.String} snowflake url * when additional parameters set */ @Test public void testGetConnectionUrlValidParamsAndAdditionalJDBCParams() throws Exception { setAdditionalJDBCParameters(); StringBuilder builder = new StringBuilder(); String expectedUrl = builder.append("jdbc:snowflake://").append(ACCOUNT).append(".").append("snowflakecomputing.com/") .append("?").append("warehouse=").append(WAREHOUSE).append("&").append("db=").append(DB).append("&") .append("schema=").append(SCHEMA).append("&").append("role=").append(ROLE) .append("&").append("application=Talend-").append(TALEND_PRODUCT_VERSION) .append("&").append("no_proxy=").append(NO_PROXY).toString(); String resultUrl = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url: " + resultUrl); Assert.assertEquals(expectedUrl, resultUrl); } /** * Checks {@link SnowflakeConnectionProperties#getConnectionUrl()} returns {@link java.lang.String} snowflake url * when additional parameters set to null */ @Test public void testGetConnectionUrlWhenAdditionalJDBCParamsIsNull() throws Exception { setAdditionalJDBCParametersToNull(); StringBuilder builder = new StringBuilder(); String expectedUrl = builder.append("jdbc:snowflake://").append(ACCOUNT).append(".").append("snowflakecomputing.com/") .append("?").append("warehouse=").append(WAREHOUSE).append("&").append("db=").append(DB).append("&") .append("schema=").append(SCHEMA).append("&").append("role=").append(ROLE) .append("&").append("application=Talend-").append(TALEND_PRODUCT_VERSION) .toString(); String resultUrl = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url: " + resultUrl); Assert.assertEquals(expectedUrl, resultUrl); } /** * Checks {@link SnowflakeConnectionProperties#getConnectionUrl()} returns {@link java.lang.String} snowflake url * when warehouse parameter is null or empty */ @Test public void testGetConnectionUrlNullOrEmptyWarehouse() throws Exception { StringBuilder builder = new StringBuilder(); String expectedUrl = builder.append("jdbc:snowflake://").append(ACCOUNT).append(".").append("snowflakecomputing.com/") .append("?").append("db=").append(DB).append("&").append("schema=").append(SCHEMA).append("&").append("role=") .append(ROLE).append("&").append("application=Talend-").append(TALEND_PRODUCT_VERSION).toString(); snowflakeConnectionProperties.warehouse.setValue(null); String resultUrlNullWarehouse = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url warehouse is null: " + resultUrlNullWarehouse); Assert.assertEquals(expectedUrl, resultUrlNullWarehouse); snowflakeConnectionProperties.warehouse.setValue(""); String resultUrlEmptyWarehouse = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url warehouse is empty: " + resultUrlEmptyWarehouse); Assert.assertEquals(expectedUrl, resultUrlEmptyWarehouse); } /** * Checks {@link SnowflakeConnectionProperties#getConnectionUrl()} returns {@link java.lang.String} snowflake url * when db parameter is null or empty */ @Test public void testGetConnectionUrlNullOrEmptyDb() throws Exception { StringBuilder builder = new StringBuilder(); String expectedUrl = builder.append("jdbc:snowflake://").append(ACCOUNT).append(".").append("snowflakecomputing.com/") .append("?").append("warehouse=").append(WAREHOUSE).append("&").append("schema=").append(SCHEMA).append("&") .append("role=").append(ROLE).append("&").append("application=Talend-").append(TALEND_PRODUCT_VERSION).toString(); snowflakeConnectionProperties.db.setValue(null); String resultUrlNullDb = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url db is null: " + resultUrlNullDb); Assert.assertEquals(expectedUrl, resultUrlNullDb); snowflakeConnectionProperties.db.setValue(""); String resultUrlEmptyDb = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url db is empty: " + resultUrlEmptyDb); Assert.assertEquals(expectedUrl, resultUrlEmptyDb); } /** * Checks {@link SnowflakeConnectionProperties#getConnectionUrl()} returns {@link java.lang.String} snowflake url * when schema parameter is null or empty */ @Test public void testGetConnectionUrlNullOrEmptySchema() throws Exception { StringBuilder builder = new StringBuilder(); String expectedUrl = builder.append("jdbc:snowflake://").append(ACCOUNT).append(".").append("snowflakecomputing.com/") .append("?").append("warehouse=").append(WAREHOUSE).append("&").append("db=").append(DB).append("&") .append("role=").append(ROLE).append("&").append("application=Talend-").append(TALEND_PRODUCT_VERSION).toString(); snowflakeConnectionProperties.schemaName.setValue(null); String resultUrlNullSchema = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url schema is null: " + resultUrlNullSchema); Assert.assertEquals(expectedUrl, resultUrlNullSchema); snowflakeConnectionProperties.schemaName.setValue(""); String resultUrlEmptySchema = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url schema is empty: " + resultUrlEmptySchema); Assert.assertEquals(expectedUrl, resultUrlEmptySchema); } /** * Checks {@link SnowflakeConnectionProperties#getConnectionUrl()} returns {@link java.lang.String} snowflake url * when role parameter is null or empty */ @Test public void testGetConnectionUrlNullOrEmptyRole() throws Exception { StringBuilder builder = new StringBuilder(); String expectedUrl = builder.append("jdbc:snowflake://").append(ACCOUNT).append(".").append("snowflakecomputing.com/") .append("?").append("warehouse=").append(WAREHOUSE).append("&").append("db=").append(DB).append("&") .append("schema=").append(SCHEMA).append("&").append("application=Talend-").append(TALEND_PRODUCT_VERSION).toString(); snowflakeConnectionProperties.role.setValue(null); String resultUrlNullSchema = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url schema is null: " + resultUrlNullSchema); Assert.assertEquals(expectedUrl, resultUrlNullSchema); snowflakeConnectionProperties.role.setValue(""); String resultUrlEmptySchema = snowflakeConnectionProperties.getConnectionUrl(); LOGGER.debug("result url schema is empty: " + resultUrlEmptySchema); Assert.assertEquals(expectedUrl, resultUrlEmptySchema); } @Test(expected = IllegalArgumentException.class) public void testGetConnectionUrlNullAccount() throws Exception { snowflakeConnectionProperties.account.setValue(null); snowflakeConnectionProperties.getConnectionUrl(); } @Test(expected = IllegalArgumentException.class) public void testGetConnectionUrlEmptyStringAccount() throws Exception { snowflakeConnectionProperties.account.setValue(""); snowflakeConnectionProperties.getConnectionUrl(); } @Test public void testI18NMessage() { I18nMessages i18nMessages = GlobalI18N.getI18nMessageProvider().getI18nMessages(SnowflakeConnectionProperties.class); String connectionSuccessMessage = i18nMessages.getMessage("messages.connectionSuccessful"); Assert.assertFalse(connectionSuccessMessage.equals("messages.connectionSuccessful")); } @Test public void testValidateTestConnection() throws Exception { snowflakeConnectionProperties.userPassword.setupLayout(); snowflakeConnectionProperties.setupLayout(); try (MockRuntimeSourceOrSinkTestFixture testFixture = new MockRuntimeSourceOrSinkTestFixture()) { testFixture.setUp(); Mockito.when(testFixture.runtimeSourceOrSink.validateConnection(snowflakeConnectionProperties)).thenReturn(ValidationResult.OK); ValidationResult vr = snowflakeConnectionProperties.validateTestConnection(); Assert.assertEquals(ValidationResult.Result.OK, vr.getStatus()); Assert.assertTrue(snowflakeConnectionProperties.getForm(SnowflakeConnectionProperties.FORM_WIZARD).isAllowForward()); } } @Test public void testValidateTestConnectionFailed() throws Exception { snowflakeConnectionProperties.userPassword.setupLayout(); snowflakeConnectionProperties.setupLayout(); try (MockRuntimeSourceOrSinkTestFixture testFixture = new MockRuntimeSourceOrSinkTestFixture()) { testFixture.setUp(); Mockito.when(testFixture.runtimeSourceOrSink.validateConnection(snowflakeConnectionProperties)) .thenReturn(new ValidationResult(Result.ERROR)); ValidationResult vr = snowflakeConnectionProperties.validateTestConnection(); Assert.assertEquals(ValidationResult.Result.ERROR, vr.getStatus()); Assert.assertFalse(snowflakeConnectionProperties.getForm(SnowflakeConnectionProperties.FORM_WIZARD).isAllowForward()); } } @Test public void testGetReferencedConnectionProperties() { snowflakeConnectionProperties.referencedComponent.setReference(new SnowflakeConnectionProperties("referenced")); Assert.assertNotNull(snowflakeConnectionProperties.getReferencedConnectionProperties()); } @Test public void testGetJdbcProperties() throws Exception { snowflakeConnectionProperties.userPassword.userId.setValue("talendTest"); Properties properties = snowflakeConnectionProperties.getJdbcProperties(); Assert.assertEquals(snowflakeConnectionProperties.userPassword.userId.getValue(), properties.getProperty("user")); Assert.assertEquals(snowflakeConnectionProperties.userPassword.password.getValue(), properties.getProperty("password")); Assert.assertEquals(String.valueOf(snowflakeConnectionProperties.loginTimeout.getValue()), properties.getProperty("loginTimeout")); } @Test public void testAfterReferencedComponent() { snowflakeConnectionProperties.userPassword.setupLayout(); snowflakeConnectionProperties.setupLayout(); snowflakeConnectionProperties.referencedComponent.componentInstanceId .setValue(TSnowflakeConnectionDefinition.COMPONENT_NAME); snowflakeConnectionProperties.afterReferencedComponent(); Assert.assertTrue(snowflakeConnectionProperties.getForm(Form.MAIN) .getWidget(snowflakeConnectionProperties.userPassword.getName()).isHidden()); Assert.assertTrue( snowflakeConnectionProperties.getForm(Form.ADVANCED).getWidget(snowflakeConnectionProperties.role).isHidden()); } @Test public void testPostDeserialize() { //Missing value from 0 version. snowflakeConnectionProperties.loginTimeout.setValue(null); snowflakeConnectionProperties.postDeserialize(0, null, false); Assert.assertEquals(SnowflakeConnectionProperties.DEFAULT_LOGIN_TIMEOUT, snowflakeConnectionProperties.loginTimeout.getValue().intValue()); snowflakeConnectionProperties.loginTimeout.setValue(0); //In 1 version value exists, no need to change it to default. snowflakeConnectionProperties.postDeserialize(1, null, false); Assert.assertEquals(0, snowflakeConnectionProperties.loginTimeout.getValue().intValue()); } @Test public void testMigrationRegion() { //Missing value from 0 version. snowflakeConnectionProperties.region.setValue(SnowflakeRegion.AWS_AP_SOUTHEAST_2); snowflakeConnectionProperties.customRegionID.setValue("ap-southeast-2"); snowflakeConnectionProperties.postDeserialize(0, null, false); Assert.assertEquals("\"ap-southeast-2\"", snowflakeConnectionProperties.regionID.getStringValue()); snowflakeConnectionProperties.useCustomRegion.setValue(true); snowflakeConnectionProperties.postDeserialize(1, null, false); Assert.assertEquals("ap-southeast-2", snowflakeConnectionProperties.regionID.getValue()); snowflakeConnectionProperties.customRegionID.setStoredValue("context.regionID"); snowflakeConnectionProperties.postDeserialize(1, null, false); Assert.assertEquals("context.regionID", snowflakeConnectionProperties.regionID.getValue()); } }
package view; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.FloatBuffer; import java.util.List; import javax.imageio.ImageIO; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.GLException; import com.jogamp.opengl.glu.GLU; import com.jogamp.opengl.math.VectorUtil; import com.jogamp.opengl.util.awt.AWTGLReadBufferUtil; import com.jogamp.opengl.util.gl2.GLUT; import com.jogamp.opengl.util.texture.Texture; import com.jogamp.opengl.util.texture.TextureCoords; import com.jogamp.opengl.util.texture.TextureIO; import hochberger.utilities.application.ResourceLoader; import hochberger.utilities.threading.ThreadRunner; import hochberger.utilities.timing.Sleeper; import hochberger.utilities.timing.ToMilis; import model.Boulder; import model.Position; import model.SurfaceMap; public class OpticalSensorTerrainVisualization extends TerrainVisualization { private static final int WAIT_CYCLES = 5; private final GLU glu; private SurfaceMap points; private boolean takeScreenshotWithNextRender; private String screenshotFilePath; private int width; private int height; private Position position; private Position viewTargetPosition; private String nextScreenshotFilePath; private int waitCycles; private Texture texture; private int screenshotCounter; private float[][][] vertexNormals; public OpticalSensorTerrainVisualization(final int width, final int height) { super(); this.width = width; this.height = height; this.glu = new GLU(); this.points = new SurfaceMap(0); this.takeScreenshotWithNextRender = false; this.position = new Position(250, 1000, 250); this.viewTargetPosition = new Position(0, 0, 0); this.screenshotFilePath = System.getProperty("user.home"); this.waitCycles = WAIT_CYCLES; this.screenshotCounter = 0; this.vertexNormals = new float[0][0][0]; } @Override public void init(final GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glShadeModel(GL2.GL_SMOOTH); gl.glClearColor(0f, 0f, 0f, 0f); gl.glClearDepth(1.0f); gl.glEnable(GL2.GL_DEPTH_TEST); gl.glDepthFunc(GL2.GL_LEQUAL); gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST); gl.glEnable(GL2.GL_NORMALIZE); gl.glEnable(GL2.GL_CULL_FACE); final float h = (float) this.width / (float) this.height; gl.glViewport(0, 0, this.width, this.height); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); this.glu.gluPerspective(60.0, h, 0.1, 10000.0); gl.glMatrixMode(GL2.GL_MODELVIEW); try { this.texture = TextureIO.newTexture(ResourceLoader.loadStream("snow_2_512.jpg"), true, "jpg"); } catch (GLException | IOException e) { e.printStackTrace(); } this.texture.enable(gl); this.texture.bind(gl); } @Override public void display(final GLAutoDrawable drawable) { update(); render(drawable); } private void update() { // TODO Auto-generated method stub } private void render(final GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glClearDepth(1d); gl.glClearColor(0f, 0f, 0f, 0f); gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT); gl.glLoadIdentity(); gl.glPushMatrix(); lighting(gl); this.glu.gluLookAt(this.position.getX(), this.position.getY(), this.position.getZ(), this.viewTargetPosition.getX(), this.viewTargetPosition.getY(), this.viewTargetPosition.getZ(), 0, 0, -1); drawTerrain(gl); takeScreenShot(drawable); gl.glFlush(); gl.glPopMatrix(); } private void takeScreenShot(final GLAutoDrawable drawable) { if (!this.takeScreenshotWithNextRender) { return; } if (0 < --this.waitCycles) { return; } this.waitCycles = WAIT_CYCLES; this.takeScreenshotWithNextRender = false; final AWTGLReadBufferUtil util = new AWTGLReadBufferUtil(drawable.getGLProfile(), false); final BufferedImage image = util.readPixelsToBufferedImage(drawable.getGL(), true); final File outputfile = new File(this.nextScreenshotFilePath); ThreadRunner.startThread(new Runnable() { @Override public void run() { try { ImageIO.write(image, "png", outputfile); } catch (final IOException e) { e.printStackTrace(); } } }); } private void drawTerrain(final GL2 gl) { gl.glPushMatrix(); final float[] matShininess = { 50.0f }; gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_SHININESS, FloatBuffer.wrap(matShininess)); final float[] matAmbient = { 0.1f, 0.1f, 0.1f, 0.0f }; gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_AMBIENT, FloatBuffer.wrap(matAmbient)); final float[] matDiffuse = { 0.7f, 0.7f, 0.7f, 1.0f }; gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_DIFFUSE, FloatBuffer.wrap(matDiffuse)); final float[] matSpecular = { 1.0f, 1.0f, 1.0f, 1.0f }; gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_SPECULAR, FloatBuffer.wrap(matSpecular)); drawSurface(gl); gl.glPopMatrix(); } @Override protected void drawSurface(final GL2 gl) { gl.glBegin(GL2.GL_TRIANGLES); final TextureCoords coords = this.texture.getImageTexCoords(); for (int z = 0; z < this.points.getZDimension() - 1; z++) { for (int x = 0; x < this.points.getXDimension() - 1; x++) { gl.glTexCoord2d(coords.bottom(), coords.left()); gl.glNormal3f(this.vertexNormals[x][z][0], this.vertexNormals[x][z][1], this.vertexNormals[x][z][2]); gl.glVertex3d(this.scalingFactor * x, this.points.get(x, z), this.scalingFactor * z); gl.glTexCoord2d(coords.bottom(), coords.right()); gl.glNormal3f(this.vertexNormals[x + 1][z + 1][0], this.vertexNormals[x + 1][z + 1][1], this.vertexNormals[x + 1][z + 1][2]); gl.glVertex3d(this.scalingFactor * (x + 1), this.points.get(x + 1, z + 1), this.scalingFactor * (z + 1)); gl.glTexCoord2d(coords.top(), coords.right()); gl.glNormal3f(this.vertexNormals[x + 1][z][0], this.vertexNormals[x + 1][z][1], this.vertexNormals[x + 1][z][2]); gl.glVertex3d(this.scalingFactor * (x + 1), this.points.get(x + 1, z), this.scalingFactor * z); gl.glTexCoord2d(coords.bottom(), coords.left()); gl.glNormal3f(this.vertexNormals[x][z][0], this.vertexNormals[x][z][1], this.vertexNormals[x][z][2]); gl.glVertex3d(this.scalingFactor * x, this.points.get(x, z), this.scalingFactor * z); gl.glTexCoord2d(coords.bottom(), coords.right()); gl.glNormal3f(this.vertexNormals[x][z + 1][0], this.vertexNormals[x][z + 1][1], this.vertexNormals[x][z + 1][2]); gl.glVertex3d(this.scalingFactor * x, this.points.get(x, z + 1), this.scalingFactor * (z + 1)); gl.glTexCoord2d(coords.top(), coords.right()); gl.glNormal3f(this.vertexNormals[x + 1][z + 1][0], this.vertexNormals[x + 1][z + 1][1], this.vertexNormals[x + 1][z + 1][2]); gl.glVertex3d(this.scalingFactor * (x + 1), this.points.get(x + 1, z + 1), this.scalingFactor * (z + 1)); } } gl.glEnd(); final GLUT glut = new GLUT(); final List<Boulder> boulders = this.points.getBoulders(); for (final Boulder boulder : boulders) { gl.glPushMatrix(); gl.glTranslated(boulder.getX(), boulder.getY(), boulder.getZ()); glut.glutSolidSphere(boulder.getRadius(), 5, 5); gl.glPopMatrix(); } } @Override public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, int height) { this.width = width; this.height = height; final GL2 gl = drawable.getGL().getGL2(); if (height <= 0) { height = 1; } final float h = (float) width / (float) height; gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); this.glu.gluPerspective(45.0f, h, 1.0, 10000.0); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); } private void lighting(final GL2 gl) { gl.glShadeModel(GL2.GL_SMOOTH); final float[] ambientLight = { 0.4f, 0.4f, 0.4f, 0f }; gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_AMBIENT, ambientLight, 0); final float[] diffuseLight = { 0.7f, 0.7f, 0.7f, 0f }; gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_DIFFUSE, diffuseLight, 0); final float[] specularLight = { 0.3f, 0.3f, 0.3f, 0f }; gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_SPECULAR, specularLight, 0); final float[] lightPosition = { 10000.0f, 10000.0f, 10000.0f, 0f }; gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, FloatBuffer.wrap(lightPosition)); gl.glEnable(GL2.GL_LIGHTING); gl.glEnable(GL2.GL_LIGHT0); } private void calculateNormals(final SurfaceMap points) { final float[][][] areaNormals = new float[points.getXDimension()][points.getZDimension()][3]; for (int z = 0; z < points.getZDimension() - 1; z++) { for (int x = 0; x < points.getXDimension() - 1; x++) { final float[] one = { 0, (float) (points.get(x, z + 1) - points.get(x, z)), 1 }; final float[] two = { 1, (float) (points.get(x + 1, z) - points.get(x, z)), 0 }; areaNormals[x][z] = VectorUtil.crossVec3(areaNormals[x][z], one, two); } } this.vertexNormals = new float[points.getXDimension()][points.getZDimension()][3]; for (int z = 1; z < points.getZDimension(); z++) { for (int x = 1; x < points.getXDimension(); x++) { for (int i = 0; i < 3; i++) { this.vertexNormals[x][z][i] = (areaNormals[x][z][i] + areaNormals[x - 1][z][i] + areaNormals[x][z - 1][i] + areaNormals[x - 1][z - 1][i]) / 4f; } this.vertexNormals[x][z] = VectorUtil.normalizeVec3(this.vertexNormals[x][z]); } } } @Override public void setPoints(final SurfaceMap points) { this.points = new SurfaceMap(0); calculateNormals(points); Sleeper.sleep(ToMilis.seconds(1.0)); this.points = points; this.position = new Position(points.getXDimension() / 2d, 1.5 * points.getXDimension(), points.getZDimension() / 2d); this.viewTargetPosition = new Position(points.getXDimension() / 2d, 0, points.getZDimension() / 2d); } public String prepareScreenshot() { this.takeScreenshotWithNextRender = true; this.nextScreenshotFilePath = this.screenshotFilePath + "/terrain_" + System.currentTimeMillis() + "_" + (++this.screenshotCounter) + ".png"; return this.nextScreenshotFilePath; } public void setScreenshotStorageFolder(final String filepath) { this.screenshotFilePath = filepath; } public void setOpticalSensor(final Position position, final Position viewTargetPosition) { this.position = position; this.viewTargetPosition = viewTargetPosition; } }
package btools.mapcreator; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.HashMap; import btools.util.CompactLongSet; import btools.util.DiffCoderDataOutputStream; import btools.util.FrozenLongSet; /** * PosUnifier does 3 steps in map-processing: * * - unify positions - add srtm elevation data - make a bordernodes file * containing net data from the bordernids-file just containing ids * * @author ab */ public class PosUnifier extends MapCreatorBase { private DiffCoderDataOutputStream nodesOutStream; private DiffCoderDataOutputStream borderNodesOut; private File nodeTilesOut; private CompactLongSet[] positionSets; private HashMap<String, SrtmRaster> srtmmap; private int lastSrtmLonIdx; private int lastSrtmLatIdx; private SrtmRaster lastSrtmRaster; private String srtmdir; private CompactLongSet borderNids; public static void main( String[] args ) throws Exception { System.out.println( "*** PosUnifier: Unify position values and enhance elevation" ); if ( args.length != 5 ) { System.out.println( "usage: java PosUnifier <node-tiles-in> <node-tiles-out> <bordernids-in> <bordernodes-out> <srtm-data-dir>" ); return; } new PosUnifier().process( new File( args[0] ), new File( args[1] ), new File( args[2] ), new File( args[3] ), args[4] ); } public void process( File nodeTilesIn, File nodeTilesOut, File bordernidsinfile, File bordernodesoutfile, String srtmdir ) throws Exception { this.nodeTilesOut = nodeTilesOut; this.srtmdir = srtmdir; // read border nids set DataInputStream dis = createInStream( bordernidsinfile ); borderNids = new CompactLongSet(); try { for ( ;; ) { long nid = readId( dis ); if ( !borderNids.contains( nid ) ) borderNids.fastAdd( nid ); } } catch (EOFException eof) { dis.close(); } borderNids = new FrozenLongSet( borderNids ); // process all files borderNodesOut = createOutStream( bordernodesoutfile ); new NodeIterator( this, true ).processDir( nodeTilesIn, ".n5d" ); borderNodesOut.close(); } @Override public void nodeFileStart( File nodefile ) throws Exception { resetSrtm(); nodesOutStream = createOutStream( fileFromTemplate( nodefile, nodeTilesOut, "u5d" ) ); positionSets = new CompactLongSet[2500]; } @Override public void nextNode( NodeData n ) throws Exception { SrtmRaster srtm = srtmForNode( n.ilon, n.ilat ); n.selev = srtm == null ? Short.MIN_VALUE : srtm.getElevation( n.ilon, n.ilat ); findUniquePos( n ); n.writeTo( nodesOutStream ); if ( borderNids.contains( n.nid ) ) { n.writeTo( borderNodesOut ); } } @Override public void nodeFileEnd( File nodeFile ) throws Exception { nodesOutStream.close(); } private boolean checkAdd( int lon, int lat ) { int slot = ((lon%5000000)/100000)*50 + ((lat%5000000)/100000); long id = ( (long) lon ) << 32 | lat; CompactLongSet set = positionSets[slot]; if ( set == null ) { positionSets[slot] = set = new CompactLongSet(); } if ( !set.contains( id ) ) { set.fastAdd( id ); return true; } return false; } private void findUniquePos( NodeData n ) { if ( !checkAdd( n.ilon, n.ilat ) ) { _findUniquePos( n ); } } private void _findUniquePos( NodeData n ) { // fix the position for uniqueness int lonmod = n.ilon % 1000000; int londelta = lonmod < 500000 ? 1 : -1; int latmod = n.ilat % 1000000; int latdelta = latmod < 500000 ? 1 : -1; for ( int latsteps = 0; latsteps < 100; latsteps++ ) { for ( int lonsteps = 0; lonsteps <= latsteps; lonsteps++ ) { int lon = n.ilon + lonsteps * londelta; int lat = n.ilat + latsteps * latdelta; if ( checkAdd( lon, lat ) ) { n.ilon = lon; n.ilat = lat; return; } } } System.out.println( "*** WARNING: cannot unify position for: " + n.ilon + " " + n.ilat ); } /** * get the srtm data set for a position srtm coords are * srtm_<srtmLon>_<srtmLat> where srtmLon = 180 + lon, srtmLat = 60 - lat */ private SrtmRaster srtmForNode( int ilon, int ilat ) throws Exception { int srtmLonIdx = ( ilon + 5000000 ) / 5000000; int srtmLatIdx = ( 654999999 - ilat ) / 5000000 - 100; // ugly negative rounding... if ( srtmLonIdx == lastSrtmLonIdx && srtmLatIdx == lastSrtmLatIdx ) { return lastSrtmRaster; } lastSrtmLonIdx = srtmLonIdx; lastSrtmLatIdx = srtmLatIdx; String slonidx = "0" + srtmLonIdx; String slatidx = "0" + srtmLatIdx; String filename = "srtm_" + slonidx.substring( slonidx.length()-2 ) + "_" + slatidx.substring( slatidx.length()-2 ); lastSrtmRaster = srtmmap.get( filename ); if ( lastSrtmRaster == null && !srtmmap.containsKey( filename ) ) { File f = new File( new File( srtmdir ), filename + ".bef" ); System.out.println( "checking: " + f + " ilon=" + ilon + " ilat=" + ilat ); if ( f.exists() ) { System.out.println( "*** reading: " + f ); try { InputStream isc = new BufferedInputStream( new FileInputStream( f ) ); lastSrtmRaster = new RasterCoder().decodeRaster( isc ); isc.close(); } catch (Exception e) { System.out.println( "**** ERROR reading " + f + " ****" ); } srtmmap.put( filename, lastSrtmRaster ); return lastSrtmRaster; } f = new File( new File( srtmdir ), filename + ".zip" ); System.out.println( "reading: " + f + " ilon=" + ilon + " ilat=" + ilat ); if ( f.exists() ) { try { lastSrtmRaster = new SrtmData( f ).getRaster(); } catch (Exception e) { System.out.println( "**** ERROR reading " + f + " ****" ); } } srtmmap.put( filename, lastSrtmRaster ); } return lastSrtmRaster; } private void resetSrtm() { srtmmap = new HashMap<String, SrtmRaster>(); lastSrtmLonIdx = -1; lastSrtmLatIdx = -1; lastSrtmRaster = null; } }
package org.sirix.io.file; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.file.Files; import java.nio.file.Path; import org.sirix.access.conf.ResourceConfiguration; import org.sirix.exception.SirixIOException; import org.sirix.io.Reader; import org.sirix.io.Storage; import org.sirix.io.Writer; import org.sirix.io.bytepipe.ByteHandlePipeline; import org.sirix.io.bytepipe.ByteHandler; import org.sirix.page.SerializationType; /** * Factory to provide File access as a backend. * * @author Sebastian Graf, University of Konstanz. * */ public final class FileStorage implements Storage { /** File name. */ private static final String FILENAME = "sirix.data"; /** Instance to storage. */ private final File mFile; /** Byte handler pipeline. */ private final ByteHandlePipeline mByteHandler; /** * Constructor. * * @param file the location of the database * @param byteHandler byte handler pipeline */ public FileStorage(final ResourceConfiguration resourceConfig) { assert resourceConfig != null : "resourceConfig must not be null!"; mFile = resourceConfig.mPath; mByteHandler = resourceConfig.mByteHandler; } @Override public Reader createReader() throws SirixIOException { try { final Path concreteStorage = createDirectoriesAndFile(); return new FileReader(new RandomAccessFile(concreteStorage.toFile(), "r"), new ByteHandlePipeline(mByteHandler), SerializationType.COMMIT); } catch (final IOException e) { throw new SirixIOException(e); } } private Path createDirectoriesAndFile() throws IOException { final Path concreteStorage = getConcreteStorage(); if (!Files.exists(concreteStorage)) { Files.createDirectories(concreteStorage.getParent()); Files.createFile(concreteStorage); } return concreteStorage; } @Override public Writer createWriter() throws SirixIOException { try { final Path concreteStorage = createDirectoriesAndFile(); return new FileWriter(new RandomAccessFile(concreteStorage.toFile(), "rw"), new ByteHandlePipeline(mByteHandler), SerializationType.COMMIT); } catch (final IOException e) { throw new SirixIOException(e); } } @Override public void close() { // not used over here } /** * Getting concrete storage for this file. * * @return the concrete storage for this database */ private Path getConcreteStorage() { return new File(mFile, new StringBuilder(ResourceConfiguration.Paths.DATA.getFile().getName()) .append(File.separator).append(FILENAME).toString()).toPath(); } @Override public boolean exists() throws SirixIOException { final Path storage = getConcreteStorage(); try { return Files.exists(storage) && Files.size(storage) > 0; } catch (final IOException e) { throw new SirixIOException(e); } } @Override public ByteHandler getByteHandler() { return mByteHandler; } }
package ch.rgw.tools; import static ch.rgw.tools.JdbcLink.DBFLAVOR_H2; import static ch.rgw.tools.JdbcLink.DBFLAVOR_MYSQL; import static ch.rgw.tools.JdbcLink.DBFLAVOR_POSTGRESQL; import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Natively handles SQL Exceptions if possible. E.g. if we try to update a database sometimes a * "column already available" exception might occur constantly preventing us from finishing the * update - although not necessary. This class provides advise to the question whether an exception * is really necessary to be thrown. */ public class DatabaseNativeExceptionHandler { private static Logger log = LoggerFactory.getLogger(DatabaseNativeExceptionHandler.class); /** * Try to handle the thrown Exception considering the native Database implementation * * @param dBFlavor * @param e * @return <code>true</code> if we can not mitigate the problem and an exception should be * thrown, else <code>false</code> */ public static boolean handleException(String dBFlavor, SQLException e){ switch (dBFlavor) { case DBFLAVOR_MYSQL: return handleMysqlException(e); case DBFLAVOR_POSTGRESQL: return handlePostgresException(e); case DBFLAVOR_H2: return handleH2Exception(e); default: log.error("Unknown database flavor: " + dBFlavor); break; } return true; } private static boolean handleH2Exception(SQLException e){ return true; } public static final String MYSQL_ERRORCODE_TABLE_EXISTS = "42S01"; public static final String MYSQL_ERRORCODE_DUPLICATE_COLUMN = "42S21"; public static final String MYSQL_ERRORCODE_DUPLICATE_KEY_NAME = "42000"; private static boolean handleMysqlException(SQLException e){ String sqlState = e.getSQLState(); switch (sqlState) { case MYSQL_ERRORCODE_TABLE_EXISTS: log.info("Found table exists, mitigating error code " + sqlState + ": " + e.getMessage()); return false; case MYSQL_ERRORCODE_DUPLICATE_COLUMN: log.info("Found duplicate column, mitigating error code " + sqlState + ": " + e.getMessage()); return false; case MYSQL_ERRORCODE_DUPLICATE_KEY_NAME: log.info("Found duplicate key name, mitigating error code " + sqlState + ": " + e.getMessage()); return false; default: } return true; } public static final String POSTGRES_ERRORCODE_DUPLICATE_COLUMN = "42701"; public static final String POSTGRES_ERRORCODE_DUPLICATE_TABLE = "42P07"; private static boolean handlePostgresException(SQLException e){ String sqlState = e.getSQLState(); switch (sqlState) { case POSTGRES_ERRORCODE_DUPLICATE_TABLE: case POSTGRES_ERRORCODE_DUPLICATE_COLUMN: log.info("Found duplicate element, mitigating error code " + sqlState + ": " + e.getMessage()); return false; default: } return true; } }
package de.fu_berlin.imp.seqan.usability_analyzer.groundedtheory.viewer; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.StyledString; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.PlatformUI; import com.bkahlert.nebula.utils.DistributionUtils.AbsoluteWidth; import com.bkahlert.nebula.utils.DistributionUtils.RelativeWidth; import com.bkahlert.nebula.utils.Stylers; import com.bkahlert.nebula.utils.ViewerUtils; import com.bkahlert.nebula.viewer.SortableTreeViewer; import de.fu_berlin.imp.seqan.usability_analyzer.core.model.ILocatable; import de.fu_berlin.imp.seqan.usability_analyzer.core.model.URI; import de.fu_berlin.imp.seqan.usability_analyzer.core.services.ILabelProviderService; import de.fu_berlin.imp.seqan.usability_analyzer.groundedtheory.model.ICode; import de.fu_berlin.imp.seqan.usability_analyzer.groundedtheory.services.ICodeService; import de.fu_berlin.imp.seqan.usability_analyzer.groundedtheory.ui.Utils; import de.fu_berlin.imp.seqan.usability_analyzer.groundedtheory.viewer.ViewerURI.State; public class CodeInstanceViewer extends Composite implements ISelectionProvider { @SuppressWarnings("unused") private static final Logger LOGGER = Logger .getLogger(CodeInstanceViewer.class); private final ILabelProviderService labelProviderService = (ILabelProviderService) PlatformUI .getWorkbench().getService(ILabelProviderService.class); private final SortableTreeViewer treeViewer; public CodeInstanceViewer(Composite parent, int style) { super(parent, style); this.setLayout(new FillLayout()); Tree tree = new Tree(this, SWT.BORDER | SWT.MULTI); tree.setHeaderVisible(true); tree.setLinesVisible(false); Utils.addCodeColorRenderSupport(tree, 1); this.treeViewer = new SortableTreeViewer(tree); this.treeViewer.setAutoExpandLevel(TreeViewer.ALL_LEVELS); this.createColumns(); this.treeViewer .setContentProvider(new CodeInstanceViewerContentProvider()); } private void createColumns() { this.treeViewer.createColumn("ID", new RelativeWidth(1.0, 150)) .setLabelProvider( new ILabelProviderService.StyledLabelProvider() { @Override public StyledString getStyledText(URI uri) throws Exception { if (uri == ViewerURI.NO_CODES_URI) { return new StyledString("no codes", Stylers.MINOR_STYLER); } StyledString text = new StyledString( CodeInstanceViewer.this.labelProviderService .getLabelProvider(uri).getText( uri), Stylers.DEFAULT_STYLER); if (uri instanceof ViewerURI && ((ViewerURI) uri).getState() == State.PARENT) { text.append(" parent", Stylers.MINOR_STYLER); } return text; } @Override public Image getImage(URI uri) throws Exception { if (uri == ViewerURI.NO_CODES_URI) { return null; } return CodeInstanceViewer.this.labelProviderService .getLabelProvider(uri).getImage(uri); } @Override public String getToolTipText(URI uri) throws Exception { if (uri == ViewerURI.NO_CODES_URI) { return null; } return uri.toString(); } }); this.treeViewer.createColumn("", new AbsoluteWidth(16)) .setLabelProvider( new ILabelProviderService.ColumnLabelProvider() { @Override public String getText(Object element) { return ""; } }); Utils.createNumPhaenomenonsColumn( this.treeViewer, (ICodeService) PlatformUI.getWorkbench().getService( ICodeService.class)); } @Override public void addSelectionChangedListener(ISelectionChangedListener listener) { this.treeViewer.addSelectionChangedListener(listener); } @Override public ISelection getSelection() { return this.treeViewer.getSelection(); } @Override public void removeSelectionChangedListener( ISelectionChangedListener listener) { this.treeViewer.removeSelectionChangedListener(listener); } @Override public void setSelection(ISelection selection) { this.treeViewer.setSelection(selection); } public void setInput(List<URI> uris) { this.treeViewer.setInput(uris.toArray(new URI[uris.size()])); } public StructuredViewer getViewer() { return this.treeViewer; } /** * Returns the {@link ILocatable} that is the root of the currently selected * item (e.g. a {@link ICode}). * * @return */ public URI getUri() { if (ViewerUtils.getInput(this.treeViewer) instanceof URI[] && ((URI[]) ViewerUtils.getInput(this.treeViewer)).length == 1) { return ((URI[]) ViewerUtils.getInput(this.treeViewer))[0]; } List<URI> uris = new LinkedList<URI>(); TreeItem[] treeItems = this.treeViewer.getTree().getSelection(); for (TreeItem treeItem : treeItems) { URI locatable = this.getURI(treeItem); if (!uris.contains(locatable)) { uris.add(locatable); } } return uris.size() == 1 ? uris.get(0) : null; } /** * Returns the {@link ILocatable} that is the root of the given * {@link TreeItem}. * <p> * If the {@link TreeItem} is itself the representative for a * {@link ILocatable} it is also returned. * * @param treeItem * @return */ private URI getURI(TreeItem treeItem) { if (treeItem.getData() instanceof URI) { return (URI) treeItem.getData(); } if (treeItem.getParentItem() != null) { return this.getURI(treeItem.getParentItem()); } return null; } }
package org.springframework.ide.vscode.boot.java.requestmapping; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.lsp4j.CodeLens; import org.eclipse.lsp4j.Command; import org.eclipse.lsp4j.Hover; import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ide.vscode.boot.java.handlers.HoverProvider; import org.springframework.ide.vscode.boot.java.livehover.LiveHoverUtils; import org.springframework.ide.vscode.boot.java.livehover.v2.LiveRequestMapping; import org.springframework.ide.vscode.boot.java.livehover.v2.RequestMappingMetrics; import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessLiveData; import org.springframework.ide.vscode.commons.java.IJavaProject; import org.springframework.ide.vscode.commons.util.Renderable; import org.springframework.ide.vscode.commons.util.Renderables; import org.springframework.ide.vscode.commons.util.StringUtil; import org.springframework.ide.vscode.commons.util.text.TextDocument; import com.google.common.collect.ImmutableList; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; /** * @author Martin Lippert */ public class RequestMappingHoverProvider implements HoverProvider { // private static final String $$_LAMBDA$ = "$$Lambda$"; private static final Logger log = LoggerFactory.getLogger(RequestMappingHoverProvider.class); private static final int CODE_LENS_LIMIT = 3; @Override public Hover provideHover(ASTNode node, Annotation annotation, ITypeBinding type, int offset, TextDocument doc, IJavaProject project, SpringProcessLiveData[] processLiveData) { return provideHover(annotation, doc, processLiveData); } @Override public Collection<CodeLens> getLiveHintCodeLenses(IJavaProject project, Annotation annotation, TextDocument doc, SpringProcessLiveData[] processLiveData) { try { if (processLiveData.length > 0) { List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> val = getRequestMappingMethodFromRunningApp(annotation, processLiveData); if (!val.isEmpty()) { Range hoverRange = doc.toRange(annotation.getStartPosition(), annotation.getLength()); return assembleCodeLenses(hoverRange, val); } } } catch (Exception e) { log.error("", e); } return null; } // @Override // public Collection<CodeLens> getLiveHintCodeLenses(IJavaProject project, MethodDeclaration methodDeclaration, // TextDocument doc, SpringBootApp[] runningApps) { // try { // ImmutableList.Builder<Tuple2<RequestMapping, SpringBootApp>> builder = ImmutableList.builder(); // if (runningApps.length > 0) { // Annotation beanAnnotation = ASTUtils.getBeanAnnotation(methodDeclaration); // if (beanAnnotation != null) { // ITypeBinding returnTypeBinding = methodDeclaration.getReturnType2().resolveBinding(); // if ("org.springframework.web.reactive.function.server.RouterFunction".equals(returnTypeBinding.getErasure().getQualifiedName())) { // for (SpringBootApp app : runningApps) { // List<RequestMapping> matches = findFunctionalRequestMappings(app.getRequestMappings(), methodDeclaration); // for (RequestMapping rm : matches) { // builder.add(Tuples.of(rm, app)); // List<Tuple2<RequestMapping, SpringBootApp>> data = builder.build(); // if (!data.isEmpty()) { // SimpleName methodName = methodDeclaration.getName(); // Range hoverRange = doc.toRange(methodName.getStartPosition(), methodName.getLength()); // return assembleCodeLenses(hoverRange, getUrls(data)); // } catch (Exception e) { // log.error("", e); // return null; // private List<RequestMapping> findFunctionalRequestMappings(Collection<RequestMapping> requestMappings, // MethodDeclaration methodDeclaration) { // ImmutableList.Builder<RequestMapping> builder = ImmutableList.builder(); // IMethodBinding binding = methodDeclaration.resolveBinding(); // if (requestMappings != null) { // for (RequestMapping rm : requestMappings) { // String fqName = rm.getFullyQualifiedClassName(); // if (fqName != null) { // int lambdaIdx = fqName.indexOf($$_LAMBDA$); // if (lambdaIdx > 0) { // String containingTypeFqName = fqName.substring(0, lambdaIdx); // if (binding.getDeclaringClass().getQualifiedName().equals(containingTypeFqName)) { // builder.add(rm); // return builder.build(); private Collection<CodeLens> assembleCodeLenses(Range range, List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> data) { Collection<CodeLens> lenses = new ArrayList<>(); int remaining = 0; for (Tuple2<LiveRequestMapping, SpringProcessLiveData> dataEntry : data) { for (String url : getUrls(dataEntry)) { if (lenses.size() <= CODE_LENS_LIMIT) { Set<String> requestMethods = dataEntry.getT1().getRequestMethods(); RequestMappingMetrics metrics = dataEntry.getT2().getLiveMterics().getRequestMappingMetrics(new String[] { url }, requestMethods.toArray(new String[requestMethods.size()])); CodeLens codeLens = createCodeLensForRequestMapping(range, url, metrics); lenses.add(codeLens); } else { remaining++; } } } if (remaining > 0) { CodeLens codeLens = createCodeLensForRemaining(range, remaining); lenses.add(codeLens); } return lenses; } private Hover provideHover(Annotation annotation, TextDocument doc, SpringProcessLiveData[] processLiveData) { try { List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> val = getRequestMappingMethodFromRunningApp(annotation, processLiveData); if (!val.isEmpty()) { Hover hover = createHoverWithContent(val); Range hoverRange = doc.toRange(annotation.getStartPosition(), annotation.getLength()); hover.setRange(hoverRange); return hover; } else { return null; } } catch (Exception e) { log.error("", e); } return null; } private List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> getRequestMappingMethodFromRunningApp(Annotation annotation, SpringProcessLiveData[] processLiveData) { List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> results = new ArrayList<>(); try { for (SpringProcessLiveData liveData : processLiveData) { LiveRequestMapping[] mappings = liveData.getRequestMappings(); if (mappings != null && mappings.length > 0) { Arrays.stream(mappings) .filter(rm -> methodMatchesAnnotation(annotation, rm)) .map(rm -> Tuples.of(rm, liveData)) .findFirst().ifPresent(t -> results.add(t)); } } } catch (Exception e) { log.error("", e); } return results; } private boolean methodMatchesAnnotation(Annotation annotation, LiveRequestMapping rm) { String rqClassName = rm.getFullyQualifiedClassName(); if (rqClassName != null) { int chop = rqClassName.indexOf("$$EnhancerBySpringCGLIB$$"); if (chop >= 0) { rqClassName = rqClassName.substring(0, chop); } rqClassName = rqClassName.replace('$', '.'); ASTNode parent = annotation.getParent(); if (parent instanceof MethodDeclaration) { MethodDeclaration methodDec = (MethodDeclaration) parent; IMethodBinding binding = methodDec.resolveBinding(); if (binding != null) { return binding.getDeclaringClass().getQualifiedName().equals(rqClassName) && binding.getName().equals(rm.getMethodName()) && Arrays.equals(Arrays.stream(binding.getParameterTypes()) .map(t -> t.getTypeDeclaration().getQualifiedName()) .toArray(String[]::new), rm.getMethodParameters()); } // } else if (parent instanceof TypeDeclaration) { // TypeDeclaration typeDec = (TypeDeclaration) parent; // return typeDec.resolveBinding().getQualifiedName().equals(rqClassName); } } return false; } private List<String> getUrls(Tuple2<LiveRequestMapping, SpringProcessLiveData> mappingMethod) { List<String> urls = new ArrayList<>(); SpringProcessLiveData liveData = mappingMethod.getT2(); String contextPath = liveData.getContextPath(); String urlScheme = liveData.getUrlScheme(); String port = liveData.getPort(); String host = liveData.getHost(); String[] paths = mappingMethod.getT1().getSplitPath(); if (paths==null || paths.length==0) { //Technically, this means the path 'predicate' is unconstrained, meaning any path matches. //So this is not quite the same as the case where path=""... but... //It is better for us to show one link where any path is allowed, versus showing no links where any link is allowed. //So we'll pretend this is the same as path="" as that gives a working link. paths = new String[] {""}; } for (String path : paths) { String url = UrlUtil.createUrl(urlScheme, host, port, path, contextPath); urls.add(url); } return urls; } private Hover createHoverWithContent(List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> mappingMethods) throws Exception { StringBuilder contentVal = new StringBuilder(); for (int i = 0; i < mappingMethods.size(); i++) { Tuple2<LiveRequestMapping, SpringProcessLiveData> mappingMethod = mappingMethods.get(i); SpringProcessLiveData liveData = mappingMethod.getT2(); LiveRequestMapping requestMapping = mappingMethod.getT1(); String urlScheme = liveData.getUrlScheme(); String port = liveData.getPort(); String host = liveData.getHost(); String[] paths = requestMapping.getSplitPath(); if (paths==null || paths.length==0) { //Technically, this means the path 'predicate' is unconstrained, meaning any path matches. //So this is not quite the same as the case where path=""... but... //It is better for us to show one link where any path is allowed, versus showing no links where any link is allowed. //So we'll pretend this is the same as path="" as that gives a working link. paths = new String[] {""}; } String contextPath = liveData.getContextPath(); List<Renderable> renderableUrls = Arrays.stream(paths).flatMap(path -> { String url = UrlUtil.createUrl(urlScheme, host, port, path, contextPath); return Stream.of(Renderables.link(url, url), Renderables.lineBreak()); }) .collect(Collectors.toList()); Renderable urlRenderables = Renderables.concat(renderableUrls); Set<String> requestMethods = requestMapping.getRequestMethods(); RequestMappingMetrics metrics = liveData.getLiveMterics().getRequestMappingMetrics(requestMapping.getSplitPath(), requestMethods.toArray(new String[requestMethods.size()])); if (metrics != null) { Renderable metricsRenderable = Renderables.concat( Renderables.bold("Count: " + metrics.getCallsCount() + " | Total Time: " + metrics.getTotalTime() + " | Max Time: " + metrics.getMaxTime()), Renderables.text("\n\n")); urlRenderables = Renderables.concat(urlRenderables, Renderables.text("\n\n"), metricsRenderable); } Renderable processSection = Renderables.concat( urlRenderables, Renderables.mdBlob(LiveHoverUtils.niceAppName(liveData)) ); if (i < mappingMethods.size() - 1) { processSection = Renderables.concat( processSection, Renderables.text("\n\n") ); } String markdown = processSection.toMarkdown(); contentVal.append(markdown); } // PT 163470104 - Add content at hover construction to avoid separators // being added between the content itself return new Hover(ImmutableList.of(Either.forLeft(contentVal.toString()))); } private CodeLens createCodeLensForRequestMapping(Range range, String content, RequestMappingMetrics metrics) { CodeLens codeLens = new CodeLens(); codeLens.setRange(range); Command cmd = new Command(); if (StringUtil.hasText(content)) { if (metrics != null) { char timeUnitShort = metrics.getTimeUnit().name().charAt(0); StringBuilder codeLensContent = new StringBuilder(content); codeLensContent.append(' '); codeLensContent.append('('); codeLensContent.append("Count="); codeLensContent.append(metrics.getCallsCount()); codeLensContent.append(' '); codeLensContent.append("Total="); codeLensContent.append(shorten(metrics.getTotalTime())); codeLensContent.append(timeUnitShort); codeLensContent.append(' '); codeLensContent.append("Max="); codeLensContent.append(shorten(metrics.getMaxTime())); codeLensContent.append(timeUnitShort); codeLensContent.append(')'); content = codeLensContent.toString(); } codeLens.setData(content); cmd.setTitle(content); cmd.setCommand("sts.open.url"); cmd.setArguments(ImmutableList.of(content)); } codeLens.setCommand(cmd); return codeLens; } private double shorten(double val) { return val; } private CodeLens createCodeLensForRemaining(Range range, int remaining) { CodeLens codeLens = new CodeLens(); codeLens.setRange(range); Command cmd = new Command(); cmd.setTitle(remaining + " more..."); // Don't set an actual command ID as to make this code lens "unclickable".. // It is just meant to be a label, to tell users to hover over the request mapping // to see the full list codeLens.setCommand(cmd); return codeLens; } }
package org.springframework.ide.vscode.boot.java.requestmapping; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.lsp4j.CodeLens; import org.eclipse.lsp4j.Command; import org.eclipse.lsp4j.Hover; import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ide.vscode.boot.java.handlers.HoverProvider; import org.springframework.ide.vscode.boot.java.livehover.LiveHoverUtils; import org.springframework.ide.vscode.boot.java.livehover.v2.LiveRequestMapping; import org.springframework.ide.vscode.boot.java.livehover.v2.RequestMappingMetrics; import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessLiveData; import org.springframework.ide.vscode.commons.java.IJavaProject; import org.springframework.ide.vscode.commons.util.Renderable; import org.springframework.ide.vscode.commons.util.Renderables; import org.springframework.ide.vscode.commons.util.StringUtil; import org.springframework.ide.vscode.commons.util.text.TextDocument; import com.google.common.collect.ImmutableList; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; /** * @author Martin Lippert */ public class RequestMappingHoverProvider implements HoverProvider { // private static final String $$_LAMBDA$ = "$$Lambda$"; private static final Logger log = LoggerFactory.getLogger(RequestMappingHoverProvider.class); private static final int CODE_LENS_LIMIT = 3; @Override public Hover provideHover(ASTNode node, Annotation annotation, ITypeBinding type, int offset, TextDocument doc, IJavaProject project, SpringProcessLiveData[] processLiveData) { return provideHover(annotation, doc, processLiveData); } @Override public Collection<CodeLens> getLiveHintCodeLenses(IJavaProject project, Annotation annotation, TextDocument doc, SpringProcessLiveData[] processLiveData) { try { if (processLiveData.length > 0) { List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> val = getRequestMappingMethodFromRunningApp(annotation, processLiveData); if (!val.isEmpty()) { Range hoverRange = doc.toRange(annotation.getStartPosition(), annotation.getLength()); return assembleCodeLenses(hoverRange, val); } } } catch (Exception e) { log.error("", e); } return null; } // @Override // public Collection<CodeLens> getLiveHintCodeLenses(IJavaProject project, MethodDeclaration methodDeclaration, // TextDocument doc, SpringBootApp[] runningApps) { // try { // ImmutableList.Builder<Tuple2<RequestMapping, SpringBootApp>> builder = ImmutableList.builder(); // if (runningApps.length > 0) { // Annotation beanAnnotation = ASTUtils.getBeanAnnotation(methodDeclaration); // if (beanAnnotation != null) { // ITypeBinding returnTypeBinding = methodDeclaration.getReturnType2().resolveBinding(); // if ("org.springframework.web.reactive.function.server.RouterFunction".equals(returnTypeBinding.getErasure().getQualifiedName())) { // for (SpringBootApp app : runningApps) { // List<RequestMapping> matches = findFunctionalRequestMappings(app.getRequestMappings(), methodDeclaration); // for (RequestMapping rm : matches) { // builder.add(Tuples.of(rm, app)); // List<Tuple2<RequestMapping, SpringBootApp>> data = builder.build(); // if (!data.isEmpty()) { // SimpleName methodName = methodDeclaration.getName(); // Range hoverRange = doc.toRange(methodName.getStartPosition(), methodName.getLength()); // return assembleCodeLenses(hoverRange, getUrls(data)); // } catch (Exception e) { // log.error("", e); // return null; // private List<RequestMapping> findFunctionalRequestMappings(Collection<RequestMapping> requestMappings, // MethodDeclaration methodDeclaration) { // ImmutableList.Builder<RequestMapping> builder = ImmutableList.builder(); // IMethodBinding binding = methodDeclaration.resolveBinding(); // if (requestMappings != null) { // for (RequestMapping rm : requestMappings) { // String fqName = rm.getFullyQualifiedClassName(); // if (fqName != null) { // int lambdaIdx = fqName.indexOf($$_LAMBDA$); // if (lambdaIdx > 0) { // String containingTypeFqName = fqName.substring(0, lambdaIdx); // if (binding.getDeclaringClass().getQualifiedName().equals(containingTypeFqName)) { // builder.add(rm); // return builder.build(); private Collection<CodeLens> assembleCodeLenses(Range range, List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> data) { Collection<CodeLens> lenses = new ArrayList<>(); int remaining = 0; for (Tuple2<LiveRequestMapping, SpringProcessLiveData> dataEntry : data) { for (Tuple2<String, String> urlWithPath : getUrlsWithPath(dataEntry)) { if (lenses.size() <= CODE_LENS_LIMIT) { SpringProcessLiveData liveData = dataEntry.getT2(); LiveRequestMapping requestMapping = dataEntry.getT1(); String url = urlWithPath.getT1(); String path = urlWithPath.getT2(); Set<String> requestMethods = requestMapping.getRequestMethods(); RequestMappingMetrics metrics = liveData.getLiveMterics() == null ? null : liveData.getLiveMterics().getRequestMappingMetrics(new String[] { path }, requestMethods.toArray(new String[requestMethods.size()])); CodeLens codeLens = createCodeLensForRequestMapping(range, url, metrics); lenses.add(codeLens); } else { remaining++; } } } if (remaining > 0) { CodeLens codeLens = createCodeLensForRemaining(range, remaining); lenses.add(codeLens); } return lenses; } private Hover provideHover(Annotation annotation, TextDocument doc, SpringProcessLiveData[] processLiveData) { try { List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> val = getRequestMappingMethodFromRunningApp(annotation, processLiveData); if (!val.isEmpty()) { Hover hover = createHoverWithContent(val); Range hoverRange = doc.toRange(annotation.getStartPosition(), annotation.getLength()); hover.setRange(hoverRange); return hover; } else { return null; } } catch (Exception e) { log.error("", e); } return null; } private List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> getRequestMappingMethodFromRunningApp(Annotation annotation, SpringProcessLiveData[] processLiveData) { List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> results = new ArrayList<>(); try { for (SpringProcessLiveData liveData : processLiveData) { LiveRequestMapping[] mappings = liveData.getRequestMappings(); if (mappings != null && mappings.length > 0) { Arrays.stream(mappings) .filter(rm -> methodMatchesAnnotation(annotation, rm)) .map(rm -> Tuples.of(rm, liveData)) .findFirst().ifPresent(t -> results.add(t)); } } } catch (Exception e) { log.error("", e); } return results; } private boolean methodMatchesAnnotation(Annotation annotation, LiveRequestMapping rm) { String rqClassName = rm.getFullyQualifiedClassName(); if (rqClassName != null) { int chop = rqClassName.indexOf("$$EnhancerBySpringCGLIB$$"); if (chop >= 0) { rqClassName = rqClassName.substring(0, chop); } rqClassName = rqClassName.replace('$', '.'); ASTNode parent = annotation.getParent(); if (parent instanceof MethodDeclaration) { MethodDeclaration methodDec = (MethodDeclaration) parent; IMethodBinding binding = methodDec.resolveBinding(); if (binding != null) { return binding.getDeclaringClass().getQualifiedName().equals(rqClassName) && binding.getName().equals(rm.getMethodName()) && Arrays.equals(Arrays.stream(binding.getParameterTypes()) .map(t -> t.getTypeDeclaration().getQualifiedName()) .toArray(String[]::new), rm.getMethodParameters()); } // } else if (parent instanceof TypeDeclaration) { // TypeDeclaration typeDec = (TypeDeclaration) parent; // return typeDec.resolveBinding().getQualifiedName().equals(rqClassName); } } return false; } private List<Tuple2<String, String>> getUrlsWithPath(Tuple2<LiveRequestMapping, SpringProcessLiveData> mappingMethod) { List<Tuple2<String, String>> urls = new ArrayList<>(); SpringProcessLiveData liveData = mappingMethod.getT2(); String contextPath = liveData.getContextPath(); String urlScheme = liveData.getUrlScheme(); String port = liveData.getPort(); String host = liveData.getHost(); LiveRequestMapping requestMapping = mappingMethod.getT1(); String[] paths = requestMapping.getSplitPath(); if (paths==null || paths.length==0) { //Technically, this means the path 'predicate' is unconstrained, meaning any path matches. //So this is not quite the same as the case where path=""... but... //It is better for us to show one link where any path is allowed, versus showing no links where any link is allowed. //So we'll pretend this is the same as path="" as that gives a working link. paths = new String[] {""}; } for (String path : paths) { String url = UrlUtil.createUrl(urlScheme, host, port, path, contextPath); urls.add(Tuples.of(url, path)); } return urls; } private Hover createHoverWithContent(List<Tuple2<LiveRequestMapping, SpringProcessLiveData>> mappingMethods) throws Exception { StringBuilder contentVal = new StringBuilder(); for (int i = 0; i < mappingMethods.size(); i++) { Tuple2<LiveRequestMapping, SpringProcessLiveData> mappingMethod = mappingMethods.get(i); SpringProcessLiveData liveData = mappingMethod.getT2(); LiveRequestMapping requestMapping = mappingMethod.getT1(); String urlScheme = liveData.getUrlScheme(); String port = liveData.getPort(); String host = liveData.getHost(); String[] paths = requestMapping.getSplitPath(); if (paths==null || paths.length==0) { //Technically, this means the path 'predicate' is unconstrained, meaning any path matches. //So this is not quite the same as the case where path=""... but... //It is better for us to show one link where any path is allowed, versus showing no links where any link is allowed. //So we'll pretend this is the same as path="" as that gives a working link. paths = new String[] {""}; } String contextPath = liveData.getContextPath(); List<Renderable> renderableUrls = Arrays.stream(paths).flatMap(path -> { String url = UrlUtil.createUrl(urlScheme, host, port, path, contextPath); return Stream.of(Renderables.link(url, url), Renderables.lineBreak()); }) .collect(Collectors.toList()); Renderable urlRenderables = Renderables.concat(renderableUrls); Set<String> requestMethods = requestMapping.getRequestMethods(); RequestMappingMetrics metrics = liveData.getLiveMterics() == null ? null : liveData.getLiveMterics().getRequestMappingMetrics(requestMapping.getSplitPath(), requestMethods.toArray(new String[requestMethods.size()])); if (metrics != null) { Renderable metricsRenderable = Renderables.concat( Renderables.bold(createHoverMetricsContent(metrics)), Renderables.text("\n\n")); urlRenderables = Renderables.concat(urlRenderables, Renderables.text("\n\n"), metricsRenderable); } Renderable processSection = Renderables.concat( urlRenderables, Renderables.mdBlob(LiveHoverUtils.niceAppName(liveData)) ); if (i < mappingMethods.size() - 1) { processSection = Renderables.concat( processSection, Renderables.text("\n\n") ); } String markdown = processSection.toMarkdown(); contentVal.append(markdown); } // PT 163470104 - Add content at hover construction to avoid separators // being added between the content itself return new Hover(ImmutableList.of(Either.forLeft(contentVal.toString()))); } private String createHoverMetricsContent(RequestMappingMetrics metrics) { char timeUnitShort = metrics.getTimeUnit().name().toLowerCase().charAt(0); StringBuilder metricsContent = new StringBuilder(); metricsContent.append("Count: "); metricsContent.append(metrics.getCallsCount()); metricsContent.append(" | Total Time: "); metricsContent.append(metrics.getTotalTime()); metricsContent.append(timeUnitShort); metricsContent.append(" | Max Time: "); metricsContent.append(metrics.getMaxTime()); metricsContent.append(timeUnitShort); return metricsContent.toString(); } private String createCodeLensMetricsContent(RequestMappingMetrics metrics) { char timeUnitShort = metrics.getTimeUnit().name().toLowerCase().charAt(0); StringBuilder metricsContent = new StringBuilder(); metricsContent.append("Count="); metricsContent.append(metrics.getCallsCount()); metricsContent.append(' '); metricsContent.append("Total="); metricsContent.append(String.format("%.2f", metrics.getTotalTime())); metricsContent.append(timeUnitShort); metricsContent.append(' '); metricsContent.append("Max="); metricsContent.append(String.format("%.2f", metrics.getMaxTime())); metricsContent.append(timeUnitShort); return metricsContent.toString(); } private CodeLens createCodeLensForRequestMapping(Range range, String content, RequestMappingMetrics metrics) { CodeLens codeLens = new CodeLens(); codeLens.setRange(range); Command cmd = new Command(); if (StringUtil.hasText(content)) { if (metrics != null) { StringBuilder codeLensContent = new StringBuilder(content); codeLensContent.append(' '); codeLensContent.append('('); codeLensContent.append(createCodeLensMetricsContent(metrics)); codeLensContent.append(')'); content = codeLensContent.toString(); } codeLens.setData(content); cmd.setTitle(content); cmd.setCommand("sts.open.url"); cmd.setArguments(ImmutableList.of(content)); } codeLens.setCommand(cmd); return codeLens; } private CodeLens createCodeLensForRemaining(Range range, int remaining) { CodeLens codeLens = new CodeLens(); codeLens.setRange(range); Command cmd = new Command(); cmd.setTitle(remaining + " more..."); // Don't set an actual command ID as to make this code lens "unclickable".. // It is just meant to be a label, to tell users to hover over the request mapping // to see the full list codeLens.setCommand(cmd); return codeLens; } }
package fr.openwide.core.showcase.core.config.spring; import java.net.MalformedURLException; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.transaction.annotation.EnableTransactionManagement; import fr.openwide.core.showcase.core.ShowcaseCorePackage; import fr.openwide.core.showcase.core.init.BootstrapApplicationServiceImpl; import fr.openwide.core.showcase.core.util.spring.ShowcaseConfigurer; import fr.openwide.core.spring.config.spring.AbstractApplicationConfig; import fr.openwide.core.spring.config.spring.annotation.ApplicationDescription; import fr.openwide.core.spring.config.spring.annotation.ConfigurationLocations; @Configuration @ApplicationDescription(name = ShowcaseCoreConfig.APPLICATION_NAME) @ConfigurationLocations @Import({ ShowcaseCoreJpaConfig.class, // configuration de la persistence ShowcaseCoreSecurityConfig.class }) @ComponentScan( basePackageClasses = { ShowcaseCorePackage.class }, excludeFilters = @Filter(Configuration.class) ) //fonctionnement de l'annotation @Transactional @EnableTransactionManagement(mode = AdviceMode.ASPECTJ) public class ShowcaseCoreConfig extends AbstractApplicationConfig { public static final String APPLICATION_NAME = "showcase"; public static final String PROFILE_TEST = "test"; @Bean(name = {"showcaseConfigurer", "configurer"}) public static ShowcaseConfigurer environment(ConfigurableApplicationContext context) throws MalformedURLException { return new ShowcaseConfigurer(); } @Bean public BootstrapApplicationServiceImpl bootstrapApplicationService() { return new BootstrapApplicationServiceImpl(); } }
package org.csstudio.diag.interconnectionServer.server; import java.util.*; import java.text.*; import org.csstudio.platform.logging.CentralLogger; public class Statistic { /* * XXX: this class has a slightly misleading name. Its inner class * StatisticContent is used to track the beacon times/timeouts (for the * watchdog functionality). */ private static Statistic statisticInstance = null; Hashtable<String,StatisticContent> connectionList = null; int totalNumberOfConnections = 0; int totalNumberOfIncomingMessages = 0; int totalNumberOfOutgoingMessages = 0; int numberOfJmsServerFailover = -1; public Statistic () { // initialize hash table connectionList = new Hashtable<String,StatisticContent>(); } public static Statistic getInstance() { // get an instance of our singleton if ( statisticInstance == null) { synchronized (Statistic.class) { if (statisticInstance == null) { statisticInstance = new Statistic(); } } } return statisticInstance; } public int getTotalNumberOfIncomingMessages() { return this.totalNumberOfIncomingMessages; } public int getTotalNumberOfOutgoingMessages() { return this.totalNumberOfOutgoingMessages; } public void incrementNumberOfJmsServerFailover () { numberOfJmsServerFailover++; } public int getNumberOfJmsServerFailover () { return numberOfJmsServerFailover; } /* public Statistic ( String statisticID, String lastMessage, int lastMessageSize, String lastCommand ) { } */ public StatisticContent getContentObject ( String statisticId) { // search for content object with id statisticId StatisticContent contentObject = null; if( connectionList.containsKey( statisticId)) { contentObject = (StatisticContent) connectionList.get( statisticId); } else { // create new statistic object contentObject = new StatisticContent( statisticId); connectionList.put( statisticId, contentObject); } return contentObject; } public class StatisticContent { String host = null; String ipAddress = null; String logicalIocName = null; String ldapIocName = null; int port = 0; String lastMessage = null; int lastMessageSize = 0; int accumulatedMessageSize = 0; int numberOfIncomingMessages = 0; int numberOfOutgoingMessages = 0; String lastCommand = null; GregorianCalendar timeStarted = null; GregorianCalendar timeReConnected = null; GregorianCalendar timeLastReceived = null; GregorianCalendar timeLastCommandSent = null; GregorianCalendar timeLastBeaconReceived = null; GregorianCalendar timePreviousBeaconReceived = null; GregorianCalendar time2ndPreviousBeaconReceived = null; int deltaTimeLastBeaconReceived = 0; int deltaTimePreviousBeaconReceived = 0; int deltaTime2ndPreviousBeaconReceived = 0; GregorianCalendar timeLastErrorOccured = null; int errorCounter = 0; boolean connectState = false; boolean selectState = false; int selectStateCounter = 0; boolean getAllAlarmsOnSelectChange = true; boolean didWeSetAllChannelToDisconnect = false; // set to true if the command has bee issued String statisticId = null; public boolean isGetAllAlarmsOnSelectChange() { return getAllAlarmsOnSelectChange; } public void setGetAllAlarmsOnSelectChange(boolean getAllAlarmsOnSelectChange) { this.getAllAlarmsOnSelectChange = getAllAlarmsOnSelectChange; } public int getSelectStateCounter() { return selectStateCounter; } public void setSelectStateCounter(int selectStateCounter) { this.selectStateCounter = selectStateCounter; } public void incrementSelectStateCounter() { this.selectStateCounter++; } public StatisticContent ( String statisticId) { // init time this.timeStarted = new GregorianCalendar(); this.timeReConnected = new GregorianCalendar(); this.timeLastReceived = new GregorianCalendar(1970,1,1); this.timeLastCommandSent = new GregorianCalendar(1970,1,1); this.timeLastBeaconReceived = new GregorianCalendar(1970,1,1); this.timePreviousBeaconReceived = new GregorianCalendar(1970,1,1); this.time2ndPreviousBeaconReceived = new GregorianCalendar(1970,1,1); this.timeLastErrorOccured = new GregorianCalendar(1970,1,1); this.statisticId = statisticId; } public void setTime (Boolean received) { // init time if ( received) { this.timeLastReceived = new GregorianCalendar(); numberOfIncomingMessages++; totalNumberOfIncomingMessages++; } else { this.timeLastCommandSent = new GregorianCalendar(); numberOfOutgoingMessages++; totalNumberOfOutgoingMessages++; } } public void setBeaconTime ( ) { // init time /* * Why is it so complicated? * Order: * IOC new connected: * (1)Beacon ->setBeaconTime() * (2)Message -> setBeaconTime() - process message - find out we are selected - check for beacon time * In this case: * - 2ndprevious == old * - previous == set by (1) -> most recent ~ as old as the beacon update time * - last == set by (2) -> the current time * ==> we have to check against the 2ndprevious time */ GregorianCalendar newTime = new GregorianCalendar(); setDeltaTimeLastBeaconReceived( gregorianTimeDifference ( this.timeLastBeaconReceived, newTime)); setDeltaTimePreviousBeaconReceived( gregorianTimeDifference ( this.timePreviousBeaconReceived, newTime)); setDeltaTime2ndPreviousBeaconReceived( gregorianTimeDifference ( this.time2ndPreviousBeaconReceived, newTime)); this.time2ndPreviousBeaconReceived = this.timePreviousBeaconReceived; this.timePreviousBeaconReceived = this.timeLastBeaconReceived; this.timeLastBeaconReceived = newTime; } public void setHost ( String host) { this.host = host; } public String getHost () { return host; } public void setPort ( int port) { this.port = port; } public int getPort () { return port; } public void setLastMessage ( String lastMessage) { this.lastMessage = lastMessage; } public void setLastMessageSize ( int lastMessageSize) { this.lastMessageSize = lastMessageSize; this.accumulatedMessageSize += lastMessageSize; } public void setConnectState ( boolean state) { this.connectState = state; } public boolean getConnectState () { return connectState; } public String dateToString ( GregorianCalendar gregorsDate) { // convert Gregorian date into string //TODO: use other time format - actually : DD-MM-YYYY Date d = gregorsDate.getTime(); SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.S" ); //DateFormat df = DateFormat.getDateInstance(); return df.format(d); } public long dateToLong ( GregorianCalendar gregorsDate) { // convert Gregorian date into long return gregorsDate.getTime().getTime(); } public int gregorianTimeDifference ( GregorianCalendar fromTime, GregorianCalendar toTime) { // calculate time difference Date fromDate = fromTime.getTime(); Date toDate = toTime.getTime(); long fromLong = fromDate.getTime(); long toLong = toDate.getTime(); long timeDifference = toLong - fromLong; int intDiff = (int)timeDifference; return intDiff; } public int gregorianTimeDifferenceFromNow ( GregorianCalendar fromTime) { // time diff from now return gregorianTimeDifference ( fromTime, new GregorianCalendar()); } public void incrementErrorCounter () { this.errorCounter++; this.timeLastErrorOccured = new GregorianCalendar(); } public int getErrorCounter () { return this.errorCounter; } public GregorianCalendar getTimeStarted () { return this.timeStarted; } public GregorianCalendar getTimeLastReceived () { return this.timeLastReceived; } public GregorianCalendar getTimeLastCommandSent () { return this.timeLastCommandSent; } public GregorianCalendar getTimeLastBeaconReceived () { return this.timeLastBeaconReceived; } public GregorianCalendar getTimeLastErrorOccured () { return this.timeLastErrorOccured; } public String getCurrentConnectState () { if( this.connectState) { return "connected"; } else { return "disconnected"; } } public String getStatisticId () { return statisticId; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public boolean isSelectState() { return selectState; } public void setSelectState(boolean selectState) { this.selectState = selectState; } public String getCurrentSelectState () { if( this.selectState) { return "selected"; } else { return "NOT selected"; } } public String getLogicalIocName() { return logicalIocName; } public void setLogicalIocName(String logicalIocName) { this.logicalIocName = logicalIocName; } public String getLdapIocName() { return ldapIocName; } public void setLdapIocName(String ldapIocName) { this.ldapIocName = ldapIocName; } public int getDeltaTimeLastBeaconReceived() { return deltaTimeLastBeaconReceived; } public void setDeltaTimeLastBeaconReceived( int deltaTimeLastBeaconReceived) { this.deltaTimeLastBeaconReceived = deltaTimeLastBeaconReceived; } public boolean wasPreviousBeaconWithinThreeBeaconTimeouts() { if ( getDeltaTime2ndPreviousBeaconReceived() > 3*PreferenceProperties.BEACON_TIMEOUT) { CentralLogger.getInstance().info(this, "Previous beacon timeout: " + getDeltaTime2ndPreviousBeaconReceived() + " [ms]"); return false; } else { CentralLogger.getInstance().info(this, "Previous beacon within timeout period: " + getDeltaTime2ndPreviousBeaconReceived() + " [ms] < " + 3*PreferenceProperties.BEACON_TIMEOUT); // CentralLogger.getInstance().info(this, "LastBeacon " + getDeltaTimePreviousBeaconReceived() + " [ms]"); // CentralLogger.getInstance().info(this, "LastBeacon " + getDeltaTimeLastBeaconReceived() + " [ms]"); return true; } } public boolean areWeConnectedLongerThenThreeBeaconTimeouts() { GregorianCalendar newTime = new GregorianCalendar(); if ( gregorianTimeDifference ( this.timeReConnected, newTime) > 3*PreferenceProperties.BEACON_TIMEOUT) { //nothing to do - already long time connected return true; } else { // the user might trigger some actions return false; } } public int getDeltaTimePreviousBeaconReceived() { return deltaTimePreviousBeaconReceived; } public void setDeltaTimePreviousBeaconReceived( int deltaTimePreviousBeaconReceived) { this.deltaTimePreviousBeaconReceived = deltaTimePreviousBeaconReceived; } public GregorianCalendar getTimePreviousBeaconReceived() { return timePreviousBeaconReceived; } public void setTimePreviousBeaconReceived( GregorianCalendar timePreviousBeaconReceived) { this.timePreviousBeaconReceived = timePreviousBeaconReceived; } public GregorianCalendar getTime2ndPreviousBeaconReceived() { return time2ndPreviousBeaconReceived; } public void setTime2ndPreviousBeaconReceived( GregorianCalendar time2ndPreviousBeaconReceived) { this.time2ndPreviousBeaconReceived = time2ndPreviousBeaconReceived; } public int getDeltaTime2ndPreviousBeaconReceived() { return deltaTime2ndPreviousBeaconReceived; } public void setDeltaTime2ndPreviousBeaconReceived( int deltaTime2ndPreviousBeaconReceived) { this.deltaTime2ndPreviousBeaconReceived = deltaTime2ndPreviousBeaconReceived; } public GregorianCalendar getTimeReConnected() { return timeReConnected; } public void setTimeReConnected(GregorianCalendar timeReConnected) { this.timeReConnected = timeReConnected; } public void setTimeReConnected() { this.timeReConnected = new GregorianCalendar(); } public boolean isDidWeSetAllChannelToDisconnect() { return didWeSetAllChannelToDisconnect; } public void setDidWeSetAllChannelToDisconnect( boolean didWeSetAllChannelToDisconnect) { this.didWeSetAllChannelToDisconnect = didWeSetAllChannelToDisconnect; } public void setStatisticId(String statisticId) { this.statisticId = statisticId; } } public void createStatisticPrintout () { System.out.println("Total incomin messages = " + this.totalNumberOfIncomingMessages); System.out.println("Total outgoing messages = " + this.totalNumberOfOutgoingMessages); System.out.println(""); Enumeration connections = this.connectionList.elements(); while (connections.hasMoreElements()) { StatisticContent thisContent = (StatisticContent)connections.nextElement(); System.out.println(" System.out.println("Host:Port: " + thisContent.host + ":" + thisContent.port); System.out.println("Current ConnectState : " + thisContent.getCurrentConnectState()); System.out.println("Number of Incoming Messages : " + thisContent.numberOfIncomingMessages); System.out.println("Number of Outgoing Messages : " + thisContent.numberOfOutgoingMessages); System.out.println("Number of Errors : " + thisContent.errorCounter); System.out.println("Last Message : " + thisContent.lastMessage); System.out.println("Last Message Size : " + thisContent.lastMessageSize); System.out.println("Accumulated Message Size : " + thisContent.accumulatedMessageSize); System.out.println("Start Time : " + thisContent.dateToString(thisContent.timeStarted)); System.out.println("Last Beacon Time : " + thisContent.dateToString(thisContent.timeLastBeaconReceived)); System.out.println("Last Message Received : " + thisContent.dateToString(thisContent.timeLastReceived)); System.out.println("Last Command Sent Time : " + thisContent.dateToString(thisContent.timeLastCommandSent)); System.out.println("Last Error Occured : " + thisContent.dateToString(thisContent.timeLastErrorOccured)); System.out.println(""); } } public String getStatisticAsString () { String result = ""; result += "\nTotal incomin messages = " + this.totalNumberOfIncomingMessages ; result += "\nTotal outgoing messages = " + this.totalNumberOfOutgoingMessages ; result += "\n" ; Enumeration connections = this.connectionList.elements( ); while (connections.hasMoreElements()) { StatisticContent thisContent = (StatisticContent)connections.nextElement(); result += "\n result += "\nHost:Port: " + thisContent.host + ":" + thisContent.port ; result += "\nCurrent ConnectState : " + thisContent.getCurrentConnectState() ; result += "\nNumber of Incoming Messages : " + thisContent.numberOfIncomingMessages ; result += "\nNumber of Outgoing Messages : " + thisContent.numberOfOutgoingMessages ; result += "\nNumber of Errors : " + thisContent.errorCounter ; result += "\nLast Message : " + thisContent.lastMessage ; result += "\nLast Message Size : " + thisContent.lastMessageSize ; result += "\nAccumulated Message Size : " + thisContent.accumulatedMessageSize ; result += "\nStart Time : " + thisContent.dateToString(thisContent.timeStarted) ; result += "\nLast Beacon Time : " + thisContent.dateToString(thisContent.timeLastBeaconReceived) ; result += "\nLast Message Received : " + thisContent.dateToString(thisContent.timeLastReceived) ; result += "\nLast Command Sent Time : " + thisContent.dateToString(thisContent.timeLastCommandSent) ; result += "\nLast Error Occured : " + thisContent.dateToString(thisContent.timeLastErrorOccured) ; result += "\n" ; } return result; } public String getNodeNames () { String nodeNames = null; boolean first = true; try { // just in case no enum is possible Enumeration connections = this.connectionList.elements(); while (connections.hasMoreElements()) { StatisticContent thisContent = (StatisticContent)connections.nextElement(); if ( first) { nodeNames = thisContent.host + ","; } else { nodeNames += thisContent.host + ","; } first = false; } } catch (Exception e) { nodeNames = "NONE"; } return nodeNames; } public String[] getNodeNameArray () { List<String> nodeNames = new ArrayList<String>(); boolean first = true; try { // just in case no enum is possible Enumeration connections = this.connectionList.elements(); while (connections.hasMoreElements()) { StatisticContent thisContent = (StatisticContent)connections.nextElement(); nodeNames.add(thisContent.getHost()); } } catch (Exception e) { nodeNames.add("NONE"); } return nodeNames.toArray(new String[0]); } public String[] getNodeNameArrayWithLogicalName () { List<String> nodeNames = new ArrayList<String>(); boolean first = true; try { // just in case no enum is possible Enumeration connections = this.connectionList.elements(); while (connections.hasMoreElements()) { StatisticContent thisContent = (StatisticContent)connections.nextElement(); nodeNames.add(thisContent.getHost() + "|" + thisContent.getLogicalIocName()); } } catch (Exception e) { nodeNames.add("NONE"); } return nodeNames.toArray(new String[0]); } public String[] getNodeNameStatusArray () { List<String> nodeNames = new ArrayList<String>(); boolean first = true; try { // just in case no enum is possible Enumeration connections = this.connectionList.elements(); while (connections.hasMoreElements()) { StatisticContent thisContent = (StatisticContent)connections.nextElement(); nodeNames.add(thisContent.getHost() + " | " + thisContent.getLogicalIocName() + " " + thisContent.getCurrentConnectState() + " " + thisContent.getCurrentSelectState()); } } catch (Exception e) { nodeNames.add("NONE"); } return nodeNames.toArray(new String[0]); } }