code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public static void centerOnParentAndSetVisible(Window window) {
window.pack();
centerOnParent(window, window.getParent());
window.setVisible(true);
} | Pack the window, center it relative to it's parent, and set the window
visible.
@param window the window to center and show. |
public static void centerOnParent(Window window, Component parent) {
if (parent == null || !parent.isShowing()) {
// call our own centerOnScreen so we work around bug in
// setLocationRelativeTo(null)
centerOnScreen(window);
}
else {
window.setLocationRelativeTo(parent);
}
} | Center the window relative to it's parent. If the parent is null, or not showing,
the window will be centered on the screen
@param window the window to center
@param parent the parent |
public static final Dimension getDimensionFromPercent(int percentWidth, int percentHeight) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
return calcDimensionFromPercent(screenSize, percentWidth, percentHeight);
} | Return a <code>Dimension</code> whose size is defined not in terms of
pixels, but in terms of a given percent of the screen's width and height.
<P>
Use to set the preferred size of a component to a certain percentage of
the screen.
@param percentWidth percentage width of the screen, in range
<code>1..100</code>.
@param percentHeight percentage height of the screen, in range
<code>1..100</code>. |
protected void doRemovePageComponent( PageComponent pageComponent ) {
if (pageComponent == getActiveComponent())
{
this.control.removeAll();
this.control.validate();
this.control.repaint();
}
} | {@inheritDoc}
Only one pageComponent is shown at a time, so if it's the active one,
remove all components from this page. |
public void setAuthenticationToken(Authentication authentication) {
if( logger.isDebugEnabled() ) {
logger.debug("New authentication token: " + authentication);
}
HttpComponentsHttpInvokerRequestExecutor executor
= (HttpComponentsHttpInvokerRequestExecutor) getHttpInvokerRequestExecutor();
DefaultHttpClient httpClient = (DefaultHttpClient) executor.getHttpClient();
BasicCredentialsProvider provider = new BasicCredentialsProvider();
httpClient.setCredentialsProvider(provider);
httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor());
UsernamePasswordCredentials usernamePasswordCredentials;
if (authentication != null) {
usernamePasswordCredentials = new UsernamePasswordCredentials(
authentication.getName(), authentication.getCredentials().toString());
} else {
usernamePasswordCredentials = null;
}
provider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
} | Handle a change in the current authentication token.
This method will fail fast if the executor isn't a CommonsHttpInvokerRequestExecutor.
@see org.valkyriercp.security.AuthenticationAware#setAuthenticationToken(org.springframework.security.core.Authentication) |
protected boolean isEmpty(Object o) {
if (o == null) {
return true;
} else if (o instanceof String) {
return !StringUtils.hasText((String) o);
} else {
return false;
}
} | Is given object <i>empty</i> (null or empty string)? |
public final void setPageDescriptor(PageDescriptor pageDescriptor) {
Assert.notNull(pageDescriptor, "pageDescriptor");
setId(pageDescriptor.getId());
setLabel(pageDescriptor.getShowPageCommandLabel());
setIcon(pageDescriptor.getIcon());
setCaption(pageDescriptor.getCaption());
this.pageDescriptor = pageDescriptor;
} | Sets the descriptor for the page that is to be opened by this command object. This
command object will be assigned the id, label, icon, and caption from the given page
descriptor.
@param pageDescriptor The page descriptor, cannot be null.
@throws IllegalArgumentException if {@code pageDescriptor} is null. |
protected Component createContentPane() {
JPanel content = new JPanel(new BorderLayout());
Component component = super.createContentPane();
if(component != null)
content.add(component);
JProgressBar progressBar = getProgressBar();
progressBar.setIndeterminate(isIndeterminate());
progressBar.setStringPainted(isShowProgressLabel());
content.add(progressBar, BorderLayout.SOUTH);
return content;
} | Returns a component that displays an image above a progress bar.
@return A splash screen containing an image and a progress bar, never null. |
protected JProgressBar getProgressBar() {
if (progressBar == null) {
progressBar = createProgressBar();
Assert.notNull(progressBar, "createProgressBar should not return null");
}
return progressBar;
} | Returns the progress bar.
@return not null |
private String getDetailsAsHTML(String title, Level level, Throwable e) {
if (e != null) {
// convert the stacktrace into a more pleasent bit of HTML
StringBuffer html = new StringBuffer("<html>");
html.append("<h2>" + escapeXml(title) + "</h2>");
html.append("<HR size='1' noshade>");
html.append("<div></div>");
html.append("<b>Message:</b>");
html.append("<pre>");
html.append(" " + escapeXml(e.toString()));
html.append("</pre>");
html.append("<b>Level:</b>");
html.append("<pre>");
html.append(" " + level);
html.append("</pre>");
html.append("<b>Stack Trace:</b>");
html.append("<pre>");
for (StackTraceElement el : e.getStackTrace()) {
html.append(" " + el.toString().replace("<init>", "<init>") + "\n");
}
if (e.getCause() != null) {
html.append("</pre>");
html.append("<b>Cause:</b>");
html.append("<pre>");
html.append(e.getCause().getMessage());
html.append("</pre><pre>");
for (StackTraceElement el : e.getCause().getStackTrace()) {
html.append(" " + el.toString().replace("<init>", "<init>") + "\n");
}
}
html.append("</pre></html>");
return html.toString();
} else {
return null;
}
} | Creates and returns HTML representing the details of this incident info. This method is only called if
the details needs to be generated: ie: the detailed error message property of the incident info is
null. |
public void uncaughtException(Thread thread, Throwable throwable) {
if (exceptionPurger != null) {
throwable = exceptionPurger.purge(throwable);
}
for (ExceptionHandlerDelegate delegate : delegateList) {
if (delegate.hasAppropriateHandler(throwable)) {
delegate.uncaughtException(thread, throwable);
return;
}
}
// A silent exception handler should be configured if it needs to be silent
logger.error("No exception handler found for throwable", throwable);
} | Delegates the throwable to the appropriate delegate exception handler.
@param thread the thread in which the throwable occurred
@param throwable the thrown throwable |
public void valueChanged( ListSelectionEvent e ) {
if( !e.getValueIsAdjusting() ) {
// We need to install this new value into the value model, but
// we don't want to propogate it back down to the adapted selection
// model (since we are responding to a change in that model).
skipSelectionModelUpdate = true;
setValue(getSelectedRows());
skipSelectionModelUpdate = false;
}
} | /*
(non-Javadoc)
@see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent) |
public void setValue( Object newValue ) {
int[] newSelection = (int[]) newValue;
if( hasChanged(currentSelection, newSelection) ) {
int[] oldValue = currentSelection;
currentSelection = newSelection;
fireValueChange(oldValue, currentSelection);
if( !skipSelectionModelUpdate) {
// Don't want notifications while we do this
model.removeListSelectionListener(this);
// Install the selection on the adapted model
model.clearSelection();
int i = 0;
int len = newSelection.length;
while( i < len ) {
int start = newSelection[i];
while( i < len - 1 && newSelection[i] == newSelection[i + 1] - 1 ) {
i++;
}
int end = newSelection[i];
model.addSelectionInterval(start, end);
i++;
}
// Reinstall listener
model.addListSelectionListener(this);
}
}
} | Set the selection value.
@param newValue must be an integer array (int[]) |
private boolean hasChanged( int[] oldValue, int[] newValue ) {
if( oldValue.length == newValue.length ) {
for( int i = 0; i < newValue.length; i++ ) {
if( oldValue[i] != newValue[i] ) {
return true;
}
}
return false;
}
return true;
} | See if two arrays are different. |
private int[] getSelectedRows() {
int iMin = model.getMinSelectionIndex();
int iMax = model.getMaxSelectionIndex();
if( (iMin == -1) || (iMax == -1) ) {
return new int[0];
}
int[] rvTmp = new int[1 + (iMax - iMin)];
int n = 0;
for( int i = iMin; i <= iMax; i++ ) {
if( model.isSelectedIndex(i) ) {
rvTmp[n++] = i;
}
}
int[] rv = new int[n];
System.arraycopy(rvTmp, 0, rv, 0, n);
return rv;
} | Returns the indices of all selected rows in the model.
@return an array of integers containing the indices of all selected rows,
or an empty array if no row is selected |
protected ValidationListener registerMessageReceiver(String propertyName, Messagable messageReceiver) {
MessagableValidationListener messagableValidationListener = new MessagableValidationListener(propertyName,
messageReceiver);
validationResults.addValidationListener(propertyName, messagableValidationListener);
messagableValidationListener.validationResultsChanged(validationResults);
return messagableValidationListener;
} | Register a messageReceiver on a specific property. To keep things in
sync, it also triggers a first time check. (validationResultsModel can
already be populated)
@param propertyName property to listen for.
@param messageReceiver message capable component.
@return {@link ValidationListener} created during the process. |
protected ValidationListener registerGuarded(String propertyName, Guarded guarded) {
GuardedValidationListener guardedValidationListener = new GuardedValidationListener(propertyName, guarded);
validationResults.addValidationListener(propertyName, guardedValidationListener);
guardedValidationListener.validationResultsChanged(validationResults);
return guardedValidationListener;
} | Register a guarded object on a specific property. To keep things in sync,
it also triggers a first time check. (validationResultsModel can already
be populated)
@param propertyName property to listen for.
@param guarded component that needs guarding.
@return {@link ValidationListener} created during the process. |
public ViewDescriptor[] getViewDescriptors() {
Map beans = applicationContext.getBeansOfType(ViewDescriptor.class, false, false);
return (ViewDescriptor[])beans.values().toArray(new ViewDescriptor[beans.size()]);
} | {@inheritDoc} |
public ViewDescriptor getViewDescriptor(String viewName) {
Assert.notNull(viewName, "viewName");
try {
return (ViewDescriptor) applicationContext.getBean(viewName, ViewDescriptor.class);
}
catch (NoSuchBeanDefinitionException e) {
return null;
}
} | Returns the view descriptor with the given identifier, or null if no such bean definition
with the given name exists in the current application context.
@param viewName The bean name of the view descriptor that is to be retrieved from the
underlying application context. Must not be null.
@throws IllegalArgumentException if {@code viewName} is null.
@throws org.springframework.beans.factory.BeanNotOfRequiredTypeException if the bean retrieved from the underlying application
context is not of type {@link ViewDescriptor}. |
public void setLayout(FormLayout layout, JPanel panel)
{
this.panel = panel;
this.layout = layout;
panel.setLayout(layout);
cc = new CellConstraints();
row = -1;
} | Set a panel with the provided layout layout.
@param layout JGoodies FormLayout
@param panel JPanel on which the builder will place the components. |
public JComponent addBinding(Binding binding, int column, int row)
{
return this.addBinding(binding, column, row, 1, 1);
} | Add a binder to a column and a row. Equals to builder.addBinding(component, column,
row).
@param binding The binding to add
@param column The column on which the binding must be added
@param column The row on which the binding must be added
@return The component produced by the binding
@see #addBinding(Binding, int, int, int, int) |
public JComponent addBinding(Binding binding, int column, int row, int widthSpan, int heightSpan)
{
((SwingBindingFactory) getBindingFactory()).interceptBinding(binding);
JComponent component = binding.getControl();
addComponent(component, column, row, widthSpan, heightSpan);
return component;
} | Add a binder to a column and a row with width and height spanning. |
protected void showPopupMenu(MouseEvent e) {
if (onAboutToShow(e)) {
JPopupMenu popupToShow = getPopupMenu(e);
if (popupToShow == null) {
return;
}
popupToShow.show(e.getComponent(), e.getX(), e.getY());
popupToShow.setVisible(true);
}
} | Called to display the popup menu. |
public boolean close() {
boolean canClose = getAdvisor().onPreWindowClose(this);
if (canClose) {
// check if page can be closed
if (currentApplicationPage != null) {
canClose = currentApplicationPage.close();
// page cannot be closed, exit method and do not dispose
if (!canClose)
return canClose;
}
if (control != null) {
control.dispose();
control = null;
}
if (windowManager != null) {
windowManager.remove(this);
}
windowManager = null;
}
return canClose;
} | Close this window. First checks with the advisor by calling the
{@link ApplicationLifecycleAdvisor#onPreWindowClose(ApplicationWindow)}
method. Then tries to close it's currentPage. If both are successfull,
the window will be disposed and removed from the {@link WindowManager}.
@return boolean <code>true</code> if both, the advisor and the
currentPage allow the closing action. |
protected JComponent createViewToolBar() {
if(getPageComponent() instanceof AbstractEditor){
AbstractEditor editor = (AbstractEditor)getPageComponent();
return editor.getEditorToolBar();
}
return null;
} | Returns the view specific toolbar if the underlying view
implementation supports it. |
protected JComponent createViewMenuBar() {
if(getPageComponent() instanceof AbstractEditor){
AbstractEditor editor = (AbstractEditor)getPageComponent();
return editor.getEditorMenuBar();
}
return null;
} | Returns the view specific menubar if the underlying view
implementation supports it. |
public final Object buildModel(CommandGroup commandGroup)
{
Object model = buildRootModel(commandGroup);
recurse(commandGroup, model, 0);
return model;
} | Main service method of this method to call.
This builds the complete mapping object-model by traversing the complete
passed in command-group structure by performing the appropriate callbacks
to the subclass implementations of {@link #buildRootModel(CommandGroup)},
{@link #buildChildModel(Object, AbstractCommand, int)}, and
{@link #buildGroupModel(Object, CommandGroup, int)}.
Additionally,
@param commandGroup
the root of the structure for which an mapping objectmodel
will be built.
@return the build object model |
public Object getCommand(String commandId, Class requiredType) throws CommandNotOfRequiredTypeException {
return this.commandRegistry.getCommand(commandId, requiredType);
} | {@inheritDoc} |
@Override
public CommandGroup createCommandGroup(List<? extends Object> members) {
return createCommandGroup(null, members.toArray(), false, null);
} | Create a command group which holds all the given members.
@param members members to add to the group.
@return a {@link CommandGroup} which contains all the members. |
@Override
public CommandGroup createCommandGroup(String groupId, Object[] members) {
return createCommandGroup(groupId, members, false, null);
} | Create a command group which holds all the given members.
@param groupId the id to configure the group.
@param members members to add to the group.
@return a {@link CommandGroup} which contains all the members. |
@Override
public CommandGroup createCommandGroup(String groupId, List<? extends AbstractCommand> members) {
return createCommandGroup(groupId, members.toArray(), false, null);
} | Create a command group which holds all the given members.
@param groupId the id to configure the group.
@param members members to add to the group.
@return a {@link CommandGroup} which contains all the members. |
@Override
public CommandGroup createCommandGroup(String groupId, Object[] members, CommandConfigurer configurer) {
return createCommandGroup(groupId, members, false, configurer);
} | Create a command group which holds all the given members.
@param groupId the id to configure the group.
@param members members to add to the group.
@param configurer the configurer to use.
@return a {@link CommandGroup} which contains all the members. |
@Override
public CommandGroup createCommandGroup(final String groupId, final Object[] members,
final boolean exclusive, final CommandConfigurer configurer) {
final CommandGroupFactoryBean groupFactory = new CommandGroupFactoryBean(groupId, null, getCommandConfigurer(), members);
groupFactory.setExclusive(exclusive);
return groupFactory.getCommandGroup();
} | Creates a command group, configuring the group using the ObjectConfigurer
service (pulling visual configuration properties from an external
source). This method will also auto-configure contained Command members
that have not yet been configured.
@param groupId id to configure this commandGroup.
@param members members to add to the group.
@return a {@link CommandGroup} that holds the given members. |
@Override
public AuthenticationManager getAuthenticationManager() {
if(ValkyrieRepository.getInstance().getApplicationConfig().applicationContext().getBeansOfType(AuthenticationManager.class).size() != 0)
return ValkyrieRepository.getInstance().getBean(AuthenticationManager.class);
else {
return null;
}
} | Get the authentication manager in use.
@return authenticationManager instance used for authentication requests |
@Override
public Authentication doLogin(Authentication authentication) {
Authentication result = null;
try {
result = getAuthenticationManager().authenticate(authentication);
} catch (AuthenticationException e) {
logger.info("authentication failed: " + e.getMessage());
// Fire application event to advise of failed login
getApplicationConfig().applicationContext().publishEvent(new AuthenticationFailedEvent(
authentication, e));
// rethrow the exception
throw e;
}
// Handle success or failure of the authentication attempt
if (logger.isDebugEnabled()) {
logger.debug("successful login - update context holder and fire event");
}
// Commit the successful Authentication object to the secure
// ContextHolder
SecurityContextHolder.getContext().setAuthentication(result);
setAuthentication(result);
// Fire application events to advise of new login
getApplicationConfig().applicationContext().publishEvent(new AuthenticationEvent(result));
getApplicationConfig().applicationContext().publishEvent(new LoginEvent(result));
return result;
} | Process a login attempt and fire all related events. If the
authentication fails, then a {@link AuthenticationFailedEvent} is
published and the exception is rethrown. If the authentication succeeds,
then an {@link AuthenticationEvent} is published, followed by a
{@link LoginEvent}.
@param authentication
token to use for the login attempt
@return Authentication token resulting from a successful call to
{@link AuthenticationManager#authenticate(org.springframework.security.core.Authentication)}
.
@see ApplicationSecurityManager#doLogin(org.springframework.security.core.Authentication)
@throws AuthenticationException
If the authentication attempt fails |
@Override
public boolean isUserInRole(String role) {
boolean inRole = false;
Authentication authentication = getAuthentication();
if (authentication != null) {
Collection<? extends GrantedAuthority> authorities = authentication
.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (role.equals(authority.getAuthority())) {
inRole = true;
break;
}
}
}
return inRole;
} | Determine if the currently authenticated user has the role provided. Note
that role comparisons are case sensitive.
@param role
to check
@return true if the user has the role requested |
@Override
public Authentication doLogout() {
Authentication existing = getAuthentication();
// Make the Authentication object null if a SecureContext exists
SecurityContextHolder.getContext().setAuthentication(null);
setAuthentication(null);
getApplicationConfig().applicationContext().publishEvent(new AuthenticationEvent(null));
getApplicationConfig().applicationContext().publishEvent(new LogoutEvent(existing));
return existing;
} | Perform a logout. Set the current authentication token to null (in both
the per-thread security context and the global context), then publish an
{@link AuthenticationEvent} followed by a {@link LogoutEvent}.
@return Authentication token that was in place prior to the logout.
@see ApplicationSecurityManager#doLogout() |
public void afterPropertiesSet() {
// Ensure that we have our authentication manager
if (getAuthenticationManager() == null) {
if (logger.isDebugEnabled()) {
logger.debug("No AuthenticationManager defined, look for one");
}
// Try the class types in sequence
Class[] types = new Class[] { ProviderManager.class,
AuthenticationProvider.class, AuthenticationManager.class };
for (int i = 0; i < types.length; i++) {
if (tryToWire(types[i])) {
break;
}
}
}
} | Ensure that we have an authentication manager to work with. If one has
not been specifically wired in, then look for beans to "auto-wire" in.
Look for a bean of one of the following types (in order):
{@link ProviderManager}, {@link AuthenticationProvider}, and
{@link AuthenticationManager}.
@see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() |
protected <T> boolean tryToWire(Class<T> type) {
boolean success = false;
String className = type.getName();
Map<String, T> map = getApplicationConfig().applicationContext().getBeansOfType(type);
if (logger.isDebugEnabled()) {
logger.debug("Search for '" + className + "' found: " + map);
}
if (map.size() == 1) {
// Got one - wire it in
Map.Entry entry = map.entrySet().iterator().next();
String name = (String) entry.getKey();
AuthenticationManager am = (AuthenticationManager) entry.getValue();
setAuthenticationManager(am);
success = true;
if (logger.isInfoEnabled()) {
logger.info("Auto-configuration using '" + name
+ "' as authenticationManager");
}
} else if (map.size() > 1) {
if (logger.isInfoEnabled()) {
logger.info("Need a single '" + className + "', found: "
+ map.keySet());
}
} else {
// Size 0, no potentials
if (logger.isInfoEnabled()) {
logger.info("Auto-configuration did not find a suitable authenticationManager of type "
+ type);
}
}
return success;
} | Try to locate and "wire in" a suitable authentication manager.
@param type
The type of bean to look for
@return true if we found and wired a suitable bean |
public static LabelInfo valueOf(final String labelDescriptor) {
if (logger.isDebugEnabled()) {
logger.debug("Creating a new LabelInfo from label descriptor [" + labelDescriptor + "]");
}
if (!StringUtils.hasText(labelDescriptor)) {
return BLANK_LABEL_INFO;
}
StringBuffer labelText = new StringBuffer();
char mnemonicChar = '\0';
int mnemonicCharIndex = DEFAULT_MNEMONIC_INDEX;
char currentChar;
for (int i = 0; i < labelDescriptor.length();) {
currentChar = labelDescriptor.charAt(i);
int nextCharIndex = i + 1;
if (currentChar == '\\') {
//confirm that the next char is a valid escaped char, add the next char to the
//stringbuffer then skip ahead 2 chars.
checkForValidEscapedCharacter(nextCharIndex, labelDescriptor);
labelText.append(labelDescriptor.charAt(nextCharIndex));
i++;
i++;
}
else if (currentChar == '&') {
//we've found a mnemonic indicator, so...
//confirm that we haven't already found one, ...
if (mnemonicChar != '\0') {
throw new IllegalArgumentException(
"The label descriptor ["
+ labelDescriptor
+ "] can only contain one non-escaped ampersand.");
}
//...that it isn't the last character, ...
if (nextCharIndex >= labelDescriptor.length()) {
throw new IllegalArgumentException(
"The label descriptor ["
+ labelDescriptor
+ "] cannot have a non-escaped ampersand as its last character.");
}
//...and that the character that it prefixes is a valid mnemonic character.
mnemonicChar = labelDescriptor.charAt(nextCharIndex);
checkForValidMnemonicChar(mnemonicChar, labelDescriptor);
//...add it to the stringbuffer and set the mnemonic index to the position of
//the newly added char, then skip ahead 2 characters
labelText.append(mnemonicChar);
mnemonicCharIndex = labelText.length() - 1;
i++;
i++;
}
else {
labelText.append(currentChar);
i++;
}
}
// mnemonics work with VK_XXX (see KeyEvent) and only uppercase letters are used as event
return new LabelInfo(labelText.toString(), Character.toUpperCase(mnemonicChar), mnemonicCharIndex);
} | Creates a new {@code LabelInfo} instance by parsing the given label descriptor to determine
the label's text and mnemonic character. The syntax rules for the descriptor are as follows:
<ul>
<li>The descriptor may be null or an empty string, in which case, an instance with no text
or mnemonic will be returned.</li>
<li>The mnemonic character is indicated by a preceding ampersand (&).</li>
<li>A backslash character (\) can be used to escape ampersand characters that are to be
displayed as part of the label's text.</li>
<li>A double backslash (a backslash escaped by a backslash) indicates that a single backslash
is to appear in the label's text.</li>
<li>Only one non-escaped ampersand can appear in the descriptor.</li>
<li>A space character cannot be specified as the mnemonic character.</li>
</ul>
@param labelDescriptor The label descriptor. The text may be null or empty, in which case a
blank {@code LabelInfo} instance will be returned.
@return A {@code LabelInfo} instance that is described by the given descriptor.
Never returns null.
@throws IllegalArgumentException if {@code labelDescriptor} violates any of the syntax rules
described above. |
private static void checkForValidEscapedCharacter(int index, String labelDescriptor) {
if (index >= labelDescriptor.length()) {
throw new IllegalArgumentException(
"The label descriptor contains an invalid escape sequence. Backslash "
+ "characters (\\) must be followed by either an ampersand (&) or another "
+ "backslash.");
}
char escapedChar = labelDescriptor.charAt(index);
if (escapedChar != '&' && escapedChar != '\\') {
throw new IllegalArgumentException(
"The label descriptor ["
+ labelDescriptor
+ "] contains an invalid escape sequence. Backslash "
+ "characters (\\) must be followed by either an ampersand (&) or another "
+ "backslash.");
}
} | Confirms that the character at the specified index within the given label descriptor is
a valid 'escapable' character. i.e. either an ampersand or backslash.
@param index The position within the label descriptor of the character to be checked.
@param labelDescriptor The label descriptor.
@throws NullPointerException if {@code labelDescriptor} is null.
@throws IllegalArgumentException if the given {@code index} position is beyond the length
of the string or if the character at that position is not an ampersand or backslash. |
public void configureLabel(JLabel label) {
Assert.notNull(label, "label");
label.setText(this.text);
label.setDisplayedMnemonic(getMnemonic());
if (getMnemonicIndex() >= -1) {
label.setDisplayedMnemonicIndex(getMnemonicIndex());
}
} | Configures the given label with the parameters from this instance.
@param label The label that is to be configured.
@throws IllegalArgumentException if {@code label} is null. |
public void configureLabelFor(JLabel label, JComponent component) {
Assert.notNull(label, "label");
Assert.notNull(component, "component");
configureLabel(label);
if (!(component instanceof JPanel)) {
String labelText = label.getText();
if (!labelText.endsWith(":")) {
if (logger.isDebugEnabled()) {
logger.debug("Appending colon to text field label text '" + this.text + "'");
}
label.setText(labelText + ":");
}
}
label.setLabelFor(component);
} | Configures the given label with the property values described by this instance and then sets
it as the label for the given component.
@param label The label to be configured.
@param component The component that the label is 'for'.
@throws IllegalArgumentException if either argument is null.
@see JLabel#setLabelFor(java.awt.Component) |
public void configureButton(AbstractButton button) {
Assert.notNull(button);
button.setText(this.text);
button.setMnemonic(getMnemonic());
button.setDisplayedMnemonicIndex(getMnemonicIndex());
} | Configures the given button with the properties held in this instance. Note that this
instance doesn't hold any keystroke accelerator information.
@param button The button to be configured.
@throws IllegalArgumentException if {@code button} is null. |
public void switchPerspective(JideApplicationWindow window, String pageId, boolean saveCurrent){
DockingManager manager = window.getDockingManager();
PerspectiveManager perspectiveManager =
((JideApplicationPage)window.getPage()).getPerspectiveManager();
if(saveCurrent){
LayoutManager.savePageLayoutData(manager, pageId, perspectiveManager.getCurrentPerspective().getId());
}
if(!LayoutManager.loadPageLayoutData(manager, pageId, this)){
display(manager);
}
perspectiveManager.setCurrentPerspective(this);
} | /*
To switch a perspective is a three stage process:
i) Possibly save the layout of the current perspective
ii) Change the layout to that of the new perspective using an
existing layout if it exists or the display definition if not
iii) Set the current perspective in the perspective manager to
the new one. |
public void addMessage(ValidationMessage validationMessage) {
if (!validationResults.getMessages().contains(validationMessage)) {
ValidationResults oldValidationResults = validationResults;
List newMessages = new ArrayList(oldValidationResults.getMessages());
newMessages.add(validationMessage);
validationResults = new DefaultValidationResults(newMessages);
fireChangedEvents();
fireValidationResultsChanged(validationMessage.getProperty());
}
} | TODO: test |
public void removeMessage(ValidationMessage validationMessage) {
if (validationResults.getMessages().contains(validationMessage)) {
ValidationResults oldValidationResults = validationResults;
List newMessages = new ArrayList(oldValidationResults.getMessages());
newMessages.remove(validationMessage);
validationResults = new DefaultValidationResults(newMessages);
fireChangedEvents();
fireValidationResultsChanged(validationMessage.getProperty());
}
} | TODO: test |
public void replaceMessage(ValidationMessage messageToReplace, ValidationMessage replacementMessage) {
ValidationResults oldValidationResults = validationResults;
List newMessages = new ArrayList(oldValidationResults.getMessages());
final boolean containsMessageToReplace = validationResults.getMessages().contains(messageToReplace);
if (containsMessageToReplace) {
newMessages.remove(messageToReplace);
}
newMessages.add(replacementMessage);
validationResults = new DefaultValidationResults(newMessages);
fireChangedEvents();
if (containsMessageToReplace
&& !ObjectUtils.nullSafeEquals(messageToReplace.getProperty(), replacementMessage.getProperty())) {
fireValidationResultsChanged(messageToReplace.getProperty());
}
fireValidationResultsChanged(replacementMessage.getProperty());
} | TODO: test |
private void updateErrors() {
boolean oldErrors = hasErrors;
hasErrors = false;
if (validationResults.getHasErrors()) {
hasErrors = true;
}
else {
Iterator childIter = children.iterator();
while (childIter.hasNext()) {
ValidationResultsModel childModel = (ValidationResultsModel) childIter.next();
if (childModel.getHasErrors()) {
hasErrors = true;
break;
}
}
}
firePropertyChange(HAS_ERRORS_PROPERTY, oldErrors, hasErrors);
} | Revaluate the hasErrors property and fire an event if things have
changed. |
private void updateInfo() {
boolean oldInfo = hasInfo;
hasInfo = false;
if (validationResults.getHasInfo()) {
hasInfo = true;
}
else {
Iterator childIter = children.iterator();
while (childIter.hasNext()) {
ValidationResultsModel childModel = (ValidationResultsModel) childIter.next();
if (childModel.getHasInfo()) {
hasInfo = true;
break;
}
}
}
firePropertyChange(HAS_INFO_PROPERTY, oldInfo, hasInfo);
} | Revaluate the hasInfo property and fire an event if things have changed. |
private void updateWarnings() {
boolean oldWarnings = hasWarnings;
hasWarnings = false;
if (validationResults.getHasWarnings()) {
hasWarnings = true;
}
else {
Iterator childIter = children.iterator();
while (childIter.hasNext()) {
ValidationResultsModel childModel = (ValidationResultsModel) childIter.next();
if (childModel.getHasWarnings()) {
hasWarnings = true;
break;
}
}
}
firePropertyChange(HAS_WARNINGS_PROPERTY, oldWarnings, hasWarnings);
} | Revaluate the hasWarnings property and fire an event if things have
changed. |
public void add(ValidationResultsModel validationResultsModel) {
if (children.add(validationResultsModel)) {
validationResultsModel.addValidationListener(this);
validationResultsModel.addPropertyChangeListener(HAS_ERRORS_PROPERTY, this);
validationResultsModel.addPropertyChangeListener(HAS_WARNINGS_PROPERTY, this);
validationResultsModel.addPropertyChangeListener(HAS_INFO_PROPERTY, this);
if ((validationResultsModel.getMessageCount() > 0))
fireChangedEvents();
}
} | Add a validationResultsModel as a child to this one. Attach listeners and
if it already has messages, fire events.
@param validationResultsModel |
public void remove(ValidationResultsModel validationResultsModel) {
if (children.remove(validationResultsModel)) {
validationResultsModel.removeValidationListener(this);
validationResultsModel.removePropertyChangeListener(HAS_ERRORS_PROPERTY, this);
validationResultsModel.removePropertyChangeListener(HAS_WARNINGS_PROPERTY, this);
validationResultsModel.removePropertyChangeListener(HAS_INFO_PROPERTY, this);
if (validationResultsModel.getMessageCount() > 0)
fireChangedEvents();
}
} | Remove the given validationResultsModel from the list of children. Remove
listeners and if it had messages, fire events.
@param validationResultsModel |
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == HAS_ERRORS_PROPERTY)
updateErrors();
else if (evt.getPropertyName() == HAS_WARNINGS_PROPERTY)
updateWarnings();
else if (evt.getPropertyName() == HAS_INFO_PROPERTY)
updateInfo();
} | Forwarding of known property events coming from child models. Each event
triggers a specific evaluation of the parent property, which will trigger
events as needed. |
public void setIdAuthorityMap(Map<String, String> idAuthorityMap)
{
idConfigAttributeDefinitionMap = new HashMap<String, List<ConfigAttribute>>(idAuthorityMap
.size());
for (Map.Entry<String, String> entry : idAuthorityMap.entrySet())
{
idConfigAttributeDefinitionMap.put(entry.getKey(), SecurityConfig.createListFromCommaDelimitedString(entry.getValue()));
}
} | Each entry of the idConfigAttributeDefinitionMap contains a SecurityControllerId
together with its actionClusters. When using this SecurityController as
FallBack, this map can be used to configure commands that are
declared/used in code.
@param idAuthorityMap |
private void addAndPrepareControlledObject(Authorizable controlledObject)
{
controlledObjects.add(new WeakReference<Authorizable>(controlledObject));
// Properly configure the new object
boolean authorize = shouldAuthorize(getLastAuthentication(), controlledObject);
updateControlledObject(controlledObject, authorize);
} | Add a new object to the list of controlled objects. Install our last
known authorization decision so newly created objects will reflect the
current security state.
@param controlledObject
to add |
protected boolean shouldAuthorize(Authentication authentication, Authorizable controlledObject)
{
Assert.state(getAccessDecisionManager() != null, "The AccessDecisionManager can not be null!");
boolean authorize = false;
try
{
if (authentication != null)
{
List<ConfigAttribute> cad = getConfigAttributeDefinition(controlledObject);
if (cad != null)
{
getAccessDecisionManager().decide(authentication, null, cad);
}
authorize = true;
} else {
// authentication must be disabled, going through
authorize = true;
}
}
catch (AccessDeniedException e)
{
authorize = false;
// This means the secured objects should not be authorized
}
return authorize;
} | Determine if our controlled objects should be authorized based on the
provided authentication token.
@param authentication
token
@return true if should authorize |
private List<ConfigAttribute> getConfigAttributeDefinition(Authorizable controlledObject)
{
// first check on global override
if (configAttributeDefinition != null)
return configAttributeDefinition;
if (controlledObject instanceof Secured)
{
Secured securedObject = (Secured) controlledObject;
if(securedObject.getSecurityControllerId() != null) {
String securityControllerId = securedObject.getSecurityControllerId();
List<ConfigAttribute> cad = idConfigAttributeDefinitionMap.get(securityControllerId);
if (cad != null)
return cad;
}
if(securedObject.getAuthorities() != null) {
return SecurityConfig.createList(((AuthorityConfigurable) controlledObject).getAuthorities());
}
} else if(controlledObject instanceof FormModel) {
FormModel formModel = (FormModel) controlledObject;
if(formModel.getId() != null) {
String securityControllerId = formModel.getId() + ".edit";
List<ConfigAttribute> cad = idConfigAttributeDefinitionMap.get(securityControllerId);
if (cad != null)
return cad;
}
}
return null;
} | Get the ConfigAttributeDefinitions with following strategy:
<ol>
<li>Check the property configAttributeDefinition. If set, this one
overrides all others.</li>
<li>Check the configAttributeDefinitionMap. Use the securityControllerId
of the object to find the appropriate configs. When this
SecurityController is set up as fallback, the securityControllerId of
Authorizable objects can be used to link them to a particular
ActionCluster.</li>
<li>Check if the controlledObject is actually an
ActionClusterConfigurable object. If it is, it probably has it's own set
of ActionClusters defined, so return a configAttributeDefinition object
conform to this property.
</ol> |
public void setControlledObjects(List secured)
{
controlledObjects = new ArrayList<WeakReference<Authorizable>>(secured.size());
// Convert to weak references and validate the object types
for (Iterator iter = secured.iterator(); iter.hasNext();)
{
Object o = iter.next();
// Ensure that we got something we can control
if (!(o instanceof Authorizable))
{
throw new IllegalArgumentException("Controlled object must implement Authorizable, got "
+ o.getClass());
}
addAndPrepareControlledObject((Authorizable) o);
}
} | Set the objects that are to be controlled. Only beans that implement the
{@link org.springframework.security.access.event.AuthorizedEvent} interface are processed.
@param secured
List of objects to control |
protected void runAuthorization()
{
// Install the decision
for (Iterator iter = controlledObjects.iterator(); iter.hasNext();)
{
WeakReference ref = (WeakReference) iter.next();
Authorizable controlledObject = (Authorizable) ref.get();
if (controlledObject == null)
{
// Has been GCed, remove from our list
iter.remove();
}
else
{
updateControlledObject(controlledObject, shouldAuthorize(getLastAuthentication(),
controlledObject));
}
}
} | securityAwareConfigurer
Update the authorization of all controlled objects. |
protected void prepareConnection(HttpURLConnection con, int contentLength)
throws IOException {
super.prepareConnection(con, contentLength);
Authentication auth = getAuthenticationToken();
if ((auth != null) && (auth.getName() != null)
&& (auth.getCredentials() != null)) {
String base64 = auth.getName() + ":"
+ auth.getCredentials().toString();
con.setRequestProperty("Authorization", "Basic "
+ new String(Base64.encodeBase64(base64.getBytes())));
if (logger.isDebugEnabled()) {
logger.debug("HttpInvocation now presenting via BASIC authentication with token:: "
+ auth);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Unable to set BASIC authentication header as Authentication token is invalid: "
+ auth);
}
}
doPrepareConnection(con, contentLength);
} | Called every time a HTTP invocation is made.
<p>
Simply allows the parent to setup the connection, and then adds an
<code>Authorization</code> HTTP header property that will be used for
BASIC authentication. Following that a call to
{@link #doPrepareConnection} is made to allow subclasses to apply any
additional configuration desired to the connection prior to invoking the
request.
<p>
The previously saved authentication token is used to obtain the principal
and credentials. If the saved token is null, then the "Authorization"
header will not be added to the request.
@param con
the HTTP connection to prepare
@param contentLength
the length of the content to send
@throws IOException
if thrown by HttpURLConnection methods |
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
final Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// In real code optimize by preserving the rect between calls
if (stroke != null) {
final int i = (int) strokeWidth / 2;
final RoundRectangle2D.Float rect = //
new RoundRectangle2D.Float(i, i, width - strokeWidth, height - strokeWidth, arc, arc);
g2.translate(x, y);
g2.setColor(c.getBackground());
g2.fill(rect);
g2.setColor(strokeColor);
g2.setStroke(stroke);
g2.draw(rect);
} else {
final RoundRectangle2D.Float rect = new RoundRectangle2D.Float(0, 0, width, height, arc, arc);
g2.translate(x, y);
g2.setColor(c.getBackground());
g2.fill(rect);
}
} | {@inheritDoc} |
public Rectangle getInteriorRectangle(Component c, int x, int y, int width, int height) {
return RoundedBorder.getInteriorRectangle(c, this, x, y, width, height);
} | {@inheritDoc} |
public static Rectangle getInteriorRectangle(Component c, Border b, int x, int y, int width, int height) {
final Insets insets;
if (b != null) {
insets = b.getBorderInsets(c);
} else {
insets = new Insets(0, 0, 0, 0);
}
return new Rectangle(x + insets.left, //
y + insets.top, //
width - insets.right - insets.left, //
height - insets.top - insets.bottom);
} | Gets the interior rectangle.
@param c
the target component.
@param b
the border.
@param x
the x coordinate.
@param y
the y coordinate.
@param width
the width.
@param height
the height.
@return the rectangle. |
private List<Enum> getSelectableEnumsList(FormModel formModel,
String formPropertyPath, Map context) {
List<Enum> out = new ArrayList<Enum>();
Boolean nullable;
if (context.containsKey(NULLABLE_KEY)) {
nullable = (Boolean) context.get(NULLABLE_KEY);
} else {
nullable = this.nullable;
}
if (nullable) {
out.add(null);
}
for (Enum e : ((Class<Enum>) getPropertyType(formModel,
formPropertyPath)).getEnumConstants()) {
out.add(e);
}
return out;
} | Adds the <code>null</code> value if this binder is nullable. |
public void setAuthenticationToken(Authentication authentication) {
if( logger.isDebugEnabled() ) {
logger.debug( "New authentication token: " + authentication );
}
final HttpInvokerRequestExecutor hire = getHttpInvokerRequestExecutor();
if( hire instanceof BasicAuthHttpInvokerRequestExecutor ) {
if( logger.isDebugEnabled() ) {
logger.debug( "Pass it along to executor" );
}
((BasicAuthHttpInvokerRequestExecutor) hire).setAuthenticationToken( authentication );
}
} | Handle a change in the current authentication token. Pass it along to the executor
if it's of the proper type.
@see BasicAuthHttpInvokerRequestExecutor
@see AuthenticationAware#setAuthenticationToken(org.springframework.security.Authentication) |
private AgentClass validateRoomAgentClass(ApiRoom agent) {
AgentClass roomAgentClass = context
.getRoomAgentClass(agent.getClass());
if(roomAgentClass == null)
throw new IllegalStateException("You mus annotate class " + agent.getClass()
+ " with @" + RoomAgent.class.getSimpleName());
return roomAgentClass;
} | Validate room agent class to check whether room agent be annotated with {@code RoomAgent}
annotation or not
@param agent room agent object
@return structure of room agent class
@throws IllegalStateException when agent class be not annotated with {@code RoomAgent} |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
for(int i = 0 ; i < agents.length ; i++) {
createRoom(i);
}
return Boolean.TRUE;
} | Execute to create list of room |
private void createRoom(int index) {
ApiRoom agent = agents[index];
try {
CreateRoomSettings settings = createRoomSettings(agent);
User owner = CommandUtil.getSfsUser(agent.getOwner(), api);
Room room = api.createRoom(extension.getParentZone(), settings, owner);
room.setProperty(APIKey.ROOM, agent);
agent.setId(room.getId());
agent.setPasswordProtected(room.isPasswordProtected());
agent.setCommand(context.command(RoomInfo.class).room(room.getId()));
}
catch (SFSCreateRoomException e) {
throw new IllegalStateException("Can not create room " + agent.getName(), e);
}
} | Create a room at index
@param index index |
private CreateRoomSettings createRoomSettings(ApiRoom agent) {
validateRoomAgentClass(agent);
CreateRoomSettings settings = new CreateRoomSettings();
settings.setName(agent.getName());
settings.setPassword(agent.getPassword());
settings.setDynamic(agent.isDynamic());
settings.setGame(agent.isGame());
settings.setHidden(agent.isHidden());
settings.setMaxSpectators(agent.getMaxSpectators());
settings.setMaxUsers(agent.getMaxUsers());
settings.setMaxVariablesAllowed(agent.getMaxRoomVariablesAllowed());
settings.setRoomProperties(agent.getProperties());
settings.setGroupId(agent.getGroupdId());
settings.setUseWordsFilter(agent.isUseWordsFilter());
settings.setAutoRemoveMode(SFSRoomRemoveMode.fromString(agent.getRemoveMode().name()));
if(agent.getExtension() != null)
settings.setExtension(new RoomExtensionSettings(agent.getExtension().getName(), agent.getExtension().getClazz()));
return settings;
} | Create smartfox CreateRoomSettings object
@param agent room agent object
@return CreateRoomSettings object |
@Override
public Tensor forward() {
Tensor x = modInX.getOutput();
double w_k = modInW.getOutput().getValue(k);
y = new Tensor(x); // copy
y.divide(w_k);
return y;
} | Foward pass: y_i = x_i / w_k |
@Override
public void backward() {
Tensor x = modInX.getOutput();
double w_k = modInW.getOutput().getValue(k);
{
Tensor tmp = new Tensor(yAdj); // copy
tmp.divide(w_k);
modInX.getOutputAdj().elemAdd(tmp);
}
{
Tensor tmp = new Tensor(yAdj); // copy
tmp.elemMultiply(x);
tmp.divide(s.negate(s.times(w_k, w_k)));
modInW.getOutputAdj().addValue(k, tmp.getSum());
}
} | Backward pass:
dG/dx_i += dG/dy_i dy_i/dx_i = dG/dy_i / w_k
dG/dw_k += \sum_{i=1}^n dG/dy_i dy_i/dw_k = \sum_{i=1}^n dG/dy_i x_i / (- w_k^2) |
@Override
public Tensor forward() {
Tensor x = modInX.getOutput();
Tensor w = modInW.getOutput();
y = new Tensor(x); // copy
y.elemMultiply(w);
return y;
} | Foward pass: y_i = x_i * w_i |
@Override
public void backward() {
Tensor x = modInX.getOutput();
Tensor w = modInW.getOutput();
{
Tensor tmp = new Tensor(yAdj); // copy
tmp.elemMultiply(w);
modInX.getOutputAdj().elemAdd(tmp);
}
{
Tensor tmp = new Tensor(yAdj); // copy
tmp.elemMultiply(x);
modInW.getOutputAdj().elemAdd(tmp);
}
} | Backward pass:
dG/dx_i += dG/dy_i dy_i/dx_i = dG/dy_i w_i
dG/dw_i += dG/dy_i dy_i/dw_i = dG/dy_i x_i |
@Override
public <T extends ApiUser> List<T> getSpectatorsList() {
return CommandUtil.getApiUserList(room.getSpectatorsList());
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.FetchRoomInfo#getSpectatorsList() |
@Override
public <T extends ApiGameUser> List<T> getSpectatorsList(Class<?> clazz) {
return CommandUtil.getApiGameUserList(room.getSpectatorsList(), clazz);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.FetchRoomInfo#getSpectatorsList(java.lang.Class) |
@Override
public <T extends ApiUser> List<T> getPlayersList() {
return CommandUtil.getApiUserList(room.getPlayersList());
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.FetchRoomInfo#getPlayersList() |
@Override
public <T extends ApiUser> List<T> getUserList() {
return CommandUtil.getApiUserList(room.getUserList());
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.FetchRoomInfo#getUserList() |
@Override
public void addUser(ApiBaseUser user) {
try {
room.addUser(CommandUtil.getSfsUser(user, api));
} catch (SFSJoinRoomException e) {
throw new IllegalStateException(e);
}
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateRoomInfo#addUser(com.tvd12.ezyfox.core.entities.ApiBaseUser) |
@Override
public void removeUser(ApiBaseUser user) {
room.removeUser(CommandUtil.getSfsUser(user, api));
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateRoomInfo#removeUser(com.tvd12.ezyfox.core.entities.ApiBaseUser) |
@Override
public void removeAllVariables() {
List<RoomVariable> vars = room.getVariables();
for(RoomVariable var : vars) var.setNull();
api.setRoomVariables(null, room, vars, true, true, false);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateRoomInfo#removeAllVariables() |
@Override
public void setCapacity(int maxUser, int maxSpectators) {
room.setCapacity(maxUser, maxSpectators);
apiRoom.setMaxUsers(maxUser);
apiRoom.setMaxSpectators(maxSpectators);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateRoomInfo#setCapacity(int, int) |
@Override
public void setGroupId(String groupId) {
room.setGroupId(groupId);
apiRoom.setGroupdId(groupId);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateRoomInfo#setGroupId(java.lang.String) |
@Override
public void setName(String name) {
room.setName(name);
apiRoom.setName(name);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateRoomInfo#setName(java.lang.String) |
@Override
public void setOwner(ApiBaseUser owner) {
room.setOwner(CommandUtil.getSfsUser(owner, api));
apiRoom.setOwner(owner);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateRoomInfo#setOwner(com.tvd12.ezyfox.core.entities.ApiBaseUser) |
@Override
public void setPassword(String password) {
room.setPassword(password);
apiRoom.setPassword(password);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateRoomInfo#setPassword(java.lang.String) |
@Override
public void switchPlayerToSpectator(ApiBaseUser user) {
try {
room.switchPlayerToSpectator(CommandUtil.getSfsUser(user, api));
} catch (SFSRoomException e) {
throw new IllegalStateException(e);
}
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateRoomInfo#switchPlayerToSpectator(com.tvd12.ezyfox.core.entities.ApiBaseUser) |
@Override
public RoomInfo room(ApiRoom room) {
this.apiRoom = room;
this.room = CommandUtil.getSfsRoom(room, extension);
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.RoomInfo#room(com.tvd12.ezyfox.core.entities.ApiRoom) |
@Override
public RoomInfo room(String name) {
this.room = CommandUtil.getSfsRoom(name, extension);
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.RoomInfo#room(java.lang.String) |
@SuppressWarnings("unchecked")
@Override
public <T> T execute() {
User sfsUser = CommandUtil.getSfsUser(agent, api);
if(sfsUser == null) return null;
try {
AgentClassUnwrapper unwrapper = context.getUserAgentClass(agent.getClass())
.getUnwrapper();
List<UserVariable> variables = new UserAgentSerializer().serialize(unwrapper, agent);
List<UserVariable> answer = variables;
if(includedVars.size() > 0)
answer = getVariables(variables, includedVars);
answer.removeAll(getVariables(answer, excludedVars));
//update user variables on server and notify to client
if(toClient) api.setUserVariables(sfsUser, answer);
// only update user variables on server
else sfsUser.setVariables(answer);
}
catch (SFSVariableException e) {
throw new IllegalStateException(e);
}
return (T)agent;
} | Execute to update user variables |
@Override
public UpdateUser include(String... varnames) {
includedVars.addAll(Arrays.asList(varnames));
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateUser#include(java.lang.String[]) |
@Override
public UpdateUser exclude(String... varnames) {
excludedVars.addAll(Arrays.asList(varnames));
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.UpdateUser#exclude(java.lang.String[]) |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
User sfsSender = CommandUtil.getSfsUser(sender, api);
Room sfsRoom = CommandUtil.getSfsRoom(room, extension);
if(sfsSender == null || sfsRoom == null)
return Boolean.FALSE;
message = (message == null) ? "" : message;
ISFSObject sfsParams = null;
if(params != null) {
MessageParamsClass clazz = context.getMessageParamsClass(params.getClass());
if(clazz != null)
sfsParams = new ResponseParamSerializer().object2params(clazz.getUnwrapper(), params);
}
if(sfsParams == null) sfsParams = new SFSObject();
api.sendPublicMessage(sfsRoom, sfsSender, message, sfsParams);
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
public void add(Sentence sentence) {
if (sentence.getAlphabet() != alphabet) {
throw new IllegalArgumentException("Alphabets do not match.");
}
addSentenceToAlphabet(sentence);
sents.add(sentence);
numTokens += sentence.size();
} | TODO: should this be private? |
public Set<String> getVocab() {
Set<String> vocab = new HashSet<String>();
for (Sentence sent : this) {
for (String label : sent) {
vocab.add(label);
}
}
return vocab;
} | Vocabulary of the sentences. |
public static <R> ImmutableGrid<R> of(int rowCount, int columnCount) {
return new EmptyGrid<R>(rowCount, columnCount);
} | Obtains an empty immutable grid of the specified row-column count.
@param <R> the type of the value
@param rowCount the number of rows, zero or greater
@param columnCount the number of columns, zero or greater
@return the empty immutable grid, not null |
public static <R> ImmutableGrid<R> of(int rowCount, int columnCount, int row, int column, R value) {
return new SingletonGrid<R>(rowCount, columnCount, row, column, value);
} | Obtains an immutable grid of the specified row-column count with a single cell.
@param <R> the type of the value
@param rowCount the number of rows, zero or greater
@param columnCount the number of columns, zero or greater
@param row the row of the single cell, zero or greater
@param column the column of the single cell, zero or greater
@param value the value of the single cell, not null
@return the empty immutable grid, not null |
public static <R> ImmutableGrid<R> copyOf(int rowCount, int columnCount, Cell<R> cell) {
if (cell == null) {
throw new IllegalArgumentException("Cell must not be null");
}
return new SingletonGrid<R>(rowCount, columnCount, cell);
} | Obtains an immutable grid with one cell.
@param <R> the type of the value
@param rowCount the number of rows, zero or greater
@param columnCount the number of columns, zero or greater
@param cell the cell that the grid should contain, not null
@return the immutable grid, not null
@throws IndexOutOfBoundsException if either index is less than zero |
public static <R> ImmutableGrid<R> copyOf(int rowCount, int columnCount, Iterable<? extends Cell<R>> cells) {
if (cells == null) {
throw new IllegalArgumentException("Cells must not be null");
}
if (!cells.iterator().hasNext()) {
return new EmptyGrid<R>(rowCount, columnCount);
}
return new SparseImmutableGrid<R>(rowCount, columnCount, cells);
} | Obtains an immutable grid by copying a set of cells.
@param <R> the type of the value
@param rowCount the number of rows, zero or greater
@param columnCount the number of columns, zero or greater
@param cells the cells to copy, not null
@return the immutable grid, not null
@throws IndexOutOfBoundsException if either index is less than zero |
public static <R> ImmutableGrid<R> copyOfDeriveCounts(Iterable<? extends Cell<R>> cells) {
if (cells == null) {
throw new IllegalArgumentException("Cells must not be null");
}
if (!cells.iterator().hasNext()) {
return new EmptyGrid<R>();
}
int rowCount = 0;
int columnCount = 0;
for (Cell<R> cell : cells) {
rowCount = Math.max(rowCount, cell.getRow());
columnCount = Math.max(columnCount, cell.getColumn());
}
return new SparseImmutableGrid<R>(rowCount + 1, columnCount + 1, cells);
} | Obtains an immutable grid by copying a set of cells, deriving the row and column count.
<p>
The row and column counts are calculated as the maximum row and column specified.
@param <R> the type of the value
@param cells the cells to copy, not null
@return the immutable grid, not null
@throws IndexOutOfBoundsException if either index is less than zero |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.