Unnamed: 0
int64
0
2.05k
func
stringlengths
27
124k
target
bool
2 classes
project
stringlengths
39
117
300
public enum VisualControlDescriptor { /**A label visual component such as a JLabel. Its value is immutable. */ Label, /**A text field component such as a JTextField, modified using getValueAsText and setValueAsText. Initialized using getValueAsText. */ TextField, /**A check box component such as a JCheckBox. It is initialized and modified using getValue and setValue of type Boolean. */ CheckBox, /**A combo box component such as a JComboBox, initialized and modified using getValue and setValue. Its enumerated list is populated using getTags. */ ComboBox; };
false
mctcore_src_main_java_gov_nasa_arc_mct_components_PropertyDescriptor.java
301
public interface PropertyEditor<E> { /** * Gets the property value as text. * @return the property value as text */ public String getAsText(); /** * Set the property value by parsing a given String. * Implementations should override this method to provide MCT component-specific operations * such as business model updates and field validation. * If a prospective field value is not valid, the implementation should * throw an exception. * @param text the new text * @throws IllegalArgumentException upon error, typically used for validity checking */ public void setAsText(String text) throws java.lang.IllegalArgumentException; /** * Gets the property value. * @return the value */ public Object getValue(); /** * Set (or change) the object that is to be edited. * @param value the new value * @throws IllegalArgumentException upon error, typically used for validity checking */ public void setValue(Object value) throws java.lang.IllegalArgumentException; /** *.Get a tag list. * If the property value must be one of a set of known tagged values, then this method should return an array of the tags. * @return a list of values for the property */ public List<E> getTags(); }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_PropertyEditor.java
302
public class TestDetectGraphicsDevices { private DetectGraphicsDevices detectGraphicsDevice; private static final String DISPLAY_0 = "Monitor0"; @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); detectGraphicsDevice = DetectGraphicsDevices.getInstance(); } @Test public void testIsGraphicsEnvHeadless() { if (detectGraphicsDevice.isGraphicsEnvHeadless()) { Assert.assertEquals(detectGraphicsDevice.isGraphicsEnvHeadless(), true); } else { Assert.assertEquals(detectGraphicsDevice.isGraphicsEnvHeadless(), false); } } @Test public void testGetNumberGraphicsDevices() { Assert.assertTrue(detectGraphicsDevice.getNumberGraphicsDevices() > 0); } @Test public void testGetGraphicsDevice() { Assert.assertTrue(detectGraphicsDevice.getGraphicsDevice().length > 0); } @Test(enabled=false) public void testGetSingleGraphicDeviceConfig() { if (!detectGraphicsDevice.isGraphicsEnvHeadless() && DetectGraphicsDevices.isMac()) { Assert.assertNotNull(detectGraphicsDevice.getSingleGraphicDeviceConfig(DISPLAY_0)); } } @Test public void testGetGraphicDeviceNames() { Assert.assertTrue(detectGraphicsDevice.getGraphicDeviceNames().size() >= 0); } }
false
mctcore_src_test_java_gov_nasa_arc_mct_components_TestDetectGraphicsDevices.java
303
public final class TextInitializer implements PropertyEditor<Object> { String visualComponentInitialValue = null; /** * Create a property editor that initializes a field. * @param visualComponentInitialValue the text value */ public TextInitializer(String visualComponentInitialValue) { this.visualComponentInitialValue = visualComponentInitialValue; } @Override public String getValue() { throw new UnsupportedOperationException(); } @Override public String getAsText() { return visualComponentInitialValue; } @Override public void setAsText(String text) throws IllegalArgumentException { throw new UnsupportedOperationException(); } @Override public void setValue(Object value) throws IllegalArgumentException { throw new UnsupportedOperationException(); } @Override public List<Object> getTags() { throw new UnsupportedOperationException(); } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_TextInitializer.java
304
public interface TimeConversion { /** * Convert this object to the UNIX epoch. * @param encodedTime some encoded representation of a time * @return milliseconds elapsed since start of UNIX epoch */ public long convertToUNIXTime(String encodedTime); /** * Convert the supplied UNIX epoch time to whatever * time representation this conversion generally supports. * @param localTimeMillis milliseconds elapsed wince start of UNIX epoch * @return an encoded representation of the time */ public String convertFromUNIXTime(long localTimeMillis); /** * Should this be interpreted as a timer? (otherwise, it will * be interpreted as a clock - for instance, negative numbers * will be rendered as before the epoch, instead of as * negative times.) * @return true if a timer, false if a clock */ public boolean isTimer(); }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_TimeConversion.java
305
public class CollectionComponent extends AbstractComponent { }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_collection_CollectionComponent.java
306
public interface Group { }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_collection_Group.java
307
public final class ComponentModelUtil { /** * Private constructor. */ private ComponentModelUtil() { } /** * Computes the set of elements contained in either of the two specified sets but not in both. * That is, set diff1 = set1 - set2 and diff2 = set2 - set1. * @param <T> - static generic type reference * @param set1 - First set. * @param set2 - Second set. * @param diff1 pre-condition: non null; post-condition: contains the asymmetric set difference set1 - set2. * @param diff2 pre-condition: non null; post-condition: contains the asymmetric set difference set2 - set1. * @param set pre-condition: non-null; post-condition:unspecified. This Set allows a comparator to be specified. * */ public static<T> void computeAsymmetricSetDifferences(final Collection<T> set1, final Collection<T> set2, final Collection<T> diff1, final Collection<T> diff2, final Collection<T> set) { if (set1 == null && set2 == null) return; if (set1 == null) { diff2.addAll(set2); return; } if (set2 == null) { diff1.addAll(set1); return; } set.removeAll(set2); diff1.addAll(set); set.clear(); set.addAll(set2); set.removeAll(set1); diff2.addAll(set); } /** * Computes the set of elements contained in either of the two specified sets but not in both. * That is, set diff1 = set1 - set2 and diff2 = set2 - set1. * @param <T> - static generic type reference * @param set1 - First set. * @param set2 - Second set. * @param diff1 pre-condition: non null; post-condition: contains the asymmetric set difference set1 - set2. * @param diff2 pre-condition: non null; post-condition: contains the asymmetric set difference set2 - set1. */ public static<T> void computeAsymmetricSetDifferences(final Collection<T> set1, final Collection<T> set2, final Collection<T> diff1, final Collection<T> diff2) { ComponentModelUtil.computeAsymmetricSetDifferences(set1, set2, diff1, diff2, set1 == null ? null : new ArrayList<T>(set1)); } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_util_ComponentModelUtil.java
308
public interface ConnectionStatus { /** * Enum for connection status. * */ enum Status { CONNECTED, DISCONNECTED, CLOSED } /** * Gets the connection status. * @return Status. */ public Status getConnectionStatus(); /** * Connect status. */ public void connect(); /** * Stop status. */ public void stop(); /** * Add observer. * @param listener observer. */ public void addObserver(Observer listener); /** * Deletes observer. * @param o - Deletes observer object */ public void deleteObserver(Observer o); }
false
mctcore_src_main_java_gov_nasa_arc_mct_connection_ConnectionStatus.java
309
enum Status { CONNECTED, DISCONNECTED, CLOSED }
false
mctcore_src_main_java_gov_nasa_arc_mct_connection_ConnectionStatus.java
310
public class GlobalContext { private static final MCTLogger ADVISORY_SERVICE_LOGGER = MCTLogger.getLogger("gov.nasa.jsc.advisory.service"); private static final GlobalContext instance = new GlobalContext(); private IIdentityManager idManager; private final UserProfile userProfile = new UserProfile(); /** * Gets the singleton instance of the global context. * * @return the global context */ public static GlobalContext getGlobalContext() { return instance; } /** * Creates a global context. This should be protected or private to enforce * the singleton pattern. */ private GlobalContext() { // } /** * Gets the current user. The user is set by a JVM property that is passed * in by the DNAV interface or a command-line parameter. * * @return the current user */ public User getUser() { return userProfile.getUser(); } /** * Change the current user. This is called by the shift change detection * mechanism. * * @param user * the new user * @param taskRunnable * the task to run after the user is switched */ public void switchUser(final User user, final Runnable taskRunnable) { ADVISORY_SERVICE_LOGGER.info("Switching user to: " + (user == null ? "null" : user.getUserId())); if (taskRunnable != null) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { userProfile.setUser(user); taskRunnable.run(); } }); } else { userProfile.setUser(user); } } /** * Gets the identity manager instance. * @return IIdentityManager. */ public IIdentityManager getIdManager() { return idManager; } /** * Sets the identity manager instance. * @param idManager - Sets the local identity manager to the instance variable. */ public void setIdManager(IIdentityManager idManager) { this.idManager = idManager; } }
false
mctcore_src_main_java_gov_nasa_arc_mct_context_GlobalContext.java
311
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { userProfile.setUser(user); taskRunnable.run(); } });
false
mctcore_src_main_java_gov_nasa_arc_mct_context_GlobalContext.java
312
public class GlobalContextTest { @Mock private User user1; @Mock private User user2; @Mock private IIdentityManager identityManager; @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); Mockito.when(user1.getUserId()).thenReturn("asi"); Mockito.when(user2.getUserId()).thenReturn("jimbooster"); } @Test public void switchUserTest() { final CyclicBarrier barrier = new CyclicBarrier(2); final AtomicBoolean runnableRan = new AtomicBoolean(false); final Runnable testRunnable = new Runnable() { @Override public void run() { try { runnableRan.set(true); barrier.await(); } catch (InterruptedException e) { throw new AssertionError(e); } catch (BrokenBarrierException e) { throw new AssertionError(e); } } }; GlobalContext.getGlobalContext().switchUser(user1, null); assertSame(GlobalContext.getGlobalContext().getUser(), user1); Thread t = new Thread(new Runnable() { @Override public void run() { GlobalContext.getGlobalContext().switchUser(user2, testRunnable); } }); t.start(); try { barrier.await(); } catch (InterruptedException e) { throw new AssertionError(e); } catch (BrokenBarrierException e) { throw new AssertionError(e); } assertTrue(runnableRan.get()); } @Test public void testGettersSetters() { GlobalContext context = GlobalContext.getGlobalContext(); assertNull(context.getIdManager()); context.setIdManager(identityManager); assertSame(context.getIdManager(), identityManager); } }
false
mctcore_src_test_java_gov_nasa_arc_mct_context_GlobalContextTest.java
313
final Runnable testRunnable = new Runnable() { @Override public void run() { try { runnableRan.set(true); barrier.await(); } catch (InterruptedException e) { throw new AssertionError(e); } catch (BrokenBarrierException e) { throw new AssertionError(e); } } };
false
mctcore_src_test_java_gov_nasa_arc_mct_context_GlobalContextTest.java
314
Thread t = new Thread(new Runnable() { @Override public void run() { GlobalContext.getGlobalContext().switchUser(user2, testRunnable); } });
false
mctcore_src_test_java_gov_nasa_arc_mct_context_GlobalContextTest.java
315
public class BrokenComponent extends AbstractComponent { @Override public boolean isLeaf() { return true; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_components_BrokenComponent.java
316
public class BrokenComponentTest { @Mock private AbstractComponent mockComponent; @Mock private Platform mockPlatform; @Mock private PolicyManager mockPolicyManager; @BeforeMethod protected void postSetup() { MockitoAnnotations.initMocks(this); (new PlatformAccess()).setPlatform(mockPlatform); Mockito.when(mockPlatform.getPolicyManager()).thenReturn(mockPolicyManager); Mockito.when(mockPolicyManager.execute(Mockito.anyString(), Mockito.any(PolicyContext.class))).thenReturn(new ExecutionResult(null,true,"")); Mockito.when(mockComponent.getComponentId()).thenReturn("abc"); } @AfterMethod protected void tearDown() { (new PlatformAccess()).setPlatform(null); } @Test /** * do some simple verifications on Broken Component */ public void verifyBrokenComponent() { BrokenComponent bc = new BrokenComponent(); Assert.assertTrue(bc.isLeaf(),"broken component should be a leaf"); // verify that children cannot be added to the model try { bc.addDelegateComponent(mockComponent); Assert.fail("children cannot be added to the broken component model"); } catch (UnsupportedOperationException uoe) { } // verify that children cannot be added to the model try { bc.addDelegateComponents(0, Collections.<AbstractComponent> singleton(mockComponent)); Assert.fail("children cannot be added to the broken component model"); } catch (UnsupportedOperationException uoe) { } // create a new instance of Inspector View, this just verifies the view works, no exceptions BrokenInfoPanel panel = new BrokenInfoPanel(bc,new ViewInfo(BrokenInfoPanel.class,"",ViewType.INSPECTOR)); Assert.assertNotNull(panel); } }
false
mctCoreTaxonomyProvider_src_test_java_gov_nasa_arc_mct_core_components_BrokenComponentTest.java
317
@SuppressWarnings("serial") public final class BrokenInfoPanel extends View { private static ResourceBundle bundle = ResourceBundle.getBundle("CoreTaxonomyResourceBundle"); //NOI18N public static final String VIEW_NAME = bundle.getString("BrokenInspectorViewName"); public BrokenInfoPanel(AbstractComponent ac, ViewInfo vi) { super(ac,vi); JPanel view = new JPanel(); view.setLayout(new BoxLayout(view, BoxLayout.Y_AXIS)); // Add the header for this view manifestation. view.add(createHeaderRow(bundle.getString("BrokenInspectorInformation"), Color.red, 15)); //NOI18N view.add(new JLabel()); setLayout(new BorderLayout()); add(view, BorderLayout.NORTH); } // The following are the utility methods for formatting this // info view manifestation. // Creates a formatted JPanel that contains the header in a JLabel private JPanel createHeaderRow(String title, Color color, float size) { JPanel panel = new JPanel(new BorderLayout()); JLabel label = new JLabel(title); label.setFont(label.getFont().deriveFont(Font.BOLD, size)); label.setForeground(color); panel.add(label, BorderLayout.WEST); return panel; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_components_BrokenInfoPanel.java
318
public class MineTaxonomyComponent extends AbstractComponent { public MineTaxonomyComponent() { } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_components_MineTaxonomyComponent.java
319
public class TelemetryDataTaxonomyComponent extends AbstractComponent { public TelemetryDataTaxonomyComponent() { } /** * For internal use only * * @param id * @param modelRole */ public TelemetryDataTaxonomyComponent(String id) { setId(id); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_components_TelemetryDataTaxonomyComponent.java
320
public final class TelemetryDisciplineComponent extends AbstractComponent implements Group { private static final String OWNER = ComponentSecurityProperties.parseNameValuefromPolicy("discipline.owner"); /** * For internal use only. */ public TelemetryDisciplineComponent() { setOwner(OWNER); } @Override protected <T> T handleGetCapability(Class<T> capability) { if (Group.class.isAssignableFrom(capability)) { return capability.cast(this); } return null; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_components_TelemetryDisciplineComponent.java
321
public class TelemetryUserDropBoxComponent extends AbstractComponent { public TelemetryUserDropBoxComponent() { } public void dropDelegateComponents(Collection<AbstractComponent> childComponents) { addDelegateComponents(childComponents); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_components_TelemetryUserDropBoxComponent.java
322
public class AllCannotBeInspectedPolicy implements Policy { private static final String EM_STR = ""; @Override public ExecutionResult execute(PolicyContext context) { AbstractComponent rootComponent = PlatformAccess.getPlatform().getRootComponent(); ExecutionResult trueResult = new ExecutionResult(context, true, EM_STR); TelemetryDataTaxonomyComponent component = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), TelemetryDataTaxonomyComponent.class); if (component == null || component != rootComponent) return trueResult; ViewType viewType = context.getProperty(PolicyContext.PropertyName.VIEW_TYPE.getName(), ViewType.class); return viewType != ViewType.OBJECT ? trueResult : new ExecutionResult(context, false, EM_STR); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_AllCannotBeInspectedPolicy.java
323
public class CanDeleteComponentPolicy implements Policy { public CanDeleteComponentPolicy() { } @Override public ExecutionResult execute(PolicyContext context) { ExecutionResult result = new ExecutionResult(context); result.setStatus(true); AbstractComponent component = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class); if (component instanceof MineTaxonomyComponent) { result.setStatus(false); result.setMessage("Cannot delete My Sandbox."); } else if (!component.getOwner().equals(PlatformAccess.getPlatform().getCurrentUser().getUserId())) { result.setStatus(false); result.setMessage(component.getDisplayName() + " cannot be deleted because it is owned by " + component.getOwner() + "."); } return result; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_CanDeleteComponentPolicy.java
324
public class CanDeleteComponentPolicyTest { private static final String USER = "asi"; private CanDeleteComponentPolicy policy = new CanDeleteComponentPolicy(); @Mock private AbstractComponent mockPrivateComponent; @Mock private AbstractComponent mockPrivateComponentWithDifferentOwner; @Mock private Platform mockPlatform; @Mock private User user; @BeforeClass public void setUp() { MockitoAnnotations.initMocks(this); Mockito.when(user.getUserId()).thenReturn(USER); Mockito.when(mockPrivateComponent.getOwner()).thenReturn(USER); Mockito.when(mockPrivateComponentWithDifferentOwner.getOwner()).thenReturn("some other user"); Mockito.when(mockPlatform.getCurrentUser()).thenReturn(user); (new PlatformAccess()).setPlatform(mockPlatform); } @AfterTest public void shutDown() { } @Test public void testCanDeleteComponentPolicy() { PolicyContext context = new PolicyContext(); context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), mockPrivateComponent); ExecutionResult exResult = policy.execute(context); Assert.assertTrue(exResult.getStatus()); context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), mockPrivateComponentWithDifferentOwner); exResult = policy.execute(context); Assert.assertFalse(exResult.getStatus()); MineTaxonomyComponent mockMine = Mockito.mock(MineTaxonomyComponent.class); context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), mockMine); exResult = policy.execute(context); Assert.assertFalse(exResult.getStatus()); } }
false
mctCoreTaxonomyProvider_src_test_java_gov_nasa_arc_mct_core_policy_CanDeleteComponentPolicyTest.java
325
public class CanRemoveComponentPolicy implements Policy { public CanRemoveComponentPolicy() { } @Override public ExecutionResult execute(PolicyContext context) { ExecutionResult result = new ExecutionResult(context); result.setStatus(true); AbstractComponent component = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class); if (component instanceof TelemetryUserDropBoxComponent) { String runtimeUser = PlatformAccess.getPlatform().getCurrentUser().getUserId(); String usersDropBoxName = runtimeUser+"'s Drop Box"; if (component.getCreator().equals(runtimeUser) && component.getDisplayName().equals(usersDropBoxName)) { return result; } else { result.setStatus(false); result.setMessage(component.getDisplayName() + " cannot remove from a DropBox because the runtime user is not the DropBox owner."); } } return result; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_CanRemoveComponentPolicy.java
326
public class CannotDragMySandbox implements Policy { @Override public ExecutionResult execute(PolicyContext context) { @SuppressWarnings("unchecked") Collection<AbstractComponent> sourceComponents = context.getProperty(PolicyContext.PropertyName.SOURCE_COMPONENTS.getName(), Collection.class); assert sourceComponents != null : "source components must be used for this policy"; for (AbstractComponent component : sourceComponents) { if (MineTaxonomyComponent.class.isAssignableFrom(component.getClass())) { return new ExecutionResult(context, false, "cannot contain my sandbox"); } } return new ExecutionResult(context, true, ""); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_CannotDragMySandbox.java
327
public class CannotDragMySandboxTest { @Mock private MineTaxonomyComponent mySandbox; @Mock private AbstractComponent component; private Policy policy; @BeforeMethod public void init() { MockitoAnnotations.initMocks(this); policy = new CannotDragMySandbox(); } @Test public void testDraggingPolicy() { List<AbstractComponent> components = new ArrayList<AbstractComponent>(); PolicyContext context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.SOURCE_COMPONENTS.getName(),components); // verify my sandbox cannot be contained components.add(mySandbox); components.add(component); Assert.assertFalse(policy.execute(context).getStatus()); components.clear(); // verify normal components can be contained components.add(component); Assert.assertTrue(policy.execute(context).getStatus()); } }
false
mctCoreTaxonomyProvider_src_test_java_gov_nasa_arc_mct_core_policy_CannotDragMySandboxTest.java
328
public class CantDuplicateDropBoxesPolicy implements Policy { /* (non-Javadoc) * @see gov.nasa.arc.mct.policy.Policy#execute(gov.nasa.arc.mct.policy.PolicyContext) */ @Override public ExecutionResult execute(PolicyContext context) { AbstractComponent component = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class); if (component.getClass().equals(TelemetryUserDropBoxComponent.class)) { return new ExecutionResult(context, false, "Can't duplicate Drop Boxes."); } return new ExecutionResult(context, true, ""); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_CantDuplicateDropBoxesPolicy.java
329
public class ChangeOwnershipPolicy implements Policy{ @Override public ExecutionResult execute(PolicyContext context) { AbstractComponent target = context.getProperty("TARGET", AbstractComponent.class); if (canChangeOwnership(target)) { return new ExecutionResult(context, true, ""); } return new ExecutionResult(context, false, "Permission denied on " + target.getDisplayName()); } private boolean canChangeOwnership(AbstractComponent component) { return RoleAccess.canChangeOwner(component, PlatformAccess.getPlatform().getCurrentUser()); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_ChangeOwnershipPolicy.java
330
public class CheckBuiltinComponentPolicy implements Policy { @Override public ExecutionResult execute(PolicyContext context) { ExecutionResult trueResult = new ExecutionResult(context, true, ""); AbstractComponent target = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class); String displayName = target.getDisplayName(); if (target instanceof MineTaxonomyComponent) return new ExecutionResult(context, false, displayName + " cannot be modified."); return trueResult; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_CheckBuiltinComponentPolicy.java
331
public class CheckComponentOwnerIsUserPolicy implements Policy { @Override public ExecutionResult execute(PolicyContext context) { AbstractComponent component = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class); if (component == null) return new ExecutionResult(context, false, "Invalid component."); // Allow dropping into every object type owned by everyone and duplicating every object type owned by everyone (except drop boxes) // if (!component.getOwner().equals("*") && !component.getOwner().equals(PlatformAccess.getPlatform().getCurrentUser().getUserId())) return new ExecutionResult(context, false, "User does not own this component."); return new ExecutionResult(context, true, ""); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_CheckComponentOwnerIsUserPolicy.java
332
public class DefaultViewForTaxonomyNode implements Policy { @Override public ExecutionResult execute(PolicyContext context) { boolean result = true; AbstractComponent targetComponent = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class); if (TelemetryDataTaxonomyComponent.class.isAssignableFrom(targetComponent.getClass())) { ViewInfo viewInfo = context.getProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), ViewInfo.class); if (viewInfo.getViewType() == ViewType.OBJECT) { result = FeedView.class.isAssignableFrom(viewInfo.getViewClass()); } } return new ExecutionResult(context, result, null); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_DefaultViewForTaxonomyNode.java
333
public class DisciplineUsersViewControlPolicy implements Policy { private static final String GA_ROLE = "GA"; private static final String EM_STRING = ""; @Override public ExecutionResult execute(PolicyContext context) { ExecutionResult trueResult = new ExecutionResult(context, true, EM_STRING); AbstractComponent component = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class); if (!(component instanceof TelemetryDisciplineComponent)) return trueResult; ViewInfo view = context.getProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), ViewInfo.class); if (!view.getViewClass().equals(UsersManifestation.class)) return trueResult; User currentUser = PlatformAccess.getPlatform().getCurrentUser(); if (!RoleAccess.hasRole(currentUser, GA_ROLE)) return new ExecutionResult(context, false, "Needs GA role to access " + component.getDisplayName()); else return trueResult; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_DisciplineUsersViewControlPolicy.java
334
public final class DropboxFilterViewPolicy implements Policy { private final String[] dropBoxComponentTypes = {TelemetryUserDropBoxComponent.class.getName()}; @Override public ExecutionResult execute(PolicyContext context) { ExecutionResult trueResult = new ExecutionResult(context, true, ""); AbstractComponent component = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class); if (!checkArguments(context, component)) return trueResult; // pass it over to the next policy in the chain ViewType viewType = context .getProperty(PolicyContext.PropertyName.VIEW_TYPE.getName(), ViewType.class); ViewInfo targetViewInfo = context.getProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), ViewInfo.class); if (viewType == ViewType.OBJECT || viewType == ViewType.CENTER) { if (hasPermission(component)) { if (DropboxCanvasView.class.isAssignableFrom(targetViewInfo.getViewClass())) return new ExecutionResult(context, false, ""); } else { if (!(DropboxCanvasView.class.isAssignableFrom(targetViewInfo.getViewClass()))) return new ExecutionResult(context, false, ""); } } return trueResult; } private boolean hasPermission(AbstractComponent component) { return PlatformAccess.getPlatform().getCurrentUser().getUserId().equals(component.getOwner()); } /* * Checks whether context contains the correct set of arguments to process this policy. */ private boolean checkArguments(PolicyContext context, AbstractComponent component) { if (context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class) == null) return false; if (!Arrays.asList(dropBoxComponentTypes).contains(component.getClass().getName())) return false; return !(context.getProperty(PolicyContext.PropertyName.VIEW_TYPE.getName(), ViewType.class) != ViewType.CENTER && context.getProperty(PolicyContext.PropertyName.VIEW_TYPE.getName(), ViewType.class) != ViewType.OBJECT); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_DropboxFilterViewPolicy.java
335
public class LeafCannotAddChildDetectionPolicy implements Policy { @Override public ExecutionResult execute(PolicyContext context) { AbstractComponent component = context.getProperty("TARGET", AbstractComponent.class); // Children are only allowed if the component is not a leaf boolean allowed = !component.isLeaf(); return new ExecutionResult(context, allowed, "You cannot add a child component to a leaf component"); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_LeafCannotAddChildDetectionPolicy.java
336
public class ObjectPermissionPolicy implements Policy { private static String ANY_USER = "*"; @Override public ExecutionResult execute(PolicyContext context) { ExecutionResult result = new ExecutionResult(context, true, ""); AbstractComponent component = context.getProperty("TARGET", AbstractComponent.class); char action = (Character) context.getProperty("ACTION"); switch(action) { case 'w': result.setStatus(isComposable(component)); break; case 'r': result.setStatus(isAccessible(component)); break; default: break; } if (!result.getStatus()) result.setMessage("Permission denied on " + component.getDisplayName()); return result; } public boolean isComposable(AbstractComponent component) { User currentUser = PlatformAccess.getPlatform().getCurrentUser(); return component.getOwner().equals(ANY_USER) || RoleAccess.canChangeOwner(component, currentUser); } public boolean isAccessible (AbstractComponent component) { return true; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_ObjectPermissionPolicy.java
337
public class PreferredViewPolicy implements Policy { @Override public ExecutionResult execute(PolicyContext context) { return new ExecutionResult(context,true,""); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_PreferredViewPolicy.java
338
public class PreferredViewPolicyTest { @Test public void testPolicy() { PreferredViewPolicy policy = new PreferredViewPolicy(); Assert.assertTrue(policy.execute(null).getStatus()); } }
false
mctCoreTaxonomyProvider_src_test_java_gov_nasa_arc_mct_core_policy_PreferredViewPolicyTest.java
339
public class ReservedWordsNamingPolicy implements Policy { static final String[] RESERVED_WORDS = {"drop box", "dropbox"}; @Override public ExecutionResult execute(PolicyContext context) { ExecutionResult result = new ExecutionResult(context, true, ""); String name = context.getProperty("NAME", String.class); String found = ""; for (int i=0; i<RESERVED_WORDS.length; i++) { if (name.toLowerCase().indexOf(RESERVED_WORDS[i].toLowerCase()) > -1) { result.setStatus(false); found = RESERVED_WORDS[i]; } } if (!result.getStatus()) result.setMessage("Name must not contain the words \"" + found + "\""); return result; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_ReservedWordsNamingPolicy.java
340
public class ReservedWordsNamingPolicyTest { private static final String TEST_STRING_SHOULD_FAIL = "UserDropBox"; private static final String TEST_STRING_SHOULD_PASS = "UsersBox"; private ReservedWordsNamingPolicy policy = new ReservedWordsNamingPolicy(); @BeforeClass public void setUp() { } @AfterTest public void shutDown() { } @Test public void testReservedWordsNamingPolicy() { PolicyContext context = new PolicyContext(); context.setProperty("NAME", TEST_STRING_SHOULD_FAIL); ExecutionResult exResult = policy.execute(context); Assert.assertFalse(exResult.getStatus()); context.setProperty("NAME", TEST_STRING_SHOULD_PASS); exResult = policy.execute(context); Assert.assertTrue(exResult.getStatus()); } }
false
mctCoreTaxonomyProvider_src_test_java_gov_nasa_arc_mct_core_policy_ReservedWordsNamingPolicyTest.java
341
public class SameComponentsCannotBeLinkedPolicy implements Policy { @SuppressWarnings("unchecked") @Override public ExecutionResult execute(PolicyContext context) { char action = context.getProperty("ACTION", Character.class); if (action != 'w') return new ExecutionResult(context, true, ""); AbstractComponent targetComponent = (AbstractComponent) context.getProperty("TARGET"); // Context stores properties untyped, so we're forced to do an unchecked conversion here. Collection<AbstractComponent> sourceComponents = (Collection<AbstractComponent>) context.getProperty("SOURCES"); if (sourceComponents != null) { for (AbstractComponent sourceComponent : sourceComponents) { if(isSameComponent(sourceComponent, targetComponent)) { return new ExecutionResult(context, false, " Cannot drop " + sourceComponent.getDisplayName() + " onto itself."); } } } return new ExecutionResult(context, true, ""); } private boolean isSameComponent(AbstractComponent source, AbstractComponent target) { // Compares two component Ids return source.getId().equals(target.getId()); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_policy_SameComponentsCannotBeLinkedPolicy.java
342
public class TestDefaultViewForTaxonomy { @DataProvider(name="policies") Object[][] generateData() { AbstractComponent[] components = new AbstractComponent[] { new AbstractComponent() { }, new TelemetryDataTaxonomyComponent() }; ViewInfo[] infos = new ViewInfo[] { new ViewInfo(FeedViewDerived.class,"view",ViewType.OBJECT), new ViewInfo(FeedViewDerived.class, "view", ViewType.EMBEDDED), new ViewInfo(NormalView.class, "view", ViewType.OBJECT) }; Object[][] outer = new Object[components.length*infos.length][]; for (int i=0; i < components.length; i++) { for (int j = 0; j < infos.length; j++) { outer[(i*infos.length)+j] = new Object[] {components[i], infos[j], !(components[i].getClass().equals(TelemetryDataTaxonomyComponent.class)&& !infos[j].getViewClass().equals(FeedViewDerived.class)&& infos[j].getViewType()==ViewType.OBJECT)}; } } return outer; } private static final class FeedViewDerived extends FeedView { /** * */ private static final long serialVersionUID = 1L; public FeedViewDerived(AbstractComponent ac, ViewInfo vi) { super(null); } @Override public void updateFromFeed(Map<String, List<Map<String, String>>> data) { } @Override public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) { } @Override public Collection<FeedProvider> getVisibleFeedProviders() { return null; } } public static final class NormalView extends View{ public NormalView(AbstractComponent ac, ViewInfo vi) {} private static final long serialVersionUID = 1L; } @Test(dataProvider="policies") public void testPolicy(AbstractComponent ac, ViewInfo vi, boolean expectedResult) { DefaultViewForTaxonomyNode policy = new DefaultViewForTaxonomyNode(); PolicyContext context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), ac); context.setProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), vi); Assert.assertEquals(policy.execute(context).getStatus(), expectedResult); } }
false
mctCoreTaxonomyProvider_src_test_java_gov_nasa_arc_mct_core_policy_TestDefaultViewForTaxonomy.java
343
new AbstractComponent() { },
false
mctCoreTaxonomyProvider_src_test_java_gov_nasa_arc_mct_core_policy_TestDefaultViewForTaxonomy.java
344
private static final class FeedViewDerived extends FeedView { /** * */ private static final long serialVersionUID = 1L; public FeedViewDerived(AbstractComponent ac, ViewInfo vi) { super(null); } @Override public void updateFromFeed(Map<String, List<Map<String, String>>> data) { } @Override public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) { } @Override public Collection<FeedProvider> getVisibleFeedProviders() { return null; } }
false
mctCoreTaxonomyProvider_src_test_java_gov_nasa_arc_mct_core_policy_TestDefaultViewForTaxonomy.java
345
public static final class NormalView extends View{ public NormalView(AbstractComponent ac, ViewInfo vi) {} private static final long serialVersionUID = 1L; }
false
mctCoreTaxonomyProvider_src_test_java_gov_nasa_arc_mct_core_policy_TestDefaultViewForTaxonomy.java
346
public class TestSameComponentCannotBeLinked { private SameComponentsCannotBeLinkedPolicy policy = new SameComponentsCannotBeLinkedPolicy(); @Test public void test() { AbstractComponent componentA = Mockito.mock(AbstractComponent.class); AbstractComponent componentB = Mockito.mock(AbstractComponent.class); Mockito.when(componentA.getId()).thenReturn("A"); Mockito.when(componentB.getId()).thenReturn("B"); PolicyContext context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.ACTION.getName(), 'w'); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), componentA); context.setProperty(PolicyContext.PropertyName.SOURCE_COMPONENTS.getName(), Collections.singletonList(componentB)); Assert.assertTrue(policy.execute(context).getStatus()); } }
false
mctCoreTaxonomyProvider_src_test_java_gov_nasa_arc_mct_core_policy_TestSameComponentCannotBeLinked.java
347
public class CoreComponentProvider extends AbstractComponentProvider implements DefaultComponentProvider { private static final ResourceBundle resource = ResourceBundle.getBundle("CoreTaxonomyResourceBundle"); // NO18N @Override public Collection<ComponentTypeInfo> getComponentTypes() { List<ComponentTypeInfo> compInfos = new ArrayList<ComponentTypeInfo>(); ComponentTypeInfo typeInfo = new ComponentTypeInfo(resource.getString("discipline_component_display_name"), resource .getString("discipline_component_description"), TelemetryDisciplineComponent.class, false); compInfos.add(typeInfo); typeInfo = new ComponentTypeInfo(resource.getString("user_dropbox_component_display_name"), resource .getString("user_dropbox_component_description"), TelemetryUserDropBoxComponent.class, false); compInfos.add(typeInfo); typeInfo = new ComponentTypeInfo(resource.getString("mine_component_display_name"), resource .getString("mine_component_description"), MineTaxonomyComponent.class, false); compInfos.add(typeInfo); typeInfo = new ComponentTypeInfo(resource.getString("broken_component_display_name"), resource .getString("broken_component_description"), BrokenComponent.class, false); compInfos.add(typeInfo); typeInfo = new ComponentTypeInfo(resource.getString("data_taxonomy_component_type_display_name"), resource.getString("data_taxonomy_component_type_description"), TelemetryDataTaxonomyComponent.class, false); compInfos.add(typeInfo); return compInfos; } @Override public Collection<ViewInfo> getViews(String componentTypeId) { if (BrokenComponent.class.getName().equals(componentTypeId)) { return Collections.singleton(new ViewInfo(BrokenInfoPanel.class, resource.getString("BrokenInspectorViewName"),ViewType.OBJECT)); //NOI18N } else if (TelemetryUserDropBoxComponent.class.getName().equals(componentTypeId)) { return Arrays.asList( new ViewInfo(DropboxCanvasView.class, resource.getString("DropBoxViewName"),ViewType.OBJECT), new ViewInfo(DropboxCanvasView.class, resource.getString("DropBoxViewName"),ViewType.CENTER)); } else if (TelemetryDisciplineComponent.class.getName().equals(componentTypeId)) { return Collections.singleton(new ViewInfo(UsersManifestation.class, "Users", ViewType.OBJECT)); } return Collections.emptyList(); } @Override public Collection<PolicyInfo> getPolicyInfos() { return Arrays.asList( new PolicyInfo(CategoryType.OBJECT_INSPECTION_POLICY_CATEGORY.getKey(), ObjectPermissionPolicy.class), new PolicyInfo(CategoryType.COMPOSITION_POLICY_CATEGORY.getKey(), LeafCannotAddChildDetectionPolicy.class), new PolicyInfo(CategoryType.ACCEPT_DELEGATE_MODEL_CATEGORY.getKey(), LeafCannotAddChildDetectionPolicy.class, SameComponentsCannotBeLinkedPolicy.class), new PolicyInfo(CategoryType.COMPONENT_NAMING_POLICY_CATEGORY.getKey(), ReservedWordsNamingPolicy.class), new PolicyInfo(CategoryType.ALLOW_COMPONENT_RENAME_POLICY_CATEGORY.getKey(), ChangeOwnershipPolicy.class, CheckBuiltinComponentPolicy.class, ReservedWordsNamingPolicy.class, ObjectPermissionPolicy.class), new PolicyInfo(CategoryType.FILTER_VIEW_ROLE.getKey(), DropboxFilterViewPolicy.class, AllCannotBeInspectedPolicy.class), new PolicyInfo(CategoryType.PREFERRED_VIEW.getKey(), PreferredViewPolicy.class), new PolicyInfo(CategoryType.CAN_DELETE_COMPONENT_POLICY_CATEGORY.getKey(), CanDeleteComponentPolicy.class), new PolicyInfo(CategoryType.CAN_REMOVE_MANIFESTATION_CATEGORY.getKey(), CanRemoveComponentPolicy.class), new PolicyInfo(CategoryType.CAN_DUPLICATE_OBJECT.getKey(), CantDuplicateDropBoxesPolicy.class, CheckComponentOwnerIsUserPolicy.class), new PolicyInfo(CategoryType.COMPOSITION_POLICY_CATEGORY.getKey(), CheckComponentOwnerIsUserPolicy.class), new PolicyInfo(CategoryType.CAN_OBJECT_BE_CONTAINED_CATEGORY.getKey(), CannotDragMySandbox.class), new PolicyInfo(CategoryType.PREFERRED_VIEW.getKey(),DefaultViewForTaxonomyNode.class), new PolicyInfo(CategoryType.SHOW_HIDE_CTRL_MANIFESTATION.getKey(), DisciplineUsersViewControlPolicy.class)); } @Override public Class<? extends AbstractComponent> getBrokenComponent() { return BrokenComponent.class; } @Override public ProviderDelegate getProviderDelegate() { return new CoreComponentProviderDelegate(); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_provider_CoreComponentProvider.java
348
public class CoreComponentProviderDelegate extends AbstractProviderDelegate { private static final String DELIM = ","; /* * Mapping * <userid, group> => <created component, set of parent components> */ private Map<String, Map<AbstractComponent, Collection<AbstractComponent>>> map = new HashMap<String, Map<AbstractComponent,Collection<AbstractComponent>>>(); @Override public void userAdded(String session, String userId, String group) { Map<AbstractComponent, Collection<AbstractComponent>> userMap = new HashMap<AbstractComponent, Collection<AbstractComponent>>(); map.put(userId + DELIM + group, userMap); PersistenceProvider persistenceService = PlatformAccess.getPlatform().getPersistenceProvider(); CoreComponentRegistry componentRegistry = PlatformAccess.getPlatform().getComponentRegistry(); AbstractComponent mySandbox = createMySandbox(persistenceService, componentRegistry, session, userMap, userId, group); createUserDropbox(persistenceService, session, userMap, userId, group, mySandbox); } private AbstractComponent createMySandbox(PersistenceProvider persistenceService, CoreComponentRegistry componentRegistry, String session, Map<AbstractComponent, Collection<AbstractComponent>> userMap, String userId, String group) { // Create My Sandbox, which goes under All AbstractComponent all = PlatformAccess.getPlatform().getRootComponent(); AbstractComponent mySandbox = createComponent(MineTaxonomyComponent.class); mySandbox.setDisplayName("My Sandbox"); mySandbox.setOwner(userId); all.addDelegateComponent(mySandbox); userMap.put(mySandbox, Collections.singleton(all)); return mySandbox; } private void createUserDropbox(PersistenceProvider persistenceProvider, String session, Map<AbstractComponent, Collection<AbstractComponent>> userMap, String userId, String group, AbstractComponent mySandbox) { // Create DropBox under My Sandbox AbstractComponent userDropBox = createComponent(TelemetryUserDropBoxComponent.class); userDropBox.setOwner(userId); ComponentInitializer ci = userDropBox.getCapability(ComponentInitializer.class); ci.setCreator(userId); ci.setCreationDate(new Date()); userDropBox.setDisplayName(userId + "'s Drop Box"); mySandbox.addDelegateComponent(userDropBox); Collection<AbstractComponent> dropboxParents = new LinkedHashSet<AbstractComponent>(); dropboxParents.add(mySandbox); userMap.put(userDropBox, dropboxParents); // Place user dropbox under the Discpline's Drop Boxes AbstractComponent dropboxContainer = null;//ownedByAdmin(persistenceProvider.findComponentByName(session, group + "\'s Drop Boxes")); assert dropboxContainer != null : "Cannot find " + group + "'s Drop Boxes component"; dropboxContainer.addDelegateComponents(Collections.singleton(userDropBox)); dropboxParents.add(dropboxContainer); } private AbstractComponent createComponent(Class<? extends AbstractComponent> clazz) { AbstractComponent newInstance = null; try { newInstance = clazz.newInstance(); newInstance.getCapability(ComponentInitializer.class).initialize(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return newInstance; } /* private AbstractComponent ownedByAdmin(Collection<AbstractComponent> components) { for (AbstractComponent component : components) { if (component.getOwner().equals("admin")) return component; } return null; } */ @Override public void userAddedFailed(String userId, String group) { Map<AbstractComponent, Collection<AbstractComponent>> userMap = map.get(userId + DELIM + group); if (userMap == null) return; // Remove connections to parent components for (AbstractComponent child : userMap.keySet()) { for (AbstractComponent parent : userMap.get(child)) { parent.removeDelegateComponent(child); } } // Remove from this delegate's map map.remove(userId + DELIM + group); } @Override public void userAddedSuccessful(String userId, String group) { map.remove(userId + DELIM + group); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_provider_CoreComponentProviderDelegate.java
349
@SuppressWarnings("serial") public class CanvasViewDropActionEvent extends ViewRoleContentDropActionEvent { /** * Creates a new event for a drop action in a canvas view manifestation. * * @param container the container of the canvas view manifestation * @param window the containing window of the canvas view * @param target the target component where the drop occurred * @param sources the source components that have been dropped * @param viewManifestation the view manifestation of the taret component * onto which the sources were dropped */ public CanvasViewDropActionEvent(Container container, Window window, AbstractComponent target, Collection<AbstractComponent> sources, View viewManifestation) { super(container, window, target, sources, viewManifestation); } /** * Creates a new event for a drop action in a canvas view manifestation. * Also specifies the cursor location within the canvas view where the * drop occurred. * * @param container the container of the canvas view manifestation * @param window the containing window of the canvas view * @param target the target component where the drop occurred * @param sources the source components that have been dropped * @param location the location within the canvas view where the drop occurred * @param viewManifestation the view manifestation of the taret component * onto which the sources were dropped */ public CanvasViewDropActionEvent(Container container, Window window, AbstractComponent target, Collection<AbstractComponent> sources, Point location, View viewManifestation) { super(container, window, target, sources, location, viewManifestation); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_CanvasViewDropActionEvent.java
350
@SuppressWarnings("serial") public class DropboxCanvasView extends View { private final JPanel innerContentPanel; private final JLabel statusMessage = new JLabel(); public DropboxCanvasView(AbstractComponent ac, ViewInfo vi) { super(ac,vi); setLayout(new BorderLayout()); innerContentPanel = new JPanel(); innerContentPanel.setDropTarget(new CanvasViewRoleDropTarget()); innerContentPanel.setBackground(UIManager.getColor("background")); innerContentPanel.setBorder(new EmptyBorder(6, 6, 6, 6)); innerContentPanel.add(statusMessage, BorderLayout.CENTER); statusMessage.setFont(innerContentPanel.getFont().deriveFont(Font.BOLD)); add(innerContentPanel); } private final class CanvasViewRoleDropTarget extends DropTarget { public void actionPerformed(CanvasViewDropActionEvent event) { final Container container = event.getContainer(); Collection<AbstractComponent> sourceComponents = event.getSources(); AbstractComponent targetComponent = event.getTarget(); // This is a composing operation PolicyContext context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), targetComponent); context.setProperty(PolicyContext.PropertyName.SOURCE_COMPONENTS.getName(), sourceComponents); context.setProperty(PolicyContext.PropertyName.ACTION.getName(), Character.valueOf('w')); context.setProperty(PolicyContext.PropertyName.VIEW_MANIFESTATION_PROVIDER.getName(), event.getTargetManifestation()); final ExecutionResult result = PlatformAccess.getPlatform().getPolicyManager().execute(PolicyInfo.CategoryType.COMPOSITION_POLICY_CATEGORY.getKey(), context); if (result.getStatus()) { // Persist PersistenceProvider persistenceProvider = PlatformAccess.getPlatform().getPersistenceProvider(); boolean successfulAction = false; try { persistenceProvider.startRelatedOperations(); targetComponent.addDelegateComponents(sourceComponents); targetComponent.save(); successfulAction = true; } finally { persistenceProvider.completeRelatedOperations(successfulAction); } if (successfulAction) { if (event.getTargetManifestation() instanceof DropboxCanvasView) { StringBuilder sentObjects = new StringBuilder(); for (AbstractComponent sourceComponent : sourceComponents) sentObjects.append("\"" + sourceComponent.getExtendedDisplayName() + "\" "); DropboxCanvasView dropboxManifestation = (DropboxCanvasView) event.getTargetManifestation(); dropboxManifestation.statusMessage.setText((sourceComponents.size() == 0) ? "No objects sent." : "Accepted at " + DateFormat.getInstance().format(new Date()) +": "+ sentObjects.toString()); dropboxManifestation.revalidate(); } // Pull tarmanifestInfoget housing window to front. event.getHousingWindow().toFront(); } } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OptionBox.showMessageDialog(container, result.getMessage(), "Composition Error - ", OptionBox.ERROR_MESSAGE); } }); } } private Collection<AbstractComponent> getComponents(View[] views) { List<AbstractComponent> components = new ArrayList<AbstractComponent>(); for (View v:views) { AbstractComponent component = v.getManifestedComponent(); components.add(component); } return components; } @Override public synchronized void drop(DropTargetDropEvent dtde) { Transferable data = dtde.getTransferable(); try { if (!data.isDataFlavorSupported(View.DATA_FLAVOR)) { dtde.rejectDrop(); return; } View[] views = (View[]) data.getTransferData(View.DATA_FLAVOR); AbstractComponent manifestedComponent = getManifestedComponent(); if (manifestedComponent != null) { DropboxCanvasView.this.requestFocusInWindow(); CanvasViewDropActionEvent event = new CanvasViewDropActionEvent(innerContentPanel, SwingUtilities.getWindowAncestor(DropboxCanvasView.this), manifestedComponent, getComponents(views), dtde.getLocation(), DropboxCanvasView.this); actionPerformed(event); } } catch (UnsupportedFlavorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_DropboxCanvasView.java
351
private final class CanvasViewRoleDropTarget extends DropTarget { public void actionPerformed(CanvasViewDropActionEvent event) { final Container container = event.getContainer(); Collection<AbstractComponent> sourceComponents = event.getSources(); AbstractComponent targetComponent = event.getTarget(); // This is a composing operation PolicyContext context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), targetComponent); context.setProperty(PolicyContext.PropertyName.SOURCE_COMPONENTS.getName(), sourceComponents); context.setProperty(PolicyContext.PropertyName.ACTION.getName(), Character.valueOf('w')); context.setProperty(PolicyContext.PropertyName.VIEW_MANIFESTATION_PROVIDER.getName(), event.getTargetManifestation()); final ExecutionResult result = PlatformAccess.getPlatform().getPolicyManager().execute(PolicyInfo.CategoryType.COMPOSITION_POLICY_CATEGORY.getKey(), context); if (result.getStatus()) { // Persist PersistenceProvider persistenceProvider = PlatformAccess.getPlatform().getPersistenceProvider(); boolean successfulAction = false; try { persistenceProvider.startRelatedOperations(); targetComponent.addDelegateComponents(sourceComponents); targetComponent.save(); successfulAction = true; } finally { persistenceProvider.completeRelatedOperations(successfulAction); } if (successfulAction) { if (event.getTargetManifestation() instanceof DropboxCanvasView) { StringBuilder sentObjects = new StringBuilder(); for (AbstractComponent sourceComponent : sourceComponents) sentObjects.append("\"" + sourceComponent.getExtendedDisplayName() + "\" "); DropboxCanvasView dropboxManifestation = (DropboxCanvasView) event.getTargetManifestation(); dropboxManifestation.statusMessage.setText((sourceComponents.size() == 0) ? "No objects sent." : "Accepted at " + DateFormat.getInstance().format(new Date()) +": "+ sentObjects.toString()); dropboxManifestation.revalidate(); } // Pull tarmanifestInfoget housing window to front. event.getHousingWindow().toFront(); } } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OptionBox.showMessageDialog(container, result.getMessage(), "Composition Error - ", OptionBox.ERROR_MESSAGE); } }); } } private Collection<AbstractComponent> getComponents(View[] views) { List<AbstractComponent> components = new ArrayList<AbstractComponent>(); for (View v:views) { AbstractComponent component = v.getManifestedComponent(); components.add(component); } return components; } @Override public synchronized void drop(DropTargetDropEvent dtde) { Transferable data = dtde.getTransferable(); try { if (!data.isDataFlavorSupported(View.DATA_FLAVOR)) { dtde.rejectDrop(); return; } View[] views = (View[]) data.getTransferData(View.DATA_FLAVOR); AbstractComponent manifestedComponent = getManifestedComponent(); if (manifestedComponent != null) { DropboxCanvasView.this.requestFocusInWindow(); CanvasViewDropActionEvent event = new CanvasViewDropActionEvent(innerContentPanel, SwingUtilities.getWindowAncestor(DropboxCanvasView.this), manifestedComponent, getComponents(views), dtde.getLocation(), DropboxCanvasView.this); actionPerformed(event); } } catch (UnsupportedFlavorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_DropboxCanvasView.java
352
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OptionBox.showMessageDialog(container, result.getMessage(), "Composition Error - ", OptionBox.ERROR_MESSAGE); } });
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_DropboxCanvasView.java
353
@SuppressWarnings("serial") public final class UsersManifestation extends View { private UsersPage usersPage; public UsersManifestation(AbstractComponent ac,ViewInfo vi) { super(ac,vi); usersPage = new UsersPage(getManifestedComponent().getDisplayName()); add(usersPage); } @Override protected JComponent initializeControlManifestation() { return new AddUserView(getManifestedComponent()); } @Override public void updateMonitoredGUI() { usersPage.refresh(); } private static final class AddUserView extends JPanel { private static final String PROMPT = "To add a user, type user ID and press Enter"; private static final String EM_STR = ""; private static final long serialVersionUID = 7516917053393171272L; public AddUserView(final AbstractComponent disciplineComponent) { setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10)); final JTextField textField = new JTextField(PROMPT); textField.setOpaque(false); textField.setBorder(new RoundedBorder(textField)); textField.setMargin(new Insets(5, 10, 5, 10)); textField.setColumns(25); textField.setForeground(Color.GRAY); textField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { clear(); } @Override public void focusLost(FocusEvent e) { textField.setText(PROMPT); } private void clear() { if (textField.getText().trim().equals(PROMPT)) { textField.setText(EM_STR); } } }); textField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { submitWhenDone(e); } private void submitWhenDone(KeyEvent e) { if (isEnter(e)) { String userId = textField.getText().trim(); if (userId.length() == 0) return; // Check userId length if (userId.length() > 20) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OptionBox.showMessageDialog(textField, "User ID cannot exceed 20 characters", "Error", JOptionPane.ERROR_MESSAGE); } }); return; } Platform platform = PlatformAccess.getPlatform(); PersistenceProvider persistenceService = platform.getPersistenceProvider(); CoreComponentRegistry componentRegistry = platform.getComponentRegistry(); AbstractComponent mySandbox = componentRegistry.newInstance(MineTaxonomyComponent.class.getName()); ComponentInitializer mysandboxCapability = mySandbox.getCapability(ComponentInitializer.class); mysandboxCapability.setCreator(userId); mysandboxCapability.setOwner(userId); mySandbox.setDisplayName("My Sandbox"); AbstractComponent dropbox = componentRegistry.newInstance(TelemetryUserDropBoxComponent.class.getName()); ComponentInitializer dropboxCapability = dropbox.getCapability(ComponentInitializer.class); dropboxCapability.setCreator("admin"); dropboxCapability.setOwner(userId); dropbox.setDisplayName(userId + "\'s drop box"); persistenceService.addNewUser(userId, disciplineComponent.getDisplayName(), mySandbox, dropbox); disciplineComponent.componentSaved(); textField.setText(EM_STR); } } private boolean isEnter(KeyEvent e) { return e.getKeyCode() == KeyEvent.VK_ENTER; } }); add(textField); } private final class RoundedBorder implements Border { private JTextField textField; public RoundedBorder(JTextField textField) { this.textField = textField; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHints(renderHints); g2.setStroke(new BasicStroke(2f)); int arcWidthAndHeight = height / 2; g2.drawRoundRect(x + 2, y + 2, width - 4, height - 4, arcWidthAndHeight, arcWidthAndHeight); } @Override public Insets getBorderInsets(Component c) { return textField.getMargin(); } @Override public boolean isBorderOpaque() { return false; } } } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_UsersManifestation.java
354
private static final class AddUserView extends JPanel { private static final String PROMPT = "To add a user, type user ID and press Enter"; private static final String EM_STR = ""; private static final long serialVersionUID = 7516917053393171272L; public AddUserView(final AbstractComponent disciplineComponent) { setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10)); final JTextField textField = new JTextField(PROMPT); textField.setOpaque(false); textField.setBorder(new RoundedBorder(textField)); textField.setMargin(new Insets(5, 10, 5, 10)); textField.setColumns(25); textField.setForeground(Color.GRAY); textField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { clear(); } @Override public void focusLost(FocusEvent e) { textField.setText(PROMPT); } private void clear() { if (textField.getText().trim().equals(PROMPT)) { textField.setText(EM_STR); } } }); textField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { submitWhenDone(e); } private void submitWhenDone(KeyEvent e) { if (isEnter(e)) { String userId = textField.getText().trim(); if (userId.length() == 0) return; // Check userId length if (userId.length() > 20) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OptionBox.showMessageDialog(textField, "User ID cannot exceed 20 characters", "Error", JOptionPane.ERROR_MESSAGE); } }); return; } Platform platform = PlatformAccess.getPlatform(); PersistenceProvider persistenceService = platform.getPersistenceProvider(); CoreComponentRegistry componentRegistry = platform.getComponentRegistry(); AbstractComponent mySandbox = componentRegistry.newInstance(MineTaxonomyComponent.class.getName()); ComponentInitializer mysandboxCapability = mySandbox.getCapability(ComponentInitializer.class); mysandboxCapability.setCreator(userId); mysandboxCapability.setOwner(userId); mySandbox.setDisplayName("My Sandbox"); AbstractComponent dropbox = componentRegistry.newInstance(TelemetryUserDropBoxComponent.class.getName()); ComponentInitializer dropboxCapability = dropbox.getCapability(ComponentInitializer.class); dropboxCapability.setCreator("admin"); dropboxCapability.setOwner(userId); dropbox.setDisplayName(userId + "\'s drop box"); persistenceService.addNewUser(userId, disciplineComponent.getDisplayName(), mySandbox, dropbox); disciplineComponent.componentSaved(); textField.setText(EM_STR); } } private boolean isEnter(KeyEvent e) { return e.getKeyCode() == KeyEvent.VK_ENTER; } }); add(textField); } private final class RoundedBorder implements Border { private JTextField textField; public RoundedBorder(JTextField textField) { this.textField = textField; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHints(renderHints); g2.setStroke(new BasicStroke(2f)); int arcWidthAndHeight = height / 2; g2.drawRoundRect(x + 2, y + 2, width - 4, height - 4, arcWidthAndHeight, arcWidthAndHeight); } @Override public Insets getBorderInsets(Component c) { return textField.getMargin(); } @Override public boolean isBorderOpaque() { return false; } } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_UsersManifestation.java
355
textField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { clear(); } @Override public void focusLost(FocusEvent e) { textField.setText(PROMPT); } private void clear() { if (textField.getText().trim().equals(PROMPT)) { textField.setText(EM_STR); } } });
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_UsersManifestation.java
356
textField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { submitWhenDone(e); } private void submitWhenDone(KeyEvent e) { if (isEnter(e)) { String userId = textField.getText().trim(); if (userId.length() == 0) return; // Check userId length if (userId.length() > 20) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OptionBox.showMessageDialog(textField, "User ID cannot exceed 20 characters", "Error", JOptionPane.ERROR_MESSAGE); } }); return; } Platform platform = PlatformAccess.getPlatform(); PersistenceProvider persistenceService = platform.getPersistenceProvider(); CoreComponentRegistry componentRegistry = platform.getComponentRegistry(); AbstractComponent mySandbox = componentRegistry.newInstance(MineTaxonomyComponent.class.getName()); ComponentInitializer mysandboxCapability = mySandbox.getCapability(ComponentInitializer.class); mysandboxCapability.setCreator(userId); mysandboxCapability.setOwner(userId); mySandbox.setDisplayName("My Sandbox"); AbstractComponent dropbox = componentRegistry.newInstance(TelemetryUserDropBoxComponent.class.getName()); ComponentInitializer dropboxCapability = dropbox.getCapability(ComponentInitializer.class); dropboxCapability.setCreator("admin"); dropboxCapability.setOwner(userId); dropbox.setDisplayName(userId + "\'s drop box"); persistenceService.addNewUser(userId, disciplineComponent.getDisplayName(), mySandbox, dropbox); disciplineComponent.componentSaved(); textField.setText(EM_STR); } } private boolean isEnter(KeyEvent e) { return e.getKeyCode() == KeyEvent.VK_ENTER; } });
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_UsersManifestation.java
357
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OptionBox.showMessageDialog(textField, "User ID cannot exceed 20 characters", "Error", JOptionPane.ERROR_MESSAGE); } });
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_UsersManifestation.java
358
private final class RoundedBorder implements Border { private JTextField textField; public RoundedBorder(JTextField textField) { this.textField = textField; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHints(renderHints); g2.setStroke(new BasicStroke(2f)); int arcWidthAndHeight = height / 2; g2.drawRoundRect(x + 2, y + 2, width - 4, height - 4, arcWidthAndHeight, arcWidthAndHeight); } @Override public Insets getBorderInsets(Component c) { return textField.getMargin(); } @Override public boolean isBorderOpaque() { return false; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_UsersManifestation.java
359
@SuppressWarnings("serial") public class UsersPage extends JPanel { private static final ResourceBundle BUNDLE = ResourceBundle.getBundle( UsersPage.class.getName().substring(0, UsersPage.class.getName().lastIndexOf("."))+".Bundle"); private static final String USER_ID = BUNDLE.getString("users.table.column.header.userid"); private static final String GROUP_ID = BUNDLE.getString("users.table.column.header.groupid"); private static final String PRIM_ROLE = "Primary Role"; private DefaultTableModel tableModel; private String discipline; public UsersPage(String discipline) { this.discipline = discipline; tableModel = new DefaultTableModel(new String[]{USER_ID, GROUP_ID, PRIM_ROLE}, 0); refresh(); JTable table = new AlternateRowColorTable(); table.setModel(tableModel); setLayout(new GridLayout(1, 1)); add(new JScrollPane(table)); } public void refresh() { clearRows(); GenericUser genericUser = new GenericUser(); PersistenceProvider persistenceService = PlatformAccess.getPlatform().getPersistenceProvider(); for (String user : persistenceService.getUsersInGroup(discipline)) { genericUser.setUserId(user); genericUser.setDisciplineId(discipline); tableModel.addRow(new Object[]{user, discipline, RoleAccess.getPrimaryRole(genericUser)}); } } private void clearRows() { if (tableModel.getRowCount() > 0) { for (int r = tableModel.getRowCount() - 1; r >= 0; r--) tableModel.removeRow(r); } } private static class GenericUser implements User { private String userId, disciplineId; public void setUserId(String userId) { this.userId = userId; } public void setDisciplineId(String disciplineId) { this.disciplineId = disciplineId; } @Override public String getUserId() { return userId; } @Override public String getDisciplineId() { return disciplineId; } @Override public User getValidUser(String userID) { return null; } } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_UsersPage.java
360
private static class GenericUser implements User { private String userId, disciplineId; public void setUserId(String userId) { this.userId = userId; } public void setDisciplineId(String disciplineId) { this.disciplineId = disciplineId; } @Override public String getUserId() { return userId; } @Override public String getDisciplineId() { return disciplineId; } @Override public User getValidUser(String userID) { return null; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_UsersPage.java
361
@SuppressWarnings("serial") public class ViewRoleContentDropActionEvent extends EventObject { private Container container; private Window window; private AbstractComponent target; private Collection<AbstractComponent> sources; private Point cursorLocation; private View targetViewManifestation; /** * Creates an event corresponding to a drop on the target * component within a container. * * @param container the container component for the target * @param window the window containing the target component * @param target the target component * @param sources the source components being dropped * @param viewManifestation the view manifestation being dropped upon */ public ViewRoleContentDropActionEvent(Container container, Window window, AbstractComponent target, Collection<AbstractComponent> sources, View viewManifestation) { super(container); this.container = container; this.window = window; this.target = target; this.sources = sources; this.targetViewManifestation = viewManifestation; } /** * Creates an event corresponding to a drop on the target * component within a container at a particular location * within the target view manifestation. * * @param container the container component for the target * @param window the window containing the target component * @param target the target component * @param sources the source components being dropped * @param location the location at which the drop occurrred * @param viewManifestation the view manifestation being dropped upon */ public ViewRoleContentDropActionEvent(Container container, Window window, AbstractComponent target, Collection<AbstractComponent> sources, Point location, View viewManifestation) { this(container, window, target, sources, viewManifestation); cursorLocation = location; } /** * Gets the container component in which the drop occurs. * * @return the container component */ public Container getContainer() { return container; } /** * Gets the housing window in which the drop occurs. * * @return the housing window */ public Window getHousingWindow() { return window; } /** * Gets the target component upon which the drop occurs. * * @return the target comoponent */ public AbstractComponent getTarget() { return target; } /** * Gets the source components that are being dropped. * * @return the source components */ public Collection<AbstractComponent> getSources() { return sources; } /** * Gets the location within the target view manifestation * where the drop occurs. * * @return the target location for the drop */ public Point getLocation() { return cursorLocation; } /** * Gets the target view manifestation onto which the source * components are dropped. * * @return the target view manifestation */ public View getTargetManifestation() { return this.targetViewManifestation; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_roles_ViewRoleContentDropActionEvent.java
362
public final class ComponentSecurityProperties { private static final ResourceBundle resource = ResourceBundle.getBundle("CoreSecurityPolicy"); //NO18N private ComponentSecurityProperties() { } public static byte parsePermissionfromPolicy(String key) { String value = resource.getString(key).trim(); byte byteValue = (byte) Integer.parseInt(value, 16); return byteValue; } public static String parseNameValuefromPolicy(String key) { String value = resource.getString(key).trim(); if ("user".equals(value)) return PlatformAccess.getPlatform().getCurrentUser().getUserId(); else if ("discipline".equals(value)) { return PlatformAccess.getPlatform().getCurrentUser().getDisciplineId(); } else return value; } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_core_util_ComponentSecurityProperties.java
363
public class Activator implements BundleActivator { @Override public void start(BundleContext context) { ServiceReference sr = context.getServiceReference(Platform.class.getName()); Platform platform = (Platform) context.getService(sr); (new PlatformAccess()).setPlatform(platform); context.ungetService(sr); sr = context.getServiceReference(PolicyManager.class.getName()); PolicyManager policyManager = (PolicyManager) context.getService(sr); (new PolicyManagerAccess()).setPolciyManager(policyManager); context.ungetService(sr); context.registerService(new String[] { ComponentProvider.class.getName(), DefaultComponentProvider.class.getName() }, new CoreComponentProvider(), null); } @Override public void stop(BundleContext context) { (new PlatformAccess()).releasePlatform(); (new PolicyManagerAccess()).releasePolicyManager(); } }
false
mctCoreTaxonomyProvider_src_main_java_gov_nasa_arc_mct_coreTaxonomyProvider_Activator.java
364
public final class InternalDBPersistenceAccess { private static final AtomicReference<PersistenceServiceImpl> ref = new AtomicReference<PersistenceServiceImpl>(); public static PersistenceServiceImpl getService() { return ref.get(); } public void setPersistenceService(PersistenceServiceImpl service) { ref.set(service); } public void releasePersistenceService() { ref.set(null); } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_access_InternalDBPersistenceAccess.java
365
@Entity @Table(name = "component_spec",uniqueConstraints=@UniqueConstraint(columnNames={"external_key", "component_type"})) @Cacheable @NamedQueries({ @NamedQuery(name = "ComponentSpec.findAll", query = "SELECT c FROM ComponentSpec c"), @NamedQuery(name = "ComponentSpec.findReferencingComponents", query = "SELECT c FROM ComponentSpec c JOIN c.referencedComponents refs WHERE refs.componentId = :component")}) public class ComponentSpec implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "component_id",length=32) private String componentId; @Basic(optional = false) @Column(name = "component_name",length=200) private String componentName; @Basic(optional = false) @Column(name = "creator_user_id",updatable=false,length=20) private String creatorUserId; @Basic(optional = false) @Column(name = "owner",length=40) private String owner; @Column(name = "date_created",updatable=false) @Temporal(TemporalType.TIMESTAMP) private Date dateCreated; @Column(name = "external_key",length=64) private String externalKey; @Basic(optional = false) @Column(name = "last_modified") @Temporal(TemporalType.TIMESTAMP) private Date lastModified; @Basic(optional = false) @Column(name = "component_type",length=150) private String componentType; @Lob @Column(name = "model_info",length=Integer.MAX_VALUE) private String modelInfo; @Basic(optional = false) @Version() @Column(name = "obj_version") private int objVersion; @OneToMany(cascade = CascadeType.ALL, mappedBy = "componentSpec",fetch=FetchType.LAZY) private Collection<ViewState> viewStateCollection; @ManyToMany(cascade = {CascadeType.REFRESH, CascadeType.MERGE,CascadeType.DETACH, CascadeType.PERSIST},fetch=FetchType.LAZY) @JoinTable(name="component_relationship",inverseJoinColumns=@JoinColumn(name="associated_component_id"), joinColumns=@JoinColumn(name="component_id")) @OrderColumn(name="seq_no") private List<ComponentSpec> referencedComponents; @OneToMany(cascade = CascadeType.ALL, mappedBy = "componentSpec",fetch=FetchType.LAZY) private Collection<TagAssociation> tagAssociationCollection; public ComponentSpec() { } @PrePersist public void initializePriorToDatabaseAdd() { dateCreated = new Date(); lastModified = dateCreated; } @PreUpdate public void updateBeforeDatabaseUpdate() { lastModified = new Date(); } public String getComponentId() { return componentId; } public void setComponentId(String componentId) { this.componentId = componentId; } public String getComponentName() { return componentName; } public void setComponentName(String componentName) { this.componentName = componentName; } public String getCreatorUserId() { return creatorUserId; } public void setCreatorUserId(String creatorUserId) { this.creatorUserId = creatorUserId; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public Date getDateCreated() { return dateCreated; } public String getExternalKey() { return externalKey; } public void setExternalKey(String externalKey) { this.externalKey = externalKey; } public Date getLastModified() { return lastModified; } public String getComponentType() { return componentType; } public void setComponentType(String componentType) { this.componentType = componentType; } public String getModelInfo() { return modelInfo; } public void setModelInfo(String modelInfo) { this.modelInfo = modelInfo; } public void setObjVersion(int versionNumber) { objVersion = versionNumber; } public int getObjVersion() { return objVersion; } public Collection<ViewState> getViewStateCollection() { return viewStateCollection; } public void setViewStateCollection(Collection<ViewState> viewStateCollection) { this.viewStateCollection = viewStateCollection; } public List<ComponentSpec> getReferencedComponents() { return referencedComponents; } public void setReferencedComponents(List<ComponentSpec> componentRelationshipCollection) { this.referencedComponents = componentRelationshipCollection; } public Collection<TagAssociation> getTagAssociationCollection() { return tagAssociationCollection; } public void setTagAssociationCollection(Collection<TagAssociation> tagAssociationCollection) { this.tagAssociationCollection = tagAssociationCollection; } @Override public int hashCode() { int hash = 0; hash += (componentId != null ? componentId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof ComponentSpec)) { return false; } ComponentSpec other = (ComponentSpec) object; if ((this.componentId == null && other.componentId != null) || (this.componentId != null && !this.componentId.equals(other.componentId))) { return false; } return true; } @Override public String toString() { return "test.ComponentSpec[ componentId=" + componentId + " ]"; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_dao_ComponentSpec.java
366
@Entity @Table(name = "database_identification") @NamedQueries({ @NamedQuery(name = "DatabaseIdentification.findAll", query = "SELECT d FROM DatabaseIdentification d"), @NamedQuery(name = "DatabaseIdentification.findSchemaId", query = "Select d FROM DatabaseIdentification d where d.name = 'schema_id'")}) public class DatabaseIdentification implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "name") private String name; @Basic(optional = false) @Column(name = "value") private String value; @Basic(optional = false) @Column(name = "obj_version") private int objVersion; public DatabaseIdentification() { } public DatabaseIdentification(String name) { this.name = name; } public DatabaseIdentification(String name, String value, int objVersion) { this.name = name; this.value = value; this.objVersion = objVersion; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public int getObjVersion() { return objVersion; } public void setObjVersion(int objVersion) { this.objVersion = objVersion; } @Override public int hashCode() { int hash = 0; hash += (name != null ? name.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DatabaseIdentification)) { return false; } DatabaseIdentification other = (DatabaseIdentification) object; if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) { return false; } return true; } @Override public String toString() { return "test.DatabaseIdentification[ name=" + name + " ]"; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_dao_DatabaseIdentification.java
367
@Entity @Table(name = "disciplines") @NamedQueries({ @NamedQuery(name = "Disciplines.findAll", query = "SELECT d FROM Disciplines d")}) public class Disciplines implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "discipline_id") private String disciplineId; @Column(name = "description") private String description; @Column(name = "program") private String program; @Basic(optional = false) @Column(name = "obj_version") private int objVersion; @OneToMany(cascade = CascadeType.ALL, mappedBy = "disciplineId") private Collection<MctUsers> mctUsersCollection; public Disciplines() { } public String getDisciplineId() { return disciplineId; } public void setDisciplineId(String disciplineId) { this.disciplineId = disciplineId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getProgram() { return program; } public void setProgram(String program) { this.program = program; } public int getObjVersion() { return objVersion; } public void setObjVersion(int objVersion) { this.objVersion = objVersion; } public Collection<MctUsers> getMctUsersCollection() { return mctUsersCollection; } public void setMctUsersCollection(Collection<MctUsers> mctUsersCollection) { this.mctUsersCollection = mctUsersCollection; } @Override public int hashCode() { int hash = 0; hash += (disciplineId != null ? disciplineId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Disciplines)) { return false; } Disciplines other = (Disciplines) object; if ((this.disciplineId == null && other.disciplineId != null) || (this.disciplineId != null && !this.disciplineId.equals(other.disciplineId))) { return false; } return true; } @Override public String toString() { return "test.Disciplines[ disciplineId=" + disciplineId + " ]"; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_dao_Disciplines.java
368
@Entity @Table(name = "mct_users") @NamedQueries({ @NamedQuery(name = "MctUsers.findAll", query = "SELECT m FROM MctUsers m"), @NamedQuery(name = "MctUsers.findByGroup", query = "SELECT m FROM MctUsers m where m.disciplineId.disciplineId = :group")}) public class MctUsers implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "user_id") private String userId; @Column(name = "firstname") private String firstname; @Column(name = "lastname") private String lastname; @Basic(optional = false) @Column(name = "obj_version") private int objVersion; @JoinColumn(name = "discipline_id", referencedColumnName = "discipline_id") @ManyToOne(optional = false) private Disciplines disciplineId; public MctUsers() { } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public int getObjVersion() { return objVersion; } public void setObjVersion(int objVersion) { this.objVersion = objVersion; } public Disciplines getDisciplineId() { return disciplineId; } public void setDisciplineId(Disciplines disciplineId) { this.disciplineId = disciplineId; } @Override public int hashCode() { int hash = 0; hash += (userId != null ? userId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof MctUsers)) { return false; } MctUsers other = (MctUsers) object; if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) { return false; } return true; } @Override public String toString() { return "test.MctUsers[ userId=" + userId + " ]"; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_dao_MctUsers.java
369
@Entity @Table(name = "tag") @NamedQueries({ @NamedQuery(name = "Tag.findAll", query = "SELECT t FROM Tag t")}) public class Tag implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "tag_id",length=100) private String tagId; @Column(name = "tag_property",length=200) private String tagProperty; @Basic(optional = false) @Column(name = "obj_version") private int objVersion; @OneToMany(cascade = CascadeType.ALL, mappedBy = "tag") private Collection<TagAssociation> tagAssociationCollection; public Tag() { } public String getTagId() { return tagId; } public void setTagId(String tagId) { this.tagId = tagId; } public String getTagProperty() { return tagProperty; } public void setTagProperty(String tagProperty) { this.tagProperty = tagProperty; } public int getObjVersion() { return objVersion; } public void setObjVersion(int objVersion) { this.objVersion = objVersion; } public Collection<TagAssociation> getTagAssociationCollection() { return tagAssociationCollection; } public void setTagAssociationCollection(Collection<TagAssociation> tagAssociationCollection) { this.tagAssociationCollection = tagAssociationCollection; } @Override public int hashCode() { int hash = 0; hash += (tagId != null ? tagId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Tag)) { return false; } Tag other = (Tag) object; if ((this.tagId == null && other.tagId != null) || (this.tagId != null && !this.tagId.equals(other.tagId))) { return false; } return true; } @Override public String toString() { return "test.Tag[ tagId=" + tagId + " ]"; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_dao_Tag.java
370
@Entity @Table(name = "tag_association") @NamedQueries({ @NamedQuery(name = "TagAssociation.findAll", query = "SELECT t FROM TagAssociation t"), @NamedQuery(name = "TagAssociation.getComponentsByTag", query="SELECT t FROM TagAssociation t WHERE t.tag.tagId = :tagId")}) public class TagAssociation implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected TagAssociationPK tagAssociationPK; @Column(name = "tag_property",length=200) private String tagProperty; @JoinColumn(name = "tag_id", referencedColumnName = "tag_id", insertable = false, updatable = false) @ManyToOne(optional = false) private Tag tag; @JoinColumn(name = "component_id", referencedColumnName = "component_id", insertable = false, updatable = false) @ManyToOne(optional = false) private ComponentSpec componentSpec; public TagAssociation() { } public TagAssociationPK getTagAssociationPK() { return tagAssociationPK; } public void setTagAssociationPK(TagAssociationPK tagAssociationPK) { this.tagAssociationPK = tagAssociationPK; } public String getTagProperty() { return tagProperty; } public void setTagProperty(String tagProperty) { this.tagProperty = tagProperty; } public Tag getTag() { return tag; } public void setTag(Tag tag) { this.tag = tag; } public ComponentSpec getComponentSpec() { return componentSpec; } public void setComponentSpec(ComponentSpec componentSpec) { this.componentSpec = componentSpec; } @Override public int hashCode() { int hash = 0; hash += (tagAssociationPK != null ? tagAssociationPK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TagAssociation)) { return false; } TagAssociation other = (TagAssociation) object; if ((this.tagAssociationPK == null && other.tagAssociationPK != null) || (this.tagAssociationPK != null && !this.tagAssociationPK.equals(other.tagAssociationPK))) { return false; } return true; } @Override public String toString() { return "test.TagAssociation[ tagAssociationPK=" + tagAssociationPK + " ]"; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_dao_TagAssociation.java
371
@Embeddable public class TagAssociationPK implements Serializable { @Basic(optional = false) @Column(name = "component_id") private String componentId; @Basic(optional = false) @Column(name = "tag_id") private String tagId; public TagAssociationPK() { } public String getComponentId() { return componentId; } public void setComponentId(String componentId) { this.componentId = componentId; } public String getTagId() { return tagId; } public void setTagId(String tagId) { this.tagId = tagId; } @Override public int hashCode() { int hash = 0; hash += (componentId != null ? componentId.hashCode() : 0); hash += (tagId != null ? tagId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TagAssociationPK)) { return false; } TagAssociationPK other = (TagAssociationPK) object; if ((this.componentId == null && other.componentId != null) || (this.componentId != null && !this.componentId.equals(other.componentId))) { return false; } if ((this.tagId == null && other.tagId != null) || (this.tagId != null && !this.tagId.equals(other.tagId))) { return false; } return true; } @Override public String toString() { return "test.TagAssociationPK[ componentId=" + componentId + ", tagId=" + tagId + " ]"; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_dao_TagAssociationPK.java
372
public class TestComponentSpec { private EntityManagerFactory factory; private EntityManager em; @BeforeMethod protected void setup() { Map<String,String> properties = new HashMap<String,String>(); properties.put("javax.persistence.jdbc.driver","org.apache.derby.jdbc.EmbeddedDriver"); properties.put("javax.persistence.jdbc.url","jdbc:derby:memory:testdb;create=true"); properties.put("hibernate.hbm2ddl.auto","create"); properties.put("hibernate.show_sql" ,"false"); properties.put("hibernate.format_sql", "false"); factory = Persistence.createEntityManagerFactory("MissionControlTechnologies", properties); em = factory.createEntityManager(); } private ComponentSpec createComponentSpec(String id, String userId, String name, String type, String owner, List<Tag> tags, Map<String,String> views) { ComponentSpec cs = new ComponentSpec(); cs.setComponentId(id); cs.setCreatorUserId(userId); cs.setComponentName(name); cs.setComponentType(type); cs.setOwner(owner); cs.setReferencedComponents(new ArrayList<ComponentSpec>()); List<ViewState> viewStates = new ArrayList<ViewState>(); for (Entry<String,String> e:views.entrySet()) { ViewState vs = new ViewState(); ViewStatePK viewStatePK = new ViewStatePK(); viewStatePK.setComponentId(cs.getComponentId()); viewStatePK.setViewType(e.getKey()); vs.setViewStatePK(viewStatePK); vs.setViewInfo(e.getValue()); viewStates.add(vs); } cs.setViewStateCollection(viewStates); cs.setTagAssociationCollection(new ArrayList<TagAssociation>()); for (Tag aTag:tags) { TagAssociation association = new TagAssociation(); TagAssociationPK tagPK = new TagAssociationPK(); tagPK.setComponentId(cs.getComponentId()); tagPK.setTagId(aTag.getTagId()); association.setTagAssociationPK(tagPK); association.setTagProperty(aTag.getTagProperty()); cs.getTagAssociationCollection().add(association); } return cs; } private void checkComponentSpec(ComponentSpec cs, String owner, String type, String creator, String name, Collection<Tag> tags, Map<String,String> views) { Assert.assertEquals(owner, cs.getOwner()); Assert.assertEquals(type, cs.getComponentType()); Assert.assertEquals(creator, cs.getCreatorUserId()); Assert.assertEquals(name, cs.getComponentName()); Assert.assertNotNull(cs.getDateCreated()); Assert.assertNotNull(cs.getLastModified()); Assert.assertEquals(cs.getViewStateCollection().size(), views.size()); for (Entry<String,String> e: views.entrySet()) { Assert.assertTrue(findViewState(cs.getViewStateCollection(), e.getKey(), e.getValue())); } Assert.assertEquals(cs.getTagAssociationCollection().size(), tags.size()); for (Tag t: tags) { Assert.assertTrue(findTags(cs.getTagAssociationCollection(), t)); } } private boolean findTags(Collection<TagAssociation> tags, Tag expectedTag) { for (TagAssociation tag: tags) { if (tag.getTag().getTagId().equals(expectedTag.getTagId())) { return true; } } return false; } private boolean findViewState(Collection<ViewState> states, String viewType, String viewValue) { for (ViewState state: states) { if (state.getViewStatePK().getViewType().equals(viewType) && state.getViewInfo().equals(viewValue)) { return true; } } return false; } @Test(expectedExceptions=OptimisticLockException.class) public void testOptimisticLockException() { ComponentSpec cs = createComponentSpec(Long.toString(1), "chris", "cs", "type1", "chris",Collections.<Tag>emptyList(), Collections.<String,String>emptyMap()); em.getTransaction().begin(); em.persist(cs); em.getTransaction().commit(); em.clear(); Assert.assertFalse(em.contains(cs)); em.getTransaction().begin(); ComponentSpec orig = em.find(ComponentSpec.class,Long.toString(1)); orig.setComponentName("revisedName"); em.getTransaction().commit(); em.clear(); ComponentSpec current = em.find(ComponentSpec.class,Long.toString(1)); Assert.assertEquals(current.getObjVersion(),1); Assert.assertEquals(cs.getObjVersion(),0); em.getTransaction().begin(); em.merge(cs); em.getTransaction().commit(); // optimistic lock exception should be thrown as there has been an intervening commit } @Test public void testComponentSpec() { em.getTransaction().begin(); long time = System.currentTimeMillis(); final Map<String,String> initialViews = Collections.singletonMap("v1", "v1value"); Tag t1 = new Tag(); t1.setTagId("tag1"); Tag t2 = new Tag(); t2.setTagId("tag2"); final List<Tag> tags = Arrays.asList(t1, t2); for (Tag t:tags) { em.persist(t); } ComponentSpec cs = createComponentSpec(Long.toString(time), "chris", "cs", "type1", "chris",tags, initialViews); em.persist(cs); ComponentSpec cs1 = createComponentSpec(Long.toString(time+1), "chris", "cs1", "type2", "chris", Collections.<Tag>emptyList(), initialViews); em.persist(cs1); cs.getReferencedComponents().add(cs1); em.getTransaction().commit(); em.clear(); cs = em.find(ComponentSpec.class, Long.toString(time)); checkComponentSpec(cs,"chris","type1", "chris", "cs", tags, initialViews); Assert.assertEquals(cs.getReferencedComponents().size(), 1); Assert.assertEquals(cs.getReferencedComponents().iterator().next().getComponentId(), Long.toString(time+1)); checkComponentSpec(cs.getReferencedComponents().iterator().next(), "chris", "type2", "chris", "cs1",Collections.<Tag>emptyList(), initialViews); em.getTransaction().begin(); ComponentSpec cs2 = createComponentSpec(Long.toString(time+2), "chris", "cs2", "type3", "chris", Collections.<Tag>emptyList(), Collections.<String,String>emptyMap()); cs = em.find(ComponentSpec.class, Long.toString(time)); cs.getReferencedComponents().add(0, cs2); em.getTransaction().commit(); em.clear(); // check cascade persist and relationship ordering Assert.assertNotNull(em.find(ComponentSpec.class, Long.toString(time+2))); cs = em.find(ComponentSpec.class, Long.toString(time)); Assert.assertEquals(cs.getReferencedComponents().size(), 2); Iterator<ComponentSpec> it = cs.getReferencedComponents().iterator(); Assert.assertEquals(it.next().getComponentId(), Long.toString(time+2)); Assert.assertEquals(it.next().getComponentId(), Long.toString(time+1)); } @AfterMethod protected void tearDown() { em.clear(); factory.close(); } }
false
databasePersistence_src_test_java_gov_nasa_arc_mct_dbpersistence_dao_TestComponentSpec.java
373
public class TestDAOClasses { private final List<Class<?>> daoClasses = Arrays.<Class<?>>asList(ComponentSpec.class, DatabaseIdentification.class, Disciplines.class, MctUsers.class, Tag.class, TagAssociation.class, ViewState.class); @BeforeMethod public void setup() { } @Test public void testGetAndSetMethods() throws Exception { for (Class<?> c:daoClasses) { Object o = c.newInstance(); for (Method m:c.getMethods()) { if (m.getName().startsWith("get")) { Object setValue = null; if (m.getReturnType().equals(String.class)) { setValue = "1"; } if (m.getReturnType().equals(Integer.TYPE)) { setValue = 1; } if (m.getReturnType().equals(Boolean.TYPE)) { setValue = true; } if (m.getReturnType().equals(Date.class)) { setValue = new Date(); } if (setValue == null) { continue; } try { Method setMethod = c.getMethod(m.getName().replaceAll("get", "set"), m.getReturnType()); setMethod.invoke(o, setValue); Assert.assertEquals(m.invoke(o, new Object[0]), setValue); } catch (NoSuchMethodException nsme) { } } } Assert.assertEquals(o, o); Assert.assertEquals(o.hashCode(), o.hashCode()); Assert.assertFalse(o.equals(Integer.valueOf(1))); o.toString(); } } }
false
databasePersistence_src_test_java_gov_nasa_arc_mct_dbpersistence_dao_TestDAOClasses.java
374
@Entity @Cacheable @Table(name = "view_state") public class ViewState implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected ViewStatePK viewStatePK; @Basic(optional = false) @Lob @Column(name = "view_info",length=Integer.MAX_VALUE) private String viewInfo; @JoinColumn(name = "component_id", referencedColumnName = "component_id", insertable = false, updatable = false) @ManyToOne(optional = false) private ComponentSpec componentSpec; public ViewState() { } public ViewStatePK getViewStatePK() { return viewStatePK; } public void setViewStatePK(ViewStatePK viewStatePK) { this.viewStatePK = viewStatePK; } public String getViewInfo() { return viewInfo; } public void setViewInfo(String viewInfo) { this.viewInfo = viewInfo; } public ComponentSpec getComponentSpec() { return componentSpec; } public void setComponentSpec(ComponentSpec componentSpec) { this.componentSpec = componentSpec; } @Override public int hashCode() { int hash = 0; hash += (viewStatePK != null ? viewStatePK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof ViewState)) { return false; } ViewState other = (ViewState) object; if ((this.viewStatePK == null && other.viewStatePK != null) || (this.viewStatePK != null && !this.viewStatePK.equals(other.viewStatePK))) { return false; } return true; } @Override public String toString() { return "ViewState[ viewStatePK=" + viewStatePK + " "+ "viewInfo " + viewInfo + "]"; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_dao_ViewState.java
375
@Embeddable public class ViewStatePK implements Serializable { @Basic(optional = false) @Column(name = "component_id") private String componentId; @Basic(optional = false) @Column(name = "view_type") private String viewType; public ViewStatePK() { } public String getComponentId() { return componentId; } public void setComponentId(String componentId) { this.componentId = componentId; } public String getViewType() { return viewType; } public void setViewType(String viewType) { this.viewType = viewType; } @Override public int hashCode() { int hash = 0; hash += (componentId != null ? componentId.hashCode() : 0); hash += (viewType != null ? viewType.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ViewStatePK)) { return false; } ViewStatePK other = (ViewStatePK) object; if ((this.componentId == null && other.componentId != null) || (this.componentId != null && !this.componentId.equals(other.componentId))) { return false; } if ((this.viewType == null && other.viewType != null) || (this.viewType != null && !this.viewType.equals(other.viewType))) { return false; } return true; } @Override public String toString() { return "test.ViewStatePK[ componentId=" + componentId + ", viewType=" + viewType + " ]"; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_dao_ViewStatePK.java
376
public class DBPersistenceProvider extends AbstractComponentProvider { @Override public SearchProvider getSearchProvider() { return new DatabaseSearchProvider(); } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_provider_DBPersistenceProvider.java
377
public final class DatabaseSearchProvider implements SearchProvider { private static final String NAME = "Search Name"; @Override public String getName() { return NAME; } @Override public JComponent createSearchUI() { return new DatabaseSearchUI(); } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_DatabaseSearchProvider.java
378
@SuppressWarnings("serial") public class DatabaseSearchUI extends JPanel implements SelectionProvider { // private final static ResourceBundle bundle = ResourceBundle.getBundle("Platform"); //NOI18N private static final int PADDING = 5; private JTextField baseDisplayedNameField; private DefaultListModel listModel = new DefaultListModel(); private JList list; private JButton goButton; private JLabel resultStatus; private JCheckBox findObjectsCreatedByMe; public DatabaseSearchUI() { setLayout(new BorderLayout()); JPanel displayNamePanel = new JPanel(new BorderLayout()); JLabel displayNameLabel = new JLabel("Base Displayed Name:"); baseDisplayedNameField = new JTextField(); baseDisplayedNameField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (goButton.isEnabled()) goButton.doClick(); } }); displayNameLabel.setLabelFor(baseDisplayedNameField); displayNamePanel.add(baseDisplayedNameField, BorderLayout.CENTER); displayNamePanel.add(displayNameLabel, BorderLayout.WEST); goButton = new JButton(); String searchButtonText = "Search";//bundle.getString("SEARCH_BUTTON"); goButton.getAccessibleContext().setAccessibleName(searchButtonText); goButton.setAction(new AbstractAction(searchButtonText) { @Override public void actionPerformed(ActionEvent e) { goButton.setEnabled(false); SearchTask task = new SearchTask(); listModel.removeAllElements(); resultStatus.setText(null); task.execute(); } }); JPanel displayNameAndGoPanel = new JPanel(new BorderLayout()); displayNameAndGoPanel.add(displayNamePanel, BorderLayout.CENTER); displayNameAndGoPanel.add(goButton, BorderLayout.EAST); listModel = new DefaultListModel(); list = new JList(listModel); list.getAccessibleContext().setAccessibleName("Search Result List"); list.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { ComponentInfo ci = (ComponentInfo) value; JLabel label = (JLabel) super.getListCellRendererComponent(list, ci.name, index, isSelected, cellHasFocus); label.setIcon(AbstractComponent.getIconForComponentType(ci.type)); return label; } }); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) firePropertyChange(SelectionProvider.SELECTION_CHANGED_PROP, null, getSelectedManifestations()); } }); list.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Collection<View> selectedManifestations = getSelectedManifestations(); if (selectedManifestations.isEmpty()) return; View manifestation = selectedManifestations.iterator().next(); if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { manifestation.getManifestedComponent().open(); return; } } }); list.setDragEnabled(true); list.setTransferHandler(new TransferHandler() { @Override protected Transferable createTransferable(JComponent c) { List<View> viewRoles = new ArrayList<View>(); for (View manifestation : getSelectedManifestations()) viewRoles.add(manifestation); return new ViewRoleSelection(viewRoles.toArray(new View[viewRoles.size()])); } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY; } }); JPanel controlPanel = new JPanel(new GridLayout(2, 1, 5, 5)); controlPanel.add(displayNameAndGoPanel); findObjectsCreatedByMe = new JCheckBox("Created By Me"); controlPanel.add(findObjectsCreatedByMe); JPanel descriptionPanel = new JPanel(new GridLayout(2, 1)); JLabel searchEverywhereLabel = new JLabel("Search everywhere"); searchEverywhereLabel.setFont(searchEverywhereLabel.getFont().deriveFont(Font.BOLD)); resultStatus = new JLabel(); resultStatus.setForeground(Color.BLUE); descriptionPanel.add(searchEverywhereLabel); descriptionPanel.add(resultStatus); JPanel upperPanel = new JPanel(new BorderLayout(PADDING, PADDING)); upperPanel.setBorder(BorderFactory.createEmptyBorder(PADDING, PADDING, PADDING, PADDING)); upperPanel.add(descriptionPanel, BorderLayout.NORTH); upperPanel.add(controlPanel, BorderLayout.CENTER); add(upperPanel, BorderLayout.NORTH); add(new JScrollPane(list), BorderLayout.CENTER); } QueryResult search(String pattern, boolean isFindObjectsCreatedByMe) { Properties props = new Properties(); if (isFindObjectsCreatedByMe) props.setProperty("creator", PlatformAccess.getPlatform().getCurrentUser().getUserId()); return InternalDBPersistenceAccess.getService().findComponentsByBaseDisplayedNamePattern(pattern, props); } private class SearchTask extends SwingWorker<List<ComponentInfo>, Void> { private AtomicInteger total = new AtomicInteger(); public SearchTask() { } @Override protected List<ComponentInfo> doInBackground() throws Exception { String displayNamePattern = baseDisplayedNameField.getText().trim(); List<ComponentInfo> list = new ArrayList<DatabaseSearchUI.ComponentInfo>(); QueryResult queryResult = search(displayNamePattern, findObjectsCreatedByMe.isSelected()); @SuppressWarnings("unchecked") List<ComponentSpec> daoObjects = (List<ComponentSpec>) queryResult.getRecords(); for (ComponentSpec cs : daoObjects) { ComponentInfo ci = new ComponentInfo(cs.getComponentId(), cs.getComponentName(), cs.getComponentType()); list.add(ci); } total.set(queryResult.getCount()); return list; } @Override public void done() { try { for (ComponentInfo ci : get()) { listModel.addElement(ci); } resultStatus.setText("Search Results: " + listModel.size() + " out of " + total.get()); } catch (InterruptedException e) { listModel.removeAllElements(); } catch (ExecutionException e) { listModel.removeAllElements(); } finally { goButton.setEnabled(true); } } } @Override public String getName() { return "Search Name"; } @Override public void addSelectionChangeListener(PropertyChangeListener listener) { addPropertyChangeListener(SelectionProvider.SELECTION_CHANGED_PROP, listener); } @Override public void removeSelectionChangeListener(PropertyChangeListener listener) { removePropertyChangeListener(SelectionProvider.SELECTION_CHANGED_PROP, listener); } @Override public Collection<View> getSelectedManifestations() { Object[] selectedValues = list.getSelectedValues(); if (selectedValues == null || selectedValues.length == 0) return Collections.emptySet(); Collection<View> manifestations = new ArrayList<View>(); for (Object value : selectedValues) { ComponentInfo ci = (ComponentInfo) value; AbstractComponent component = AbstractComponent.getComponentById(ci.id); manifestations.add(component.getViewInfos(ViewType.NODE).iterator().next().createView(component)); } return manifestations; } @Override public void clearCurrentSelections() { list.clearSelection(); } private static class ComponentInfo { public ComponentInfo(String id, String name, String type) { this.id = id; this.name = name; this.type = type; } private String id; private String name; private String type; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_DatabaseSearchUI.java
379
baseDisplayedNameField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (goButton.isEnabled()) goButton.doClick(); } });
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_DatabaseSearchUI.java
380
goButton.setAction(new AbstractAction(searchButtonText) { @Override public void actionPerformed(ActionEvent e) { goButton.setEnabled(false); SearchTask task = new SearchTask(); listModel.removeAllElements(); resultStatus.setText(null); task.execute(); } });
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_DatabaseSearchUI.java
381
list.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { ComponentInfo ci = (ComponentInfo) value; JLabel label = (JLabel) super.getListCellRendererComponent(list, ci.name, index, isSelected, cellHasFocus); label.setIcon(AbstractComponent.getIconForComponentType(ci.type)); return label; } });
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_DatabaseSearchUI.java
382
list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) firePropertyChange(SelectionProvider.SELECTION_CHANGED_PROP, null, getSelectedManifestations()); } });
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_DatabaseSearchUI.java
383
list.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Collection<View> selectedManifestations = getSelectedManifestations(); if (selectedManifestations.isEmpty()) return; View manifestation = selectedManifestations.iterator().next(); if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { manifestation.getManifestedComponent().open(); return; } } });
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_DatabaseSearchUI.java
384
list.setTransferHandler(new TransferHandler() { @Override protected Transferable createTransferable(JComponent c) { List<View> viewRoles = new ArrayList<View>(); for (View manifestation : getSelectedManifestations()) viewRoles.add(manifestation); return new ViewRoleSelection(viewRoles.toArray(new View[viewRoles.size()])); } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY; } });
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_DatabaseSearchUI.java
385
private static class ComponentInfo { public ComponentInfo(String id, String name, String type) { this.id = id; this.name = name; this.type = type; } private String id; private String name; private String type; }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_DatabaseSearchUI.java
386
private class SearchTask extends SwingWorker<List<ComponentInfo>, Void> { private AtomicInteger total = new AtomicInteger(); public SearchTask() { } @Override protected List<ComponentInfo> doInBackground() throws Exception { String displayNamePattern = baseDisplayedNameField.getText().trim(); List<ComponentInfo> list = new ArrayList<DatabaseSearchUI.ComponentInfo>(); QueryResult queryResult = search(displayNamePattern, findObjectsCreatedByMe.isSelected()); @SuppressWarnings("unchecked") List<ComponentSpec> daoObjects = (List<ComponentSpec>) queryResult.getRecords(); for (ComponentSpec cs : daoObjects) { ComponentInfo ci = new ComponentInfo(cs.getComponentId(), cs.getComponentName(), cs.getComponentType()); list.add(ci); } total.set(queryResult.getCount()); return list; } @Override public void done() { try { for (ComponentInfo ci : get()) { listModel.addElement(ci); } resultStatus.setText("Search Results: " + listModel.size() + " out of " + total.get()); } catch (InterruptedException e) { listModel.removeAllElements(); } catch (ExecutionException e) { listModel.removeAllElements(); } finally { goButton.setEnabled(true); } } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_DatabaseSearchUI.java
387
public class QueryResult { private int count; private Collection<?> records; /** * Initializes query result. * @param count - total count * @param records - collection of records */ public QueryResult(int count, Collection<?> records) { this.count = count; this.records = records; } /** * Gets the count. * @return count - integer */ public int getCount() { return count; } /** * Gets the records. * @return collection of records. */ public Collection<?> getRecords() { return records; } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_search_QueryResult.java
388
public class TestDatabaseSearchUI { private Robot robot; private static final String TITLE = "Test Frame"; private MockPlatformSearchUI platformSearchUI; @BeforeMethod public void setup() { robot = BasicRobot.robotWithNewAwtHierarchy(); GuiActionRunner.execute(new GuiTask() { @Override protected void executeInEDT() throws Throwable { platformSearchUI = new MockPlatformSearchUI(); JFrame frame = new JFrame(TITLE); frame.setName(TITLE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); platformSearchUI.setOpaque(true); // content panes must be opaque frame.setContentPane(platformSearchUI); frame.pack(); frame.setVisible(true); } }); } @AfterMethod public void tearDown(){ robot.cleanUp(); } @Test public void testSearchClickResults() { FrameFixture window = WindowFinder.findFrame(TITLE).using(robot); final JListFixture list = window.list(new JListMatcher("Search Result List")); ComponentSpec cs1 = Mockito.mock(ComponentSpec.class); ComponentSpec cs2 = Mockito.mock(ComponentSpec.class); QueryResult q = new QueryResult(2, Arrays.asList(cs1, cs2)); platformSearchUI.setQueryResult(q); window.button(new JButtonMatcher("Search")).click(); Condition condition = new Condition("Results Arrived.") { @Test @Override public boolean test() { return list.target.getModel().getSize() > 0; } @Override protected void done() { AssertJUnit.assertEquals(list.target.getModel().getSize(), 2); } }; Pause.pause(condition); } private static class JButtonMatcher extends GenericTypeMatcher<JButton> { private final String label; public JButtonMatcher(String label) { super(JButton.class, true); this.label = label; } @Override protected boolean isMatching(JButton cb) { return label.equals(cb.getAccessibleContext().getAccessibleName()) || label.equals(cb.getToolTipText()); } } private static class JListMatcher extends GenericTypeMatcher<JList> { private final String label; public JListMatcher(String label) { super(JList.class, true); this.label = label; } @Override protected boolean isMatching(JList l) { return label.equals(l.getAccessibleContext().getAccessibleName()); } } @SuppressWarnings("serial") private class MockPlatformSearchUI extends DatabaseSearchUI { private QueryResult q; public void setQueryResult(QueryResult q) { this.q = q; } @Override QueryResult search(String pattern, boolean isFindObjectsCreatedByMe) { return q; } } }
false
databasePersistence_src_test_java_gov_nasa_arc_mct_dbpersistence_search_TestDatabaseSearchUI.java
389
GuiActionRunner.execute(new GuiTask() { @Override protected void executeInEDT() throws Throwable { platformSearchUI = new MockPlatformSearchUI(); JFrame frame = new JFrame(TITLE); frame.setName(TITLE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); platformSearchUI.setOpaque(true); // content panes must be opaque frame.setContentPane(platformSearchUI); frame.pack(); frame.setVisible(true); } });
false
databasePersistence_src_test_java_gov_nasa_arc_mct_dbpersistence_search_TestDatabaseSearchUI.java
390
Condition condition = new Condition("Results Arrived.") { @Test @Override public boolean test() { return list.target.getModel().getSize() > 0; } @Override protected void done() { AssertJUnit.assertEquals(list.target.getModel().getSize(), 2); } };
false
databasePersistence_src_test_java_gov_nasa_arc_mct_dbpersistence_search_TestDatabaseSearchUI.java
391
private static class JButtonMatcher extends GenericTypeMatcher<JButton> { private final String label; public JButtonMatcher(String label) { super(JButton.class, true); this.label = label; } @Override protected boolean isMatching(JButton cb) { return label.equals(cb.getAccessibleContext().getAccessibleName()) || label.equals(cb.getToolTipText()); } }
false
databasePersistence_src_test_java_gov_nasa_arc_mct_dbpersistence_search_TestDatabaseSearchUI.java
392
private static class JListMatcher extends GenericTypeMatcher<JList> { private final String label; public JListMatcher(String label) { super(JList.class, true); this.label = label; } @Override protected boolean isMatching(JList l) { return label.equals(l.getAccessibleContext().getAccessibleName()); } }
false
databasePersistence_src_test_java_gov_nasa_arc_mct_dbpersistence_search_TestDatabaseSearchUI.java
393
@SuppressWarnings("serial") private class MockPlatformSearchUI extends DatabaseSearchUI { private QueryResult q; public void setQueryResult(QueryResult q) { this.q = q; } @Override QueryResult search(String pattern, boolean isFindObjectsCreatedByMe) { return q; } }
false
databasePersistence_src_test_java_gov_nasa_arc_mct_dbpersistence_search_TestDatabaseSearchUI.java
394
public class PersistenceServiceImpl implements PersistenceProvider { private static final Logger LOGGER = LoggerFactory.getLogger(PersistenceServiceImpl.class); private static final String PERSISTENCE_PROPS = "properties/persistence.properties"; private static final String VERSION_PROPS = "properties/version.properties"; private static final JAXBContext propContext; private static final ComponentIdComparator COMPONENT_ID_COMPARATOR = new ComponentIdComparator(); private final ConcurrentHashMap<String, List<WeakReference<AbstractComponent>>> cache = new ConcurrentHashMap<String, List<WeakReference<AbstractComponent>>>(); static { try { propContext = JAXBContext.newInstance(ExtendedProperties.class); } catch (JAXBException e) { throw new RuntimeException(e); } } static class ComponentIdComparator implements Comparator<AbstractComponent>, Serializable{ private static final long serialVersionUID = 1834331905999908621L; public int compare(AbstractComponent o1, AbstractComponent o2) { return o1.getComponentId().compareTo(o2.getComponentId()); } } private static final ThreadLocal<Set<AbstractComponent>> components = new ThreadLocal<Set<AbstractComponent>>(){ @Override protected Set<AbstractComponent> initialValue() { return Collections.emptySet(); } }; private EntityManagerFactory entityManagerFactory; private Date lastPollTime; public void setEntityManagerProperties(Properties p) { ClassLoader originalCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { entityManagerFactory = Persistence.createEntityManagerFactory("MissionControlTechnologies", p); } finally { Thread.currentThread().setContextClassLoader(originalCL); } } public void activate(ComponentContext context) throws IOException { setEntityManagerProperties(getPersistenceProperties()); new InternalDBPersistenceAccess().setPersistenceService(this); checkDatabaseVersion(); Timer databasePollingTimer = new Timer(); databasePollingTimer.schedule(new TimerTask() { @Override public void run() { InternalDBPersistenceAccess.getService().updateComponentsFromDatabase(); } }, Calendar.getInstance().getTime(), 3000); } private Properties getPersistenceProperties() throws IOException { Properties properties = new Properties(); InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(PERSISTENCE_PROPS); if (is == null) throw new IOException("Unable to get mct property file: " + PERSISTENCE_PROPS); try { properties.load(is); } finally { is.close(); } // adjust user name and connection string properties for JPA final String dbUser = "mct.database_userName"; final String dbPassword = "mct.database_password"; final String dbConnectionURL = "mct.database_connectionUrl"; final String dbName = "mct.database_name"; final String dbProperties = "mct.database_properties"; properties.put("javax.persistence.jdbc.user", System.getProperty(dbUser, properties.getProperty(dbUser))); properties.put("javax.persistence.jdbc.password",System.getProperty(dbPassword,properties.getProperty(dbPassword))); String connectionURL = System.getProperty(dbConnectionURL, properties.getProperty(dbConnectionURL)) + System.getProperty(dbName, properties.getProperty(dbName)) + "?" + System.getProperty(dbProperties, properties.getProperty(dbProperties)); properties.put("javax.persistence.jdbc.url",connectionURL); return properties; } private void checkDatabaseVersion() { // Don't check schema versions if a special JVM parameter is set. if (System.getProperty("mct.db.check-schema-version", Boolean.TRUE.toString()).equals(Boolean.TRUE.toString())) { Properties versionProperties = new Properties(); try { InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(VERSION_PROPS); if (is == null) throw new IOException("Unable to get mct property file: " + VERSION_PROPS); try { versionProperties.load(is); } finally { is.close(); } } catch (IOException e) { throw new RuntimeException("Cannot load version properties (properties/version.properties)", e); } String schemaId; if ((schemaId = versionProperties.getProperty("mct.db.schema_id")) == null) { throw new RuntimeException("required property mct.db.schema_id is undefined"); } EntityManager em = entityManagerFactory.createEntityManager(); try { TypedQuery<DatabaseIdentification> q = em.createNamedQuery("DatabaseIdentification.findSchemaId", DatabaseIdentification.class); DatabaseIdentification di = q.getSingleResult(); if (!schemaId.equals(di.getValue())) { throw new RuntimeException ("Mismatched schemaID.\nDeployed schema ID is " + di.getValue() + "\nbut MCT requires schema ID " + schemaId); } } finally { em.close(); } } } @Override public AbstractComponent getComponentFromStore(String componentId) { Cache c = entityManagerFactory.getCache(); c.evict(ComponentSpec.class, componentId); return getComponent(componentId); } @Override public AbstractComponent getComponent(String componentId) { EntityManager em = entityManagerFactory.createEntityManager(); ComponentSpec cs = null; try { cs = em.find(ComponentSpec.class, componentId); } finally { em.close(); } if (cs != null) { return createAbstractComponent(cs); } return null; } @Override public Collection<AbstractComponent> getReferences(AbstractComponent component) { Collection<AbstractComponent> references = new ArrayList<AbstractComponent>(); EntityManager em = entityManagerFactory.createEntityManager(); try { TypedQuery<ComponentSpec> q = em.createNamedQuery("ComponentSpec.findReferencingComponents", ComponentSpec.class); q.setParameter("component", component.getComponentId()); List<ComponentSpec> referencingComponents = q.getResultList(); for (ComponentSpec cs:referencingComponents) { references.add(createAbstractComponent(cs)); } } finally { em.close(); } return references; } private boolean hasWorkUnitBeenStarted() { return getCurrentComponents() != Collections.<AbstractComponent>emptySet(); } @Override public void startRelatedOperations() { assert entityManagerFactory != null; if (hasWorkUnitBeenStarted()) { throw new IllegalStateException("startRelatedOperations cannot be invoked until the last operations has been closed"); } components.set(new TreeSet<AbstractComponent>(COMPONENT_ID_COMPARATOR)); } @Override public void completeRelatedOperations(boolean save) { try { if (save) { persist(components.get()); } } finally { components.remove(); } } @Override public void addComponentToWorkUnit(AbstractComponent component) { if (hasWorkUnitBeenStarted()) { getCurrentComponents().add(component); } } public Collection<AbstractComponent> getCurrentComponents() { return components.get(); } @Override public Set<String> getAllUsers() { EntityManager em = entityManagerFactory.createEntityManager(); Set<String> userNames = null; try { TypedQuery<MctUsers> q = em.createNamedQuery("MctUsers.findAll", MctUsers.class); List<MctUsers> users = q.getResultList(); userNames = new HashSet<String>(users.size()); for (MctUsers u:users) { userNames.add(u.getUserId()); } } finally { em.close(); } return userNames; } @Override public Collection<String> getUsersInGroup(String group) { EntityManager em = entityManagerFactory.createEntityManager(); List<String> userNames = null; try { TypedQuery<MctUsers> q = em.createNamedQuery("MctUsers.findByGroup", MctUsers.class); q.setParameter("group", group); List<MctUsers> users = q.getResultList(); userNames = new ArrayList<String>(users.size()); for (MctUsers u:users) { userNames.add(u.getUserId()); } } finally { em.close(); } return userNames; } private ExtendedProperties createExtendedProperties(String props) { Unmarshaller unmarshaller; try { unmarshaller = propContext.createUnmarshaller(); InputStream is = new ByteArrayInputStream(props.getBytes("ASCII")); return ExtendedProperties.class.cast(unmarshaller.unmarshal(is)); } catch (JAXBException je) { throw new RuntimeException(je); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private String generateStringFromView(ExtendedProperties viewState) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); Marshaller marshaller = propContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_ENCODING, "ASCII"); marshaller.marshal(viewState, out); return out.toString("ASCII"); } catch (JAXBException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private ViewState createViewState(String viewType, String componentId, ExtendedProperties viewData, EntityManager em, ComponentSpec cs) { ViewStatePK viewStatePK = new ViewStatePK(); viewStatePK.setComponentId(componentId); viewStatePK.setViewType(viewType); ViewState vs = em.find(ViewState.class, viewStatePK); if (vs == null) { vs = new ViewState(); vs.setViewStatePK(viewStatePK); if (cs.getViewStateCollection() == null) { cs.setViewStateCollection(new ArrayList<ViewState>()); } cs.getViewStateCollection().add(vs); } vs.setViewInfo(generateStringFromView(viewData)); return vs; } private void updateComponentSpec(AbstractComponent ac,ComponentSpec cs,EntityManager em, boolean fullSave) { cs.setComponentId(ac.getComponentId()); cs.setComponentName(ac.getDisplayName()); cs.setOwner(ac.getOwner()); cs.setCreatorUserId(ac.getCreator()); cs.setComponentType(ac.getClass().getName()); cs.setExternalKey(ac.getExternalKey()); if (!fullSave) { return; } cs.setObjVersion(ac.getVersion()); ModelStatePersistence persistence = ac.getCapability(ModelStatePersistence.class); if (persistence != null) { cs.setModelInfo(persistence.getModelState()); } // save relationships // non optimal implementation as this will require a query to get the relationships cs.setReferencedComponents(new ArrayList<ComponentSpec>(ac.getComponents().size())); for (AbstractComponent c : ac.getComponents()) { ComponentSpec refCs = em.find(ComponentSpec.class, c.getComponentId()); if (refCs == null) { // this can be null if the component has been deleted continue; } cs.getReferencedComponents().add(refCs); } // save views ComponentInitializer ci = ac.getCapability(ComponentInitializer.class); if (ci.getMutatedViewRoleProperties() != null) { for (Entry<String,ExtendedProperties> viewEntry : ci.getAllViewRoleProperties().entrySet()) { createViewState(viewEntry.getKey(), cs.getComponentId(), viewEntry.getValue(),em,cs); } } } @Override public void persist(Collection<AbstractComponent> componentsToPersist) { EntityManager em = entityManagerFactory.createEntityManager(); try { em.getTransaction().begin(); // first persist all new components, without relationships, model, and view states for (AbstractComponent nc : componentsToPersist) { if (nc.getCreationDate() == null) { ComponentSpec cs = new ComponentSpec(); updateComponentSpec(nc, cs, em, false); em.persist(cs); } } // now persist the data for (AbstractComponent c : componentsToPersist) { updateComponentSpec(c, em.find(ComponentSpec.class, c.getComponentId()), em, true); } em.flush(); em.getTransaction().commit(); for (AbstractComponent c : componentsToPersist) { ComponentInitializer ci = c.getCapability(ComponentInitializer.class); ci.componentSaved(); if (c.getCreationDate() == null) { ci.setCreationDate(em.find(ComponentSpec.class, c.getComponentId()).getDateCreated()); } c.getCapability(Updatable.class).setVersion(em.find(ComponentSpec.class, c.getComponentId()).getObjVersion()); c.componentSaved(); List<WeakReference<AbstractComponent>> list = cache.get(c.getComponentId()); if (list == null) { list = Collections.synchronizedList(new LinkedList<WeakReference<AbstractComponent>>()); cache.put(c.getComponentId(), list); } list.add(new WeakReference<AbstractComponent>(c)); } } catch(OptimisticLockException ole) { throw new gov.nasa.arc.mct.api.persistence.OptimisticLockException(ole); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } @Override public void delete(Collection<AbstractComponent> componentsToDelete) { EntityManager em = entityManagerFactory.createEntityManager(); try { em.getTransaction().begin(); for (AbstractComponent component:componentsToDelete) { ComponentSpec componentToDelete = em.find(ComponentSpec.class, component.getComponentId()); if (componentToDelete == null) { // component has already been deleted from database but not refreshed in the user interface continue; } TypedQuery<ComponentSpec> q = em.createNamedQuery("ComponentSpec.findReferencingComponents", ComponentSpec.class); q.setParameter("component", component.getComponentId()); List<ComponentSpec> referencingComponents = q.getResultList(); for (ComponentSpec cs:referencingComponents) { cs.getReferencedComponents().remove(componentToDelete); } em.remove(componentToDelete); } em.getTransaction().commit(); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } @Override public boolean hasComponentsTaggedBy(String tagId) { EntityManager em = null; try { em = entityManagerFactory.createEntityManager(); TypedQuery<TagAssociation> q = em.createNamedQuery("TagAssociation.getComponentsByTag", TagAssociation.class); q.setParameter("tagId", tagId); q.setMaxResults(1); return !q.getResultList().isEmpty(); } finally { if (em != null) { em.close(); } } } @Override public List<AbstractComponent> getReferencedComponents( AbstractComponent component) { List<AbstractComponent> references = new ArrayList<AbstractComponent>(); EntityManager em = entityManagerFactory.createEntityManager(); if (component.getComponentId() != null) { try { ComponentSpec reference = em.find(ComponentSpec.class, component.getComponentId()); if (reference != null) { List<ComponentSpec> referencedComponents = reference.getReferencedComponents(); for (ComponentSpec cs:referencedComponents) { if (cs != null) { AbstractComponent ac = createAbstractComponent(cs); references.add(ac); } } } } finally { em.close(); } } return references; } @Override public User getUser(String userId) { EntityManager em = entityManagerFactory.createEntityManager(); User u = null; try { MctUsers users = em.find(MctUsers.class, userId); if (users != null) { final String discipline = users.getDisciplineId().getDisciplineId(); final String uId = users.getUserId(); u = new User() { @Override public String getDisciplineId() { return discipline; } @Override public String getUserId() { return uId; } @Override public User getValidUser(String userID) { return getUser(userID); } }; } } finally { em.close(); } return u; } /** * Finds all the components by base display name regex pattern. * @param pattern - regex. * @param props <code>Properties</code> set arguments for SQL query. * @return QueryResult - search results. */ @SuppressWarnings("unchecked") public QueryResult findComponentsByBaseDisplayedNamePattern(String pattern, Properties props) { String username = PlatformAccess.getPlatform().getCurrentUser().getUserId(); pattern = pattern.isEmpty() ? "%" : pattern.replace('*', '%'); String countQuery = "select count(*) from component_spec c " + "where c.creator_user_id like :creator " + "and c.component_id not in (select component_id from component_spec where component_type = 'gov.nasa.arc.mct.core.components.TelemetryDataTaxonomyComponent' and component_name = 'All')" + "and (c.component_type != 'gov.nasa.arc.mct.core.components.MineTaxonomyComponent' or c.owner = :owner) " + "and c.component_name like :pattern ;"; String entitiesQuery = "select c.* from component_spec c " + "where c.creator_user_id like :creator " + "and c.component_id not in (select component_id from component_spec where component_type = 'gov.nasa.arc.mct.core.components.TelemetryDataTaxonomyComponent' and component_name = 'All')" + "and (c.component_type != 'gov.nasa.arc.mct.core.components.MineTaxonomyComponent' or c.owner = :owner) " + "and c.component_name like :pattern " + "limit 100"; EntityManager em = entityManagerFactory.createEntityManager(); try { Query q = em.createNativeQuery(countQuery); q.setParameter("pattern", pattern); q.setParameter("owner", username); q.setParameter("creator", (props != null && props.get("creator") != null) ? props.get("creator") : "%" ); int count = ((Number) q.getSingleResult()).intValue(); q = em.createNativeQuery(entitiesQuery, ComponentSpec.class); q.setParameter("pattern", pattern); q.setParameter("owner", username); q.setParameter("creator", (props != null && props.get("creator") != null) ? props.get("creator") : "%" ); List<ComponentSpec> daoObjects = q.getResultList(); return new QueryResult(count, daoObjects); } catch (Exception t) { LOGGER.error("error executing query", t); return null; } finally { em.close(); } } AbstractComponent newAbstractComponent(ComponentSpec cs) { return PlatformAccess.getPlatform().getComponentRegistry().newInstance(cs.getComponentType()); } private AbstractComponent createAbstractComponent(ComponentSpec cs) { AbstractComponent ac = newAbstractComponent(cs); ComponentInitializer initializer = ac.getCapability(ComponentInitializer.class); initializer.setCreationDate(cs.getDateCreated()); initializer.setCreator(cs.getCreatorUserId()); initializer.setOwner(cs.getOwner()); initializer.setId(cs.getComponentId()); ac.setExternalKey(cs.getExternalKey()); ac.setDisplayName(cs.getComponentName()); ac.getCapability(Updatable.class).setVersion(cs.getObjVersion()); ModelStatePersistence persister = ac.getCapability(ModelStatePersistence.class); if (persister != null) { persister.setModelState(cs.getModelInfo()); } // Add ac to cache List<WeakReference<AbstractComponent>> list = cache.get(cs.getComponentId()); if (list == null) { list = Collections.synchronizedList(new LinkedList<WeakReference<AbstractComponent>>()); } list.add(new WeakReference<AbstractComponent>(ac)); cache.put(cs.getComponentId(), list); return ac; } @Override public <T extends AbstractComponent> T getComponent(String externalKey, Class<T> componentType) { EntityManager em = entityManagerFactory.createEntityManager(); try { TypedQuery<ComponentSpec> q = em.createQuery("SELECT c FROM ComponentSpec c WHERE c.externalKey = :externalKey and c.componentType = :componentType", ComponentSpec.class); q.setParameter("externalKey", externalKey); q.setParameter("componentType", componentType.getName()); ComponentSpec cs = q.getResultList().get(0); AbstractComponent ac = createAbstractComponent(cs); return componentType.cast(ac); } finally { em.close(); } } private Date getCurrentTimeFromDatabase() { User currentUser = PlatformAccess.getPlatform().getCurrentUser(); if (currentUser == null) return null; String userId = currentUser.getUserId(); EntityManager em = entityManagerFactory.createEntityManager(); try { TypedQuery<Date> q = em.createQuery("SELECT CURRENT_TIMESTAMP FROM ComponentSpec c WHERE c.owner = :owner", Date.class); q.setParameter("owner", userId); return q.getSingleResult(); } finally { em.close(); } } private void iterateOverChangedComponents(ChangedComponentVisitor v) { if (lastPollTime == null) { lastPollTime = getCurrentTimeFromDatabase(); if (lastPollTime == null) return; } String query = "SELECT CURRENT_TIMESTAMP, c FROM ComponentSpec c WHERE c.lastModified BETWEEN ?1 AND CURRENT_TIMESTAMP"; EntityManager em = entityManagerFactory.createEntityManager(); try { Query q = em.createQuery(query); q.setParameter(1, lastPollTime, TemporalType.TIMESTAMP); final int MAX_CACHE_SIZE = 500; int iteration = 0; boolean done = false; while(!done) { q.setFirstResult(MAX_CACHE_SIZE * iteration); q.setMaxResults(MAX_CACHE_SIZE); @SuppressWarnings("rawtypes") List resultList = q.getResultList(); for (int i=0; i<resultList.size(); i++) { for (Object obj : (Object[]) resultList.get(i)) { if (obj instanceof ComponentSpec) v.operateOnComponent((ComponentSpec) obj); if (obj instanceof Date) lastPollTime = (Date) obj; } } done = resultList.size() < MAX_CACHE_SIZE; iteration++; em.clear(); } } catch (Exception t) { LOGGER.error("error executing query", t); } finally { em.close(); } } private void cleanCacheIfNecessary(String componentId, int latestVersion) { Cache c = entityManagerFactory.getCache(); if (c.contains(ComponentSpec.class, componentId)) { EntityManager em = entityManagerFactory.createEntityManager(); ComponentSpec cs = em.find(ComponentSpec.class, componentId); if (cs != null && cs.getObjVersion() < latestVersion) { c.evict(ComponentSpec.class, componentId); } em.close(); } } private void updateComponentIfNecessary(final ComponentSpec c, final Collection<AbstractComponent> cachedComponents) { Collection<AbstractComponent> delegateComponets = new ArrayList<AbstractComponent>(); for (final AbstractComponent ac : cachedComponents) { Updatable updatable = ac.getCapability(Updatable.class); updatable.setStaleByVersion(c.getObjVersion()); cleanCacheIfNecessary(c.getComponentId(), c.getObjVersion()); if (ac.getWorkUnitDelegate() != null) { ac.getWorkUnitDelegate().getCapability(Updatable.class).setStaleByVersion(Integer.MAX_VALUE); delegateComponets.add(ac.getWorkUnitDelegate()); } } cachedComponents.addAll(delegateComponets); for (final AbstractComponent ac: cachedComponents) { if (ac.isStale()) { ac.resetComponentProperties(new AbstractComponent.ResetPropertiesTransaction() { @Override public void perform() { Updatable updatable = ac.getCapability(Updatable.class); updatable.notifyStale(); } }); LOGGER.debug("{} updated", c.getComponentName()); } } } private int pollCounter = 0; @Override public void updateComponentsFromDatabase() { pollCounter++; iterateOverChangedComponents( new ChangedComponentVisitor() { @Override public void operateOnComponent(ComponentSpec c) { List<WeakReference<AbstractComponent>> list = cache.get(c.getComponentId()); if (list != null && !list.isEmpty()) { Collection<AbstractComponent> cachedComponents = new ArrayList<AbstractComponent>(list.size()); synchronized(list) { Iterator<WeakReference<AbstractComponent>> it = list.iterator(); while (it.hasNext()) { AbstractComponent ac = it.next().get(); if (ac != null) { cachedComponents.add(ac); } else { it.remove(); } } } if (!cachedComponents.isEmpty()) updateComponentIfNecessary(c, cachedComponents); } } } ); if (pollCounter % 1000 == 0) cleanCache(); } public interface ChangedComponentVisitor { /** * This method is invoked for each component that has changed. * @param component that has changed */ void operateOnComponent(ComponentSpec component); } @Override public List<AbstractComponent> getBootstrapComponents() { List<ComponentSpec> cslist = null; EntityManager em = entityManagerFactory.createEntityManager(); try { String userId = PlatformAccess.getPlatform().getCurrentUser().getUserId(); TypedQuery<ComponentSpec> q = em.createQuery("SELECT t.componentSpec FROM TagAssociation t where t.tag.tagId = 'bootstrap:admin' or (t.tag.tagId = 'bootstrap:creator' and t.componentSpec.creatorUserId = :user)", ComponentSpec.class); q.setParameter("user", userId); cslist = q.getResultList(); } finally { em.close(); } if (cslist != null) { List<AbstractComponent> aclist = new ArrayList<AbstractComponent>(); for (ComponentSpec cs : cslist) { AbstractComponent ac = createAbstractComponent(cs); aclist.add(ac); } return aclist; } return null; } private void cleanCache() { Iterator<String> iterator = cache.keySet().iterator(); while(iterator.hasNext()) { String componentId = iterator.next(); List<WeakReference<AbstractComponent>> list = cache.get(componentId); boolean canBeDeleted = true; synchronized(list) { for (WeakReference<AbstractComponent> r : list) { if (r.get() != null) { canBeDeleted = false; } } } if (canBeDeleted) iterator.remove(); } } @Override public void addNewUser(String userId, String groupId, AbstractComponent mysandbox, AbstractComponent dropbox) { String userDropboxesId = PlatformAccess.getPlatform().getUserDropboxes().getComponentId(); EntityManager em = entityManagerFactory.createEntityManager(); try { em.getTransaction().begin(); Disciplines group = em.find(Disciplines.class, groupId); MctUsers user = new MctUsers(); user.setUserId(userId); user.setDisciplineId(group); em.persist(user); ComponentSpec mysandboxComponentSpec = new ComponentSpec(); updateComponentSpec(mysandbox, mysandboxComponentSpec, em, true); em.persist(mysandboxComponentSpec); TagAssociationPK tagAssociationPK = new TagAssociationPK(); tagAssociationPK.setComponentId(mysandbox.getComponentId()); tagAssociationPK.setTagId("bootstrap:creator"); TagAssociation tagAssociation = new TagAssociation(); tagAssociation.setTagAssociationPK(tagAssociationPK); em.persist(tagAssociation); ComponentSpec dropboxComponentSpec = new ComponentSpec(); updateComponentSpec(dropbox, dropboxComponentSpec, em, true); em.persist(dropboxComponentSpec); ComponentSpec userDropboxes = em.find(ComponentSpec.class, userDropboxesId); userDropboxes.getReferencedComponents().add(dropboxComponentSpec); mysandboxComponentSpec.getReferencedComponents().add(dropboxComponentSpec); em.persist(userDropboxes); em.persist(mysandboxComponentSpec); em.getTransaction().commit(); } finally { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); } } @Override public Map<String, ExtendedProperties> getAllProperties(String componentId) { EntityManager em = entityManagerFactory.createEntityManager(); Map<String, ExtendedProperties> properties = new HashMap<String, ExtendedProperties>(); try { ComponentSpec cs = em.find(ComponentSpec.class, componentId); if (cs != null) { for (ViewState vs: cs.getViewStateCollection()) { properties.put(vs.getViewStatePK().getViewType(), createExtendedProperties(vs.getViewInfo())); } } return properties; } finally { em.close(); } } @Override public AbstractComponent getComponent(String externalKey, String componentType) { EntityManager em = entityManagerFactory.createEntityManager(); try { TypedQuery<ComponentSpec> q = em .createQuery( "SELECT c FROM ComponentSpec c " + "WHERE c.externalKey = :externalKey and c.componentType = :componentType", ComponentSpec.class); q.setParameter("externalKey", externalKey); q.setParameter("componentType", componentType); ComponentSpec cs = q.getResultList().get(0); AbstractComponent ac = createAbstractComponent(cs); return ac; } finally { em.close(); } } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_service_PersistenceServiceImpl.java
395
private static final ThreadLocal<Set<AbstractComponent>> components = new ThreadLocal<Set<AbstractComponent>>(){ @Override protected Set<AbstractComponent> initialValue() { return Collections.emptySet(); } };
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_service_PersistenceServiceImpl.java
396
databasePollingTimer.schedule(new TimerTask() { @Override public void run() { InternalDBPersistenceAccess.getService().updateComponentsFromDatabase(); } }, Calendar.getInstance().getTime(), 3000);
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_service_PersistenceServiceImpl.java
397
u = new User() { @Override public String getDisciplineId() { return discipline; } @Override public String getUserId() { return uId; } @Override public User getValidUser(String userID) { return getUser(userID); } };
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_service_PersistenceServiceImpl.java
398
ac.resetComponentProperties(new AbstractComponent.ResetPropertiesTransaction() { @Override public void perform() { Updatable updatable = ac.getCapability(Updatable.class); updatable.notifyStale(); } });
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_service_PersistenceServiceImpl.java
399
new ChangedComponentVisitor() { @Override public void operateOnComponent(ComponentSpec c) { List<WeakReference<AbstractComponent>> list = cache.get(c.getComponentId()); if (list != null && !list.isEmpty()) { Collection<AbstractComponent> cachedComponents = new ArrayList<AbstractComponent>(list.size()); synchronized(list) { Iterator<WeakReference<AbstractComponent>> it = list.iterator(); while (it.hasNext()) { AbstractComponent ac = it.next().get(); if (ac != null) { cachedComponents.add(ac); } else { it.remove(); } } } if (!cachedComponents.isEmpty()) updateComponentIfNecessary(c, cachedComponents); } } }
false
databasePersistence_src_main_java_gov_nasa_arc_mct_dbpersistence_service_PersistenceServiceImpl.java