text
stringlengths 30
1.67M
|
|---|
<s> package com . mousefeed . eclipse ; import static org . apache . commons . lang . Validate . isTrue ; import static org . apache . commons . lang . Validate . notNull ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FormAttachment ; import org . eclipse . swt . layout . FormData ; import org . eclipse . swt . layout . FormLayout ; import org . eclipse . swt . widgets . Control ; public final class Layout { public static final int STACKED_V_OFFSET = <NUM_LIT:10> ; public static final int H_OFFSET = <NUM_LIT:10> ; public static final int STACKED_LABEL_V_OFFSET = <NUM_LIT:0> ; public static final int WINDOW_MARGIN = <NUM_LIT:10> ; public static final int WHOLE_SIZE = <NUM_LIT:100> ; private Layout ( ) { } public static FormData placeUnder ( final Control control , final Control aboveControl , final int gap ) { notNull ( control ) ; isTrue ( aboveControl == null || control . getParent ( ) . equals ( aboveControl . getParent ( ) ) ) ; isTrue ( control . getParent ( ) . getLayout ( ) instanceof FormLayout ) ; isTrue ( gap >= <NUM_LIT:0> ) ; final FormData formData = new FormData ( ) ; formData . left = aboveControl == null ? getLeftAttachment ( ) : new FormAttachment ( aboveControl , <NUM_LIT:0> , SWT . LEFT ) ; final int offset = aboveControl == null ? WINDOW_MARGIN : gap ; formData . top = new FormAttachment ( aboveControl , offset ) ; control . setLayoutData ( formData ) ; return formData ; } private static FormAttachment getLeftAttachment ( ) { return new FormAttachment ( <NUM_LIT:0> , WINDOW_MARGIN ) ; } } </s>
|
<s> package com . mousefeed . eclipse ; import static org . apache . commons . lang . Validate . notNull ; import java . lang . reflect . Field ; import org . eclipse . core . commands . Command ; import org . eclipse . core . commands . ParameterizedCommand ; import org . eclipse . ui . menus . CommandContributionItem ; public class CommandContributionItemCommandLocator { private static final String COMMAND_FIELD = "<STR_LIT>" ; public CommandContributionItemCommandLocator ( ) { } public Command get ( final CommandContributionItem item ) { final ParameterizedCommand parCommand = getItemParCommand ( item ) ; return parCommand == null ? null : parCommand . getCommand ( ) ; } private ParameterizedCommand getItemParCommand ( final CommandContributionItem item ) { final Field commandField = getCommandField ( ) ; try { commandField . setAccessible ( true ) ; return ( ParameterizedCommand ) commandField . get ( item ) ; } catch ( final SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( final IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( final IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } private Field getCommandField ( ) { try { final Field commandField = CommandContributionItem . class . getDeclaredField ( COMMAND_FIELD ) ; notNull ( commandField ) ; return commandField ; } catch ( final SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( final NoSuchFieldException e ) { throw new RuntimeException ( e ) ; } } } </s>
|
<s> package com . mousefeed . eclipse ; import static org . apache . commons . lang . Validate . isTrue ; import com . mousefeed . client . collector . Collector ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . plugin . AbstractUIPlugin ; public class Activator extends AbstractUIPlugin { public static final String PLUGIN_ID = "<STR_LIT>" ; private static Activator plugin ; private final Collector collector = new Collector ( ) ; public Activator ( ) { isTrue ( plugin == null ) ; plugin = this ; } public static Activator getDefault ( ) { return plugin ; } public static ImageDescriptor getImageDescriptor ( final String path ) { return imageDescriptorFromPlugin ( PLUGIN_ID , path ) ; } public Collector getCollector ( ) { return collector ; } } </s>
|
<s> package com . mousefeed . eclipse ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . graphics . Font ; class DestroyFontDisposeListener implements DisposeListener { private final Font newFont ; public DestroyFontDisposeListener ( final Font newFont ) { this . newFont = newFont ; } public void widgetDisposed ( final DisposeEvent e ) { newFont . dispose ( ) ; } } </s>
|
<s> package com . mousefeed . eclipse ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IStartup ; import org . eclipse . ui . PlatformUI ; public class Startup implements IStartup { public Startup ( ) { } public void earlyStartup ( ) { getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { getDisplay ( ) . addFilter ( SWT . Selection , new GlobalSelectionListener ( ) ) ; } } ) ; } public Display getDisplay ( ) { return PlatformUI . getWorkbench ( ) . getDisplay ( ) ; } } </s>
|
<s> package com . mousefeed . eclipse ; import com . mousefeed . client . Messages ; import org . eclipse . jface . bindings . TriggerSequence ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . keys . IBindingService ; public class LastActionInvocationRemiderFactory { private static final String CONFIGURE_ACTION_INVOCATION_ACTION_ID = "<STR_LIT>" ; private static final Messages MESSAGES = new Messages ( LastActionInvocationRemiderFactory . class ) ; public LastActionInvocationRemiderFactory ( ) { } public String getText ( ) { final TriggerSequence [ ] bindings = getBindingService ( ) . getActiveBindingsFor ( CONFIGURE_ACTION_INVOCATION_ACTION_ID ) ; final String binding = bindings . length == <NUM_LIT:0> ? MESSAGES . get ( "<STR_LIT>" ) : bindings [ <NUM_LIT:0> ] . format ( ) ; return MESSAGES . get ( "<STR_LIT:text>" , binding ) ; } private IBindingService getBindingService ( ) { return ( IBindingService ) getWorkbench ( ) . getAdapter ( IBindingService . class ) ; } private IWorkbench getWorkbench ( ) { return PlatformUI . getWorkbench ( ) ; } } </s>
|
<s> package com . mousefeed . eclipse . commands ; import static com . mousefeed . eclipse . Layout . STACKED_V_OFFSET ; import static com . mousefeed . eclipse . Layout . placeUnder ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . Messages ; import com . mousefeed . client . OnWrongInvocationMode ; import com . mousefeed . client . collector . AbstractActionDesc ; import com . mousefeed . eclipse . preferences . ActionOnWrongInvocationMode ; import com . mousefeed . eclipse . preferences . PreferenceAccessor ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FormLayout ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; public class ConfigureActionInvocationDialog extends Dialog { private static final Messages MESSAGES = new Messages ( ConfigureActionInvocationDialog . class ) ; private static final int DEFAULT_ON_WRONG_INVOCATION_MODE_IDX = <NUM_LIT:0> ; private final AbstractActionDesc actionDesc ; private Combo onWrongInvocationModeCombo ; private final PreferenceAccessor preferences = PreferenceAccessor . getInstance ( ) ; private final OnWrongInvocationModeUI onWrongInvocationModeUI = new OnWrongInvocationModeUI ( ) ; public ConfigureActionInvocationDialog ( final Shell parentShell , final AbstractActionDesc actionDesc ) { super ( parentShell ) ; notNull ( parentShell ) ; notNull ( actionDesc ) ; this . actionDesc = actionDesc ; } @ Override protected Control createDialogArea ( final Composite parent ) { final Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setLayout ( new FormLayout ( ) ) ; Control c ; c = createActionNameLabel ( composite , null ) ; c = onWrongInvocationModeUI . createLabel ( composite , c , MESSAGES . get ( "<STR_LIT>" ) ) ; onWrongInvocationModeCombo = onWrongInvocationModeUI . createCombo ( composite , c ) ; onWrongInvocationModeCombo . add ( getDefaultInvocationMode ( ) , <NUM_LIT:0> ) ; updateOnWrongInvocationModeCombo ( preferences . getOnWrongInvocationMode ( actionDesc . getId ( ) ) ) ; applyDialogFont ( composite ) ; return composite ; } @ Override protected void configureShell ( final Shell shell ) { super . configureShell ( shell ) ; shell . setText ( MESSAGES . get ( "<STR_LIT:title>" , actionDesc . getLabel ( ) ) ) ; } private Control createActionNameLabel ( final Composite container , final Control above ) { notNull ( container ) ; final Label label = new Label ( container , SWT . NULL ) ; final String text = MESSAGES . get ( "<STR_LIT>" , actionDesc . getLabel ( ) ) ; label . setText ( text ) ; placeUnder ( label , above , STACKED_V_OFFSET ) ; return label ; } @ Override protected void okPressed ( ) { final OnWrongInvocationMode mode = getSelectedOnWrongInvocationMode ( ) ; if ( mode == null ) { preferences . removeOnWrongInvocaitonMode ( actionDesc . getId ( ) ) ; } else { final ActionOnWrongInvocationMode actionMode = new ActionOnWrongInvocationMode ( actionDesc ) ; actionMode . setOnWrongInvocationMode ( getSelectedOnWrongInvocationMode ( ) ) ; preferences . setOnWrongInvocationMode ( actionMode ) ; } super . okPressed ( ) ; } private void updateOnWrongInvocationModeCombo ( final OnWrongInvocationMode mode ) { onWrongInvocationModeCombo . setText ( mode == null ? getDefaultInvocationMode ( ) : mode . getLabel ( ) ) ; } private OnWrongInvocationMode getSelectedOnWrongInvocationMode ( ) { final int i = onWrongInvocationModeCombo . getSelectionIndex ( ) ; return i == DEFAULT_ON_WRONG_INVOCATION_MODE_IDX ? null : OnWrongInvocationMode . values ( ) [ i - <NUM_LIT:1> ] ; } private String getDefaultInvocationMode ( ) { return MESSAGES . get ( "<STR_LIT>" ) ; } } </s>
|
<s> package com . mousefeed . eclipse . commands ; import static com . mousefeed . eclipse . Layout . STACKED_LABEL_V_OFFSET ; import static com . mousefeed . eclipse . Layout . STACKED_V_OFFSET ; import static com . mousefeed . eclipse . Layout . WHOLE_SIZE ; import static com . mousefeed . eclipse . Layout . WINDOW_MARGIN ; import static com . mousefeed . eclipse . Layout . placeUnder ; import static org . apache . commons . lang . Validate . isTrue ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . OnWrongInvocationMode ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FormAttachment ; import org . eclipse . swt . layout . FormData ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; public class OnWrongInvocationModeUI { public OnWrongInvocationModeUI ( ) { } public Label createLabel ( final Composite container , final Control aboveControl , final String labelText ) { notNull ( container ) ; notNull ( labelText ) ; final Label label = new Label ( container , SWT . NULL ) ; label . setText ( labelText ) ; placeUnder ( label , aboveControl , STACKED_V_OFFSET ) ; return label ; } public Combo createCombo ( final Composite container , final Control aboveControl ) { notNull ( container ) ; isTrue ( aboveControl == null || aboveControl instanceof Label ) ; final Combo combo = new Combo ( container , SWT . READ_ONLY ) ; combo . setItems ( OnWrongInvocationMode . getLabels ( ) ) ; final FormData formData = placeUnder ( combo , aboveControl , STACKED_LABEL_V_OFFSET ) ; formData . right = new FormAttachment ( WHOLE_SIZE , - WINDOW_MARGIN ) ; return combo ; } } </s>
|
<s> package com . mousefeed . eclipse . commands ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . Messages ; import com . mousefeed . client . collector . AbstractActionDesc ; import com . mousefeed . client . collector . Collector ; import com . mousefeed . eclipse . Activator ; import java . util . Map ; import org . eclipse . core . commands . AbstractHandler ; import org . eclipse . core . commands . ExecutionEvent ; import org . eclipse . core . commands . ExecutionException ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . commands . IElementUpdater ; import org . eclipse . ui . handlers . HandlerUtil ; import org . eclipse . ui . menus . UIElement ; public class ConfigureActionInvocationHandler extends AbstractHandler implements IElementUpdater { private static final Messages MESSAGES = new Messages ( ConfigureActionInvocationHandler . class ) ; private final Collector collector = Activator . getDefault ( ) . getCollector ( ) ; public ConfigureActionInvocationHandler ( ) { } public Object execute ( final ExecutionEvent event ) throws ExecutionException { if ( getLastAction ( ) == null ) { return null ; } final IWorkbenchWindow window = HandlerUtil . getActiveWorkbenchWindowChecked ( event ) ; final ConfigureActionInvocationDialog dlg = new ConfigureActionInvocationDialog ( window . getShell ( ) , getLastAction ( ) ) ; dlg . open ( ) ; return null ; } @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) public void updateElement ( final UIElement element , final Map parameters ) { notNull ( element ) ; element . setText ( MESSAGES . get ( "<STR_LIT>" , getLastAction ( ) . getLabel ( ) ) ) ; } private AbstractActionDesc getLastAction ( ) { return collector . getLastAction ( ) ; } } </s>
|
<s> package com . mousefeed . eclipse ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . collector . AbstractActionDesc ; import org . eclipse . core . commands . Command ; import org . eclipse . core . commands . common . NotDefinedException ; import org . eclipse . jface . bindings . TriggerSequence ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . keys . IBindingService ; import org . eclipse . ui . menus . CommandContributionItem ; class CommandActionDescGenerator { private final CommandContributionItemCommandLocator locator = new CommandContributionItemCommandLocator ( ) ; private final IBindingService bindingService ; public CommandActionDescGenerator ( ) { bindingService = ( IBindingService ) PlatformUI . getWorkbench ( ) . getAdapter ( IBindingService . class ) ; } public AbstractActionDesc generate ( final CommandContributionItem commandContributionItem ) { notNull ( commandContributionItem ) ; final ActionDescImpl actionDesc = new ActionDescImpl ( ) ; final Command command = locator . get ( commandContributionItem ) ; if ( command == null ) { return null ; } try { actionDesc . setLabel ( command . getName ( ) ) ; } catch ( final NotDefinedException e ) { throw new RuntimeException ( e ) ; } final String commandId = command . getId ( ) ; actionDesc . setDef ( commandId ) ; final TriggerSequence binding = bindingService . getBestActiveBindingFor ( commandId ) ; if ( binding != null ) { actionDesc . setAccelerator ( binding . format ( ) ) ; } return actionDesc ; } } </s>
|
<s> package com . mousefeed . eclipse ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . collector . AbstractActionDesc ; import org . eclipse . core . commands . Command ; import org . eclipse . core . commands . common . NotDefinedException ; import org . eclipse . e4 . ui . workbench . renderers . swt . HandledContributionItem ; import org . eclipse . jface . bindings . TriggerSequence ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . keys . IBindingService ; @ SuppressWarnings ( "<STR_LIT>" ) class HandledActionDescGenerator { private final HandledContributionItemCommandLocator locator = new HandledContributionItemCommandLocator ( ) ; private final IBindingService bindingService ; public HandledActionDescGenerator ( ) { bindingService = ( IBindingService ) PlatformUI . getWorkbench ( ) . getAdapter ( IBindingService . class ) ; } public AbstractActionDesc generate ( final HandledContributionItem handledContributionItem ) { notNull ( handledContributionItem ) ; final ActionDescImpl actionDesc = new ActionDescImpl ( ) ; final Command command = locator . get ( handledContributionItem ) ; if ( command == null ) { return null ; } try { actionDesc . setLabel ( command . getName ( ) ) ; } catch ( final NotDefinedException e ) { throw new RuntimeException ( e ) ; } final String commandId = command . getId ( ) ; actionDesc . setDef ( commandId ) ; final TriggerSequence binding = bindingService . getBestActiveBindingFor ( commandId ) ; if ( binding != null ) { actionDesc . setAccelerator ( binding . format ( ) ) ; } return actionDesc ; } } </s>
|
<s> package com . mousefeed . eclipse . preferences ; import static org . apache . commons . lang . StringUtils . isNotBlank ; import static org . apache . commons . lang . Validate . isTrue ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . OnWrongInvocationMode ; import com . mousefeed . client . collector . AbstractActionDesc ; import java . io . Serializable ; import java . util . Comparator ; public class ActionOnWrongInvocationMode implements Cloneable { private String id ; private String label ; private OnWrongInvocationMode onWrongInvocationMode ; public ActionOnWrongInvocationMode ( ) { } public ActionOnWrongInvocationMode ( final AbstractActionDesc actionDesc ) { notNull ( actionDesc ) ; setId ( actionDesc . getId ( ) ) ; setLabel ( actionDesc . getLabel ( ) ) ; } @ Override public Object clone ( ) throws CloneNotSupportedException { return super . clone ( ) ; } public String getId ( ) { return id ; } public void setId ( final String id ) { isTrue ( isNotBlank ( id ) ) ; this . id = id ; } public String getLabel ( ) { return label ; } public void setLabel ( final String label ) { isTrue ( isNotBlank ( label ) ) ; this . label = label ; } public OnWrongInvocationMode getOnWrongInvocationMode ( ) { return onWrongInvocationMode ; } public void setOnWrongInvocationMode ( final OnWrongInvocationMode onWrongInvocationMode ) { notNull ( onWrongInvocationMode ) ; this . onWrongInvocationMode = onWrongInvocationMode ; } public static class LabelComparator implements Comparator < ActionOnWrongInvocationMode > , Serializable { static final long serialVersionUID = <NUM_LIT:1> ; public LabelComparator ( ) { } public int compare ( final ActionOnWrongInvocationMode mode1 , final ActionOnWrongInvocationMode mode2 ) { return mode1 . getLabel ( ) . compareTo ( mode2 . getLabel ( ) ) ; } } } </s>
|
<s> package com . mousefeed . eclipse . preferences ; import static com . mousefeed . eclipse . preferences . PreferenceConstants . P_DEFAULT_ON_WRONG_INVOCATION_MODE ; import static com . mousefeed . eclipse . preferences . PreferenceConstants . P_INVOCATION_CONTROL_ENABLED ; import static com . mousefeed . eclipse . preferences . PreferenceConstants . P_CONFIGURE_KEYBOARD_SHORTCUT_ENABLED ; import static com . mousefeed . eclipse . preferences . PreferenceConstants . P_CONFIGURE_KEYBOARD_SHORTCUT_THRESHOLD ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . OnWrongInvocationMode ; import com . mousefeed . eclipse . Activator ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileReader ; import java . io . FileWriter ; import java . io . IOException ; import java . io . Reader ; import java . io . Writer ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . WorkbenchException ; import org . eclipse . ui . XMLMemento ; public class PreferenceAccessor { static final String ACTIONS_WRONG_INVOCATION_MODE_FILE = "<STR_LIT>" ; private static final PreferenceAccessor INSTANCE = new PreferenceAccessor ( ) ; private static final String TAG_ACTIONS_WRONG_INVOCATION_MODE = "<STR_LIT>" ; private static final String TAG_ACTION = "<STR_LIT>" ; private static final String TAG_ACTION_ID = "<STR_LIT:id>" ; private static final String TAG_ACTION_LABEL = "<STR_LIT:label>" ; private static final String TAG_ON_WRONG_INVOCATION_MODE = "<STR_LIT>" ; private final Map < String , ActionOnWrongInvocationMode > actionsOnWrongMode = new HashMap < String , ActionOnWrongInvocationMode > ( ) ; PreferenceAccessor ( ) { loadActionsOnWrongInvocationMode ( ) ; } public static PreferenceAccessor getInstance ( ) { return INSTANCE ; } public boolean isInvocationControlEnabled ( ) { return getPreferenceStore ( ) . getBoolean ( P_INVOCATION_CONTROL_ENABLED ) ; } public void storeInvocationControlEnabled ( final boolean invocationControlEnabled ) { getPreferenceStore ( ) . setValue ( P_INVOCATION_CONTROL_ENABLED , invocationControlEnabled ) ; } public boolean isConfigureKeyboardShortcutEnabled ( ) { return getPreferenceStore ( ) . getBoolean ( P_CONFIGURE_KEYBOARD_SHORTCUT_ENABLED ) ; } public void storeConfigureKeyboardShortcutEnabled ( final boolean configureKeyboardShortcutEnabled ) { getPreferenceStore ( ) . setValue ( P_CONFIGURE_KEYBOARD_SHORTCUT_ENABLED , configureKeyboardShortcutEnabled ) ; } public int getConfigureKeyboardShortcutThreshold ( ) { return getPreferenceStore ( ) . getInt ( P_CONFIGURE_KEYBOARD_SHORTCUT_THRESHOLD ) ; } public void storeConfigureKeyboardShortcutThreshold ( final int configureKeyboardShortcutThreshold ) { getPreferenceStore ( ) . setValue ( P_CONFIGURE_KEYBOARD_SHORTCUT_THRESHOLD , configureKeyboardShortcutThreshold ) ; } public OnWrongInvocationMode getOnWrongInvocationMode ( ) { final String stored = getPreferenceStore ( ) . getString ( P_DEFAULT_ON_WRONG_INVOCATION_MODE ) ; return stored == null ? OnWrongInvocationMode . DEFAULT : OnWrongInvocationMode . valueOf ( stored ) ; } public OnWrongInvocationMode getOnWrongInvocationMode ( final String actionId ) { notNull ( actionId ) ; final ActionOnWrongInvocationMode mode = actionsOnWrongMode . get ( actionId ) ; return mode == null ? null : mode . getOnWrongInvocationMode ( ) ; } public void setOnWrongInvocationMode ( final ActionOnWrongInvocationMode settings ) { notNull ( settings ) ; actionsOnWrongMode . put ( settings . getId ( ) , settings ) ; saveActionsOnWrongInvocationMode ( ) ; } public Collection < ActionOnWrongInvocationMode > getActionsOnWrongInvocationMode ( ) { return actionsOnWrongMode . values ( ) ; } public void setActionsOnWrongInvocationMode ( final Collection < ActionOnWrongInvocationMode > settings ) { this . actionsOnWrongMode . clear ( ) ; for ( ActionOnWrongInvocationMode mode : settings ) { final ActionOnWrongInvocationMode clone ; try { clone = ( ActionOnWrongInvocationMode ) mode . clone ( ) ; } catch ( final CloneNotSupportedException e ) { throw new RuntimeException ( ) ; } this . actionsOnWrongMode . put ( clone . getId ( ) , clone ) ; } saveActionsOnWrongInvocationMode ( ) ; } public void removeOnWrongInvocaitonMode ( final String actionId ) { notNull ( actionId ) ; actionsOnWrongMode . remove ( actionId ) ; saveActionsOnWrongInvocationMode ( ) ; } public void storeOnWrongInvocationMode ( final OnWrongInvocationMode value ) { notNull ( value ) ; getPreferenceStore ( ) . setValue ( P_DEFAULT_ON_WRONG_INVOCATION_MODE , value . name ( ) ) ; } private void loadActionsOnWrongInvocationMode ( ) { final File file = getActionsWrongInvocationModeFile ( ) ; if ( ! file . exists ( ) || file . length ( ) == <NUM_LIT:0> ) { return ; } Reader reader = null ; try { reader = new FileReader ( file ) ; final XMLMemento memento = XMLMemento . createReadRoot ( reader ) ; loadActionsOnWrongInvocationMode ( memento ) ; } catch ( final FileNotFoundException ignore ) { } catch ( final WorkbenchException e ) { throw new RuntimeException ( e ) ; } finally { try { if ( reader != null ) { reader . close ( ) ; } } catch ( final IOException e ) { throw new RuntimeException ( e ) ; } } } private void loadActionsOnWrongInvocationMode ( final XMLMemento memento ) { actionsOnWrongMode . clear ( ) ; final IMemento [ ] children = memento . getChildren ( TAG_ACTION ) ; for ( IMemento child : children ) { final ActionOnWrongInvocationMode mode = new ActionOnWrongInvocationMode ( ) ; mode . setLabel ( child . getString ( TAG_ACTION_LABEL ) ) ; mode . setId ( child . getString ( TAG_ACTION_ID ) ) ; mode . setOnWrongInvocationMode ( OnWrongInvocationMode . valueOf ( child . getString ( TAG_ON_WRONG_INVOCATION_MODE ) ) ) ; actionsOnWrongMode . put ( mode . getId ( ) , mode ) ; } } private void saveActionsOnWrongInvocationMode ( ) { final XMLMemento memento = createActionsOnWrongInvocationModeMemento ( ) ; Writer writer = null ; try { writer = new FileWriter ( getActionsWrongInvocationModeFile ( ) ) ; memento . save ( writer ) ; } catch ( final IOException e ) { throw new RuntimeException ( e ) ; } finally { try { if ( writer != null ) { writer . close ( ) ; } } catch ( final IOException e ) { throw new RuntimeException ( e ) ; } } } private XMLMemento createActionsOnWrongInvocationModeMemento ( ) { final XMLMemento memento = XMLMemento . createWriteRoot ( TAG_ACTIONS_WRONG_INVOCATION_MODE ) ; for ( ActionOnWrongInvocationMode val : actionsOnWrongMode . values ( ) ) { final IMemento actionMemento = memento . createChild ( TAG_ACTION ) ; actionMemento . putString ( TAG_ACTION_ID , val . getId ( ) ) ; actionMemento . putString ( TAG_ACTION_LABEL , val . getLabel ( ) ) ; actionMemento . putString ( TAG_ON_WRONG_INVOCATION_MODE , val . getOnWrongInvocationMode ( ) . name ( ) ) ; } return memento ; } private IPreferenceStore getPreferenceStore ( ) { return Activator . getDefault ( ) . getPreferenceStore ( ) ; } File getActionsWrongInvocationModeFile ( ) { if ( Activator . getDefault ( ) == null ) { return new File ( "<STR_LIT>" ) ; } return Activator . getDefault ( ) . getStateLocation ( ) . append ( ACTIONS_WRONG_INVOCATION_MODE_FILE ) . toFile ( ) ; } } </s>
|
<s> package com . mousefeed . eclipse . preferences ; import static com . mousefeed . eclipse . Layout . STACKED_V_OFFSET ; import static com . mousefeed . eclipse . Layout . WHOLE_SIZE ; import static com . mousefeed . eclipse . Layout . WINDOW_MARGIN ; import static com . mousefeed . eclipse . Layout . placeUnder ; import static com . mousefeed . eclipse . preferences . PreferenceConstants . CONFIGURE_KEYBOARD_SHORTCUT_ENABLED_DEFAULT ; import static com . mousefeed . eclipse . preferences . PreferenceConstants . CONFIGURE_KEYBOARD_SHORTCUT_THRESHOLD_DEFAULT ; import static com . mousefeed . eclipse . preferences . PreferenceConstants . INVOCATION_CONTROL_ENABLED_DEFAULT ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . Messages ; import com . mousefeed . client . OnWrongInvocationMode ; import com . mousefeed . eclipse . Activator ; import com . mousefeed . eclipse . commands . OnWrongInvocationModeUI ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . FormAttachment ; import org . eclipse . swt . layout . FormData ; import org . eclipse . swt . layout . FormLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Spinner ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; public class ActionInvocationPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final Messages MESSAGES = new Messages ( ActionInvocationPreferencePage . class ) ; private final PreferenceAccessor preferences = PreferenceAccessor . getInstance ( ) ; private Button invocationControlEnabledCheckbox ; private Button configureKeyboardShortcutCheckbox ; private Spinner configureKeyboardShortcutThreshold ; private Combo onWrongInvocationModeCombo ; private final OnWrongInvocationModeUI onWrongInvocationModeUI = new OnWrongInvocationModeUI ( ) ; private ActionInvocationModeControl actionModeControl ; public ActionInvocationPreferencePage ( ) { super ( ) ; setPreferenceStore ( Activator . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( MESSAGES . get ( "<STR_LIT:description>" ) ) ; } protected Control createContents ( final Composite parent ) { initializeDialogUnits ( parent ) ; final Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setLayout ( new FormLayout ( ) ) ; Control c ; invocationControlEnabledCheckbox = createInvocationControlEnabledCheckbox ( composite , null ) ; ( ( FormData ) invocationControlEnabledCheckbox . getLayoutData ( ) ) . top = new FormAttachment ( <NUM_LIT:0> ) ; c = invocationControlEnabledCheckbox ; configureKeyboardShortcutCheckbox = createConfigureKeyboardShortcutCheckbox ( composite , c ) ; c = configureKeyboardShortcutCheckbox ; configureKeyboardShortcutThreshold = createConfigureKeyboardShortcutThreshold ( composite , c ) ; c = configureKeyboardShortcutThreshold ; c = onWrongInvocationModeUI . createLabel ( composite , c , MESSAGES . get ( "<STR_LIT>" ) ) ; onWrongInvocationModeCombo = onWrongInvocationModeUI . createCombo ( composite , c ) ; c = onWrongInvocationModeCombo ; updateOnWrongInvocationModeCombo ( preferences . getOnWrongInvocationMode ( ) ) ; updateInvocationControlEnabled ( preferences . isInvocationControlEnabled ( ) ) ; updateConfigureKeyboardShortcutEnabled ( preferences . isConfigureKeyboardShortcutEnabled ( ) ) ; updateConfigureKeyboardShortcutThreshold ( preferences . getConfigureKeyboardShortcutThreshold ( ) ) ; actionModeControl = createActionModeControl ( composite ) ; c = actionModeControl ; final Control separator = createHorizontalSeparator ( composite , c ) ; layoutActionModeControl ( onWrongInvocationModeCombo , separator ) ; onInvocationControlEnabledCheckboxSelected ( ) ; Dialog . applyDialogFont ( composite ) ; return composite ; } @ Override protected void performDefaults ( ) { super . performDefaults ( ) ; updateOnWrongInvocationModeCombo ( OnWrongInvocationMode . DEFAULT ) ; updateInvocationControlEnabled ( INVOCATION_CONTROL_ENABLED_DEFAULT ) ; updateConfigureKeyboardShortcutEnabled ( CONFIGURE_KEYBOARD_SHORTCUT_ENABLED_DEFAULT ) ; updateConfigureKeyboardShortcutThreshold ( CONFIGURE_KEYBOARD_SHORTCUT_THRESHOLD_DEFAULT ) ; actionModeControl . clearActionSettings ( ) ; } @ Override public boolean performOk ( ) { preferences . storeOnWrongInvocationMode ( getSelectedOnWrongInvocationMode ( ) ) ; preferences . storeInvocationControlEnabled ( isInvocationControlEnabled ( ) ) ; preferences . storeConfigureKeyboardShortcutEnabled ( isConfigureKeyboardShortcutEnabled ( ) ) ; preferences . storeConfigureKeyboardShortcutThreshold ( getConfigureKeyboardShortcutThreshold ( ) ) ; preferences . setActionsOnWrongInvocationMode ( actionModeControl . getActionModes ( ) ) ; return super . performOk ( ) ; } public void init ( final IWorkbench workbench ) { } private Button createInvocationControlEnabledCheckbox ( final Composite container , final Control above ) { notNull ( container ) ; final Button checkbox = new Button ( container , SWT . CHECK | SWT . LEAD ) ; checkbox . setText ( MESSAGES . get ( "<STR_LIT>" ) ) ; checkbox . setToolTipText ( MESSAGES . get ( "<STR_LIT>" ) ) ; placeUnder ( checkbox , above , STACKED_V_OFFSET ) ; checkbox . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { onInvocationControlEnabledCheckboxSelected ( ) ; } } ) ; return checkbox ; } private void onInvocationControlEnabledCheckboxSelected ( ) { final Button checkbox = invocationControlEnabledCheckbox ; for ( Control c : checkbox . getParent ( ) . getChildren ( ) ) { if ( ! c . equals ( invocationControlEnabledCheckbox ) ) { c . setEnabled ( isInvocationControlEnabled ( ) ) ; } } } private Button createConfigureKeyboardShortcutCheckbox ( final Composite container , final Control above ) { notNull ( container ) ; final Button checkbox = new Button ( container , SWT . CHECK | SWT . LEAD ) ; checkbox . setText ( MESSAGES . get ( "<STR_LIT>" ) ) ; checkbox . setToolTipText ( MESSAGES . get ( "<STR_LIT>" ) ) ; placeUnder ( checkbox , above , STACKED_V_OFFSET ) ; checkbox . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { onConfigureKeyboardShortcutCheckboxSelected ( ) ; } } ) ; return checkbox ; } private void onConfigureKeyboardShortcutCheckboxSelected ( ) { final Control c = configureKeyboardShortcutThreshold ; c . setEnabled ( isInvocationControlEnabled ( ) ) ; } private Spinner createConfigureKeyboardShortcutThreshold ( final Composite container , final Control above ) { notNull ( container ) ; final Label label = new Label ( container , SWT . NONE ) ; label . setText ( MESSAGES . get ( "<STR_LIT>" ) ) ; placeUnder ( label , above , STACKED_V_OFFSET ) ; final Spinner spinner = new Spinner ( container , SWT . NONE ) ; spinner . setToolTipText ( MESSAGES . get ( "<STR_LIT>" ) ) ; placeUnder ( spinner , label , STACKED_V_OFFSET ) ; return spinner ; } private ActionInvocationModeControl createActionModeControl ( final Composite composite ) { return new ActionInvocationModeControl ( composite ) ; } private void layoutActionModeControl ( final Control aboveControl , final Control belowControl ) { final FormData formData = placeUnder ( actionModeControl , aboveControl , STACKED_V_OFFSET ) ; formData . right = new FormAttachment ( WHOLE_SIZE , - WINDOW_MARGIN ) ; formData . bottom = new FormAttachment ( belowControl , - STACKED_V_OFFSET , SWT . TOP ) ; } private Control createHorizontalSeparator ( final Composite composite , final Control aboveControl ) { final Label separator = new Label ( composite , SWT . SEPARATOR | SWT . HORIZONTAL | SWT . LINE_SOLID | SWT . SHADOW_OUT ) ; final FormData formData = new FormData ( ) ; formData . left = new FormAttachment ( <NUM_LIT:0> , WINDOW_MARGIN ) ; formData . right = new FormAttachment ( WHOLE_SIZE , - WINDOW_MARGIN ) ; formData . bottom = new FormAttachment ( WHOLE_SIZE , <NUM_LIT:0> ) ; separator . setLayoutData ( formData ) ; return separator ; } private OnWrongInvocationMode getSelectedOnWrongInvocationMode ( ) { final int i = onWrongInvocationModeCombo . getSelectionIndex ( ) ; return OnWrongInvocationMode . values ( ) [ i ] ; } private void updateOnWrongInvocationModeCombo ( final OnWrongInvocationMode mode ) { notNull ( mode ) ; onWrongInvocationModeCombo . setText ( mode . getLabel ( ) ) ; } private boolean isInvocationControlEnabled ( ) { return invocationControlEnabledCheckbox . getSelection ( ) ; } private void updateInvocationControlEnabled ( final boolean enabled ) { invocationControlEnabledCheckbox . setSelection ( enabled ) ; } private boolean isConfigureKeyboardShortcutEnabled ( ) { return configureKeyboardShortcutCheckbox . getSelection ( ) ; } private void updateConfigureKeyboardShortcutEnabled ( final boolean enabled ) { configureKeyboardShortcutCheckbox . setSelection ( enabled ) ; } private int getConfigureKeyboardShortcutThreshold ( ) { return configureKeyboardShortcutThreshold . getSelection ( ) ; } private void updateConfigureKeyboardShortcutThreshold ( final int threshold ) { configureKeyboardShortcutThreshold . setSelection ( threshold ) ; } } </s>
|
<s> package com . mousefeed . eclipse . preferences ; public final class PreferenceConstants { public static final String P_INVOCATION_CONTROL_ENABLED = "<STR_LIT>" ; public static final boolean INVOCATION_CONTROL_ENABLED_DEFAULT = true ; public static final String P_CONFIGURE_KEYBOARD_SHORTCUT_ENABLED = "<STR_LIT>" ; public static final boolean CONFIGURE_KEYBOARD_SHORTCUT_ENABLED_DEFAULT = true ; public static final String P_CONFIGURE_KEYBOARD_SHORTCUT_THRESHOLD = "<STR_LIT>" ; public static final int CONFIGURE_KEYBOARD_SHORTCUT_THRESHOLD_DEFAULT = <NUM_LIT:2> ; public static final String P_DEFAULT_ON_WRONG_INVOCATION_MODE = "<STR_LIT>" ; private PreferenceConstants ( ) { } } </s>
|
<s> package com . mousefeed . eclipse . preferences ; import static com . mousefeed . eclipse . Layout . H_OFFSET ; import static com . mousefeed . eclipse . Layout . STACKED_V_OFFSET ; import static com . mousefeed . eclipse . Layout . WHOLE_SIZE ; import com . mousefeed . client . Messages ; import com . mousefeed . client . OnWrongInvocationMode ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . eclipse . jface . viewers . CellEditor ; import org . eclipse . jface . viewers . ComboBoxCellEditor ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . TableEditor ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . FormAttachment ; import org . eclipse . swt . layout . FormData ; import org . eclipse . swt . layout . FormLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; class ActionInvocationModeControl extends Composite { static enum Column { LABEL , MODE } private static final Messages MESSAGES = new Messages ( ActionInvocationModeControl . class ) ; private final PreferenceAccessor preferences = PreferenceAccessor . getInstance ( ) ; private final List < ActionOnWrongInvocationMode > actionModes = createActionModes ( ) ; private final Table table ; private final TableViewer tableViewer ; private final Button removeButton ; public ActionInvocationModeControl ( final Composite parent ) { super ( parent , SWT . NONE ) ; this . setLayout ( new FormLayout ( ) ) ; table = createTable ( null ) ; tableViewer = createTableViewer ( ) ; resizeTableColumns ( ) ; table . addKeyListener ( new KeyAdapter ( ) { @ Override public void keyPressed ( final KeyEvent e ) { if ( e . character == SWT . DEL && e . stateMask == <NUM_LIT:0> ) { removeSelected ( ) ; e . doit = false ; } } } ) ; tableViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( final SelectionChangedEvent event ) { onTableSelectionChanged ( ) ; } } ) ; removeButton = createRemoveButton ( ) ; layoutTable ( removeButton ) ; createAddReminder ( removeButton ) ; onTableSelectionChanged ( ) ; } private void onTableSelectionChanged ( ) { removeButton . setEnabled ( ! tableViewer . getSelection ( ) . isEmpty ( ) ) ; } private void removeSelected ( ) { final IStructuredSelection selection = ( IStructuredSelection ) tableViewer . getSelection ( ) ; final List < ? > selectedModes = selection . toList ( ) ; if ( selectedModes . isEmpty ( ) ) { getDisplay ( ) . beep ( ) ; } else { actionModes . removeAll ( selectedModes ) ; tableViewer . refresh ( false ) ; } } private void resizeTableColumns ( ) { for ( TableColumn column : table . getColumns ( ) ) { column . pack ( ) ; } } private Table createTable ( final Control aboveControl ) { final Table t = new Table ( this , SWT . V_SCROLL | SWT . BORDER | SWT . MULTI | SWT . FULL_SELECTION ) ; t . setLinesVisible ( true ) ; t . setHeaderVisible ( true ) ; { final TableColumn column = new TableColumn ( t , SWT . NONE , <NUM_LIT:0> ) ; column . setText ( MESSAGES . get ( "<STR_LIT>" ) ) ; } { final TableColumn column = new TableColumn ( t , SWT . NONE , <NUM_LIT:1> ) ; column . setText ( MESSAGES . get ( "<STR_LIT>" ) ) ; } return t ; } private TableViewer createTableViewer ( ) { final TableViewer viewer = new TableViewer ( table ) ; viewer . setContentProvider ( new ActionInvocationModeTableContentProvider ( ) ) ; viewer . setLabelProvider ( new ActionInvocationModeTableLabelProvider ( ) ) ; new TableEditor ( table ) ; viewer . setCellEditors ( new CellEditor [ ] { null , createOnWrongInvocationModeCellEditor ( ) } ) ; viewer . setColumnProperties ( new String [ ] { Column . LABEL . name ( ) , Column . MODE . name ( ) } ) ; viewer . setCellModifier ( new ActionInvocationModeTableCellModifier ( viewer ) ) ; viewer . setInput ( actionModes ) ; return viewer ; } private List < ActionOnWrongInvocationMode > createActionModes ( ) { final List < ActionOnWrongInvocationMode > modes = new ArrayList < ActionOnWrongInvocationMode > ( preferences . getActionsOnWrongInvocationMode ( ) ) ; Collections . sort ( modes , new ActionOnWrongInvocationMode . LabelComparator ( ) ) ; return modes ; } private ComboBoxCellEditor createOnWrongInvocationModeCellEditor ( ) { return new ComboBoxCellEditor ( table , OnWrongInvocationMode . getLabels ( ) , SWT . READ_ONLY ) ; } private Button createRemoveButton ( ) { final Button b = new Button ( this , SWT . PUSH ) ; final FormData formData = new FormData ( ) ; formData . right = new FormAttachment ( WHOLE_SIZE ) ; formData . bottom = new FormAttachment ( WHOLE_SIZE ) ; b . setLayoutData ( formData ) ; b . setText ( MESSAGES . get ( "<STR_LIT>" ) ) ; b . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { removeSelected ( ) ; } } ) ; return b ; } private Label createAddReminder ( final Control rightControl ) { final Label label = new Label ( this , SWT . WRAP | SWT . LEFT ) ; label . setText ( MESSAGES . get ( "<STR_LIT>" ) ) ; final FormData formData = new FormData ( ) ; formData . left = new FormAttachment ( <NUM_LIT:0> ) ; formData . right = new FormAttachment ( rightControl , - H_OFFSET , SWT . LEFT ) ; formData . top = new FormAttachment ( rightControl , <NUM_LIT:0> , SWT . TOP ) ; label . setLayoutData ( formData ) ; return label ; } private void layoutTable ( final Control belowControl ) { final FormData formData = new FormData ( ) ; formData . left = new FormAttachment ( <NUM_LIT:0> , <NUM_LIT:0> ) ; formData . top = new FormAttachment ( <NUM_LIT:0> , <NUM_LIT:0> ) ; formData . right = new FormAttachment ( WHOLE_SIZE , <NUM_LIT:0> ) ; formData . bottom = new FormAttachment ( belowControl , - STACKED_V_OFFSET , SWT . TOP ) ; table . setLayoutData ( formData ) ; } public List < ActionOnWrongInvocationMode > getActionModes ( ) { return actionModes ; } public void clearActionSettings ( ) { getActionModes ( ) . clear ( ) ; tableViewer . refresh ( ) ; } } </s>
|
<s> package com . mousefeed . eclipse . preferences ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . OnWrongInvocationMode ; import com . mousefeed . eclipse . preferences . ActionInvocationModeControl . Column ; import org . eclipse . jface . viewers . ICellModifier ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . swt . widgets . Item ; public class ActionInvocationModeTableCellModifier implements ICellModifier { private final TableViewer tableViewer ; public ActionInvocationModeTableCellModifier ( final TableViewer tableViewer ) { validateTableViewer ( tableViewer ) ; this . tableViewer = tableViewer ; } void validateTableViewer ( final TableViewer viewer ) { notNull ( viewer ) ; } public boolean canModify ( final Object element , final String property ) { return property . equals ( Column . MODE . name ( ) ) ; } public Object getValue ( final Object element , final String property ) { final ActionOnWrongInvocationMode mode = ( ActionOnWrongInvocationMode ) element ; if ( property . equals ( Column . LABEL . name ( ) ) ) { return mode . getLabel ( ) ; } else if ( property . equals ( Column . MODE . name ( ) ) ) { return mode . getOnWrongInvocationMode ( ) . ordinal ( ) ; } else { return null ; } } public void modify ( final Object element , final String property , final Object value ) { final Object actionModeObject = element instanceof Item ? ( ( Item ) element ) . getData ( ) : element ; final ActionOnWrongInvocationMode actionMode = ( ActionOnWrongInvocationMode ) actionModeObject ; if ( property . equals ( Column . MODE . name ( ) ) ) { final OnWrongInvocationMode mode = OnWrongInvocationMode . values ( ) [ ( Integer ) value ] ; actionMode . setOnWrongInvocationMode ( mode ) ; updateTableViewer ( actionModeObject , property ) ; } else { return ; } } void updateTableViewer ( final Object element , final String property ) { tableViewer . update ( element , new String [ ] { property } ) ; } } </s>
|
<s> package com . mousefeed . eclipse . preferences ; import com . mousefeed . eclipse . preferences . ActionInvocationModeControl . Column ; import org . eclipse . jface . viewers . BaseLabelProvider ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . swt . graphics . Image ; class ActionInvocationModeTableLabelProvider extends BaseLabelProvider implements ITableLabelProvider { public ActionInvocationModeTableLabelProvider ( ) { } public boolean isLabelProperty ( final Object element , final String property ) { if ( property . equals ( Column . LABEL . name ( ) ) ) { return false ; } else if ( property . equals ( Column . MODE . name ( ) ) ) { return true ; } else { throw new IllegalArgumentException ( "<STR_LIT>" + property ) ; } } public Image getColumnImage ( final Object element , final int columnIndex ) { return null ; } public String getColumnText ( final Object element , final int columnIndex ) { final ActionOnWrongInvocationMode mode = ( ActionOnWrongInvocationMode ) element ; if ( columnIndex == Column . LABEL . ordinal ( ) ) { return mode . getLabel ( ) ; } else if ( columnIndex == Column . MODE . ordinal ( ) ) { return mode . getOnWrongInvocationMode ( ) . getLabel ( ) ; } else { throw new IllegalArgumentException ( "<STR_LIT>" + columnIndex ) ; } } } </s>
|
<s> package com . mousefeed . eclipse . preferences ; import org . eclipse . core . runtime . preferences . AbstractPreferenceInitializer ; import org . eclipse . jface . preference . IPreferenceStore ; import com . mousefeed . client . OnWrongInvocationMode ; import com . mousefeed . eclipse . Activator ; public class PreferenceInitializer extends AbstractPreferenceInitializer { public PreferenceInitializer ( ) { } @ Override public void initializeDefaultPreferences ( ) { final IPreferenceStore store = Activator . getDefault ( ) . getPreferenceStore ( ) ; store . setDefault ( PreferenceConstants . P_DEFAULT_ON_WRONG_INVOCATION_MODE , OnWrongInvocationMode . DEFAULT . name ( ) ) ; store . setDefault ( PreferenceConstants . P_INVOCATION_CONTROL_ENABLED , PreferenceConstants . INVOCATION_CONTROL_ENABLED_DEFAULT ) ; store . setDefault ( PreferenceConstants . P_CONFIGURE_KEYBOARD_SHORTCUT_ENABLED , PreferenceConstants . CONFIGURE_KEYBOARD_SHORTCUT_ENABLED_DEFAULT ) ; store . setDefault ( PreferenceConstants . P_CONFIGURE_KEYBOARD_SHORTCUT_THRESHOLD , PreferenceConstants . CONFIGURE_KEYBOARD_SHORTCUT_THRESHOLD_DEFAULT ) ; } } </s>
|
<s> package com . mousefeed . eclipse . preferences ; import com . mousefeed . client . Messages ; import com . mousefeed . eclipse . Activator ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; public class PreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { private static final Messages MESSAGES = new Messages ( PreferencePage . class ) ; public PreferencePage ( ) { super ( GRID ) ; setPreferenceStore ( Activator . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( MESSAGES . get ( "<STR_LIT:description>" ) ) ; } @ Override public void createFieldEditors ( ) { } public void init ( final IWorkbench workbench ) { } } </s>
|
<s> package com . mousefeed . eclipse . preferences ; import java . util . Collection ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . Viewer ; public class ActionInvocationModeTableContentProvider implements IStructuredContentProvider { public ActionInvocationModeTableContentProvider ( ) { } public Object [ ] getElements ( final Object inputElement ) { return ( ( Collection < ? > ) inputElement ) . toArray ( ) ; } public void dispose ( ) { } public void inputChanged ( final Viewer viewer , final Object oldInput , final Object newInput ) { } } </s>
|
<s> package com . mousefeed . eclipse ; import static com . mousefeed . eclipse . Layout . WHOLE_SIZE ; import static com . mousefeed . eclipse . Layout . WINDOW_MARGIN ; import static org . apache . commons . lang . Validate . isTrue ; import static org . apache . commons . lang . Validate . notNull ; import static org . apache . commons . lang . time . DateUtils . MILLIS_PER_SECOND ; import com . mousefeed . client . Messages ; import java . util . HashSet ; import org . apache . commons . lang . StringUtils ; import org . eclipse . core . commands . Command ; import org . eclipse . core . commands . ParameterizedCommand ; import org . eclipse . core . commands . common . NotDefinedException ; import org . eclipse . jface . dialogs . PopupDialog ; import org . eclipse . jface . preference . PreferenceDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StyleRange ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . events . FocusAdapter ; import org . eclipse . swt . events . FocusEvent ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . layout . FormAttachment ; import org . eclipse . swt . layout . FormData ; import org . eclipse . swt . layout . FormLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Link ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . commands . ICommandService ; import org . eclipse . ui . dialogs . PreferencesUtil ; public class NagPopUp extends PopupDialog { protected static class PreferenceDialogLauncher implements Runnable { private final Object data ; protected PreferenceDialogLauncher ( final Object data ) { this . data = data ; } public void run ( ) { final Display workbenchDisplay = PlatformUI . getWorkbench ( ) . getDisplay ( ) ; final Shell activeShell = workbenchDisplay . getActiveShell ( ) ; final String id = ORG_ECLIPSE_UI_PREFERENCE_PAGES_KEYS_ID ; final String [ ] displayedIds = new String [ ] { id } ; final PreferenceDialog preferenceDialog = PreferencesUtil . createPreferenceDialogOn ( activeShell , id , displayedIds , data ) ; preferenceDialog . open ( ) ; } } private static final String ORG_ECLIPSE_UI_PREFERENCE_PAGES_KEYS_ID = "<STR_LIT>" ; private static final int DISTANCE_TO_CURSOR = <NUM_LIT> ; private static final int FONT_INCREASE_MULT = <NUM_LIT:2> ; private static final int CLOSE_TIMEOUT = <NUM_LIT:4> * ( int ) MILLIS_PER_SECOND ; private static final int CLOSE_LISTENER_TIMEOUT = <NUM_LIT> ; private static final Messages MESSAGES = new Messages ( NagPopUp . class ) ; private static final LastActionInvocationRemiderFactory REMINDER_FACTORY = new LastActionInvocationRemiderFactory ( ) ; private final String actionName ; private final String actionId ; private final String accelerator ; private final boolean actionCancelled ; private boolean open ; private StyledText actionDescriptionText ; @ SuppressWarnings ( "<STR_LIT:unused>" ) private Link actionLink ; private Listener closeOnActionListener = new Listener ( ) { public void handleEvent ( final Event event ) { NagPopUp . this . close ( ) ; } } ; public NagPopUp ( final String actionName , final String accelerator , final boolean actionCancelled ) { super ( ( Shell ) null , PopupDialog . HOVER_SHELLSTYLE , false , false , false , false , false , getTitleText ( actionCancelled ) , getActionConfigurationReminder ( ) ) ; isTrue ( StringUtils . isNotBlank ( actionName ) ) ; isTrue ( StringUtils . isNotBlank ( accelerator ) ) ; this . actionName = actionName ; this . accelerator = accelerator ; this . actionCancelled = actionCancelled ; this . actionId = null ; } public NagPopUp ( final String actionName , final String actionId ) { super ( ( Shell ) null , PopupDialog . HOVER_SHELLSTYLE , false , false , false , false , false , getTitleText ( false ) , getActionConfigurationReminder ( ) ) ; isTrue ( StringUtils . isNotBlank ( actionName ) ) ; isTrue ( StringUtils . isNotBlank ( actionId ) ) ; this . actionName = actionName ; this . actionId = actionId ; this . actionCancelled = false ; this . accelerator = null ; } @ Override protected Control createDialogArea ( final Composite parent ) { final Composite composite = new Composite ( parent , SWT . NO_FOCUS ) ; composite . setLayout ( new FormLayout ( ) ) ; if ( isLinkPopup ( ) ) { final String linkText = MESSAGES . get ( "<STR_LIT>" , actionName ) ; actionLink = createLink ( composite , linkText ) ; } else { actionDescriptionText = createActionDescriptionText ( composite ) ; } composite . pack ( true ) ; return composite ; } protected boolean isLinkPopup ( ) { return actionId != null && accelerator == null ; } private StyledText createActionDescriptionText ( final Composite parent ) { notNull ( parent ) ; final StyledText text = new StyledText ( parent , SWT . READ_ONLY ) ; configureFormData ( text ) ; text . setText ( accelerator + "<STR_LIT:U+0020(>" + actionName + "<STR_LIT:)>" ) ; if ( actionCancelled ) { final StyleRange style = new StyleRange ( ) ; style . start = <NUM_LIT:0> ; style . length = text . getText ( ) . length ( ) ; style . strikeout = true ; text . setStyleRange ( style ) ; } configureBigFont ( text ) ; text . addFocusListener ( new FocusAdapter ( ) { @ Override public void focusGained ( final FocusEvent event ) { NagPopUp . this . close ( ) ; } } ) ; return text ; } protected Link createLink ( final Composite parent , final String text ) { final Link link = new Link ( parent , SWT . NONE ) ; link . setFont ( parent . getFont ( ) ) ; link . setText ( "<STR_LIT>" + text + "<STR_LIT>" ) ; configureFormData ( link ) ; configureBigFont ( link ) ; link . addFocusListener ( new FocusAdapter ( ) { @ Override public void focusGained ( final FocusEvent e ) { doLinkActivated ( ) ; } } ) ; return link ; } @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) final void doLinkActivated ( ) { Object data = null ; final IWorkbench workbench = Activator . getDefault ( ) . getWorkbench ( ) ; final ICommandService commandService = ( ICommandService ) workbench . getService ( ICommandService . class ) ; final Command command = commandService . getCommand ( actionId ) ; if ( command != null ) { final HashSet allParameterizedCommands = new HashSet ( ) ; try { allParameterizedCommands . addAll ( ParameterizedCommand . generateCombinations ( command ) ) ; } catch ( final NotDefinedException e ) { } if ( ! allParameterizedCommands . isEmpty ( ) ) { data = allParameterizedCommands . iterator ( ) . next ( ) ; openWorkspacePreferences ( data ) ; } } } protected final void openWorkspacePreferences ( final Object data ) { final Display display = Display . getCurrent ( ) ; final PreferenceDialogLauncher runnable = new PreferenceDialogLauncher ( data ) ; display . asyncExec ( runnable ) ; } @ Override protected Control createContents ( final Composite parent ) { final Control control = super . createContents ( parent ) ; if ( actionCancelled ) { actionDescriptionText . setForeground ( getDisplay ( ) . getSystemColor ( SWT . COLOR_RED ) ) ; } return control ; } private void configureFormData ( final Control c ) { final FormData formData = new FormData ( ) ; formData . left = new FormAttachment ( WINDOW_MARGIN ) ; formData . right = new FormAttachment ( WHOLE_SIZE , - WINDOW_MARGIN ) ; formData . top = new FormAttachment ( WINDOW_MARGIN ) ; formData . bottom = new FormAttachment ( WHOLE_SIZE , - WINDOW_MARGIN ) ; c . setLayoutData ( formData ) ; } private void configureBigFont ( final Control c ) { final FontData [ ] fontData = c . getFont ( ) . getFontData ( ) ; for ( int i = <NUM_LIT:0> ; i < fontData . length ; i ++ ) { fontData [ i ] . setHeight ( fontData [ i ] . getHeight ( ) * FONT_INCREASE_MULT ) ; } final Font newFont = new Font ( getDisplay ( ) , fontData ) ; c . setFont ( newFont ) ; c . addDisposeListener ( new DestroyFontDisposeListener ( newFont ) ) ; } @ Override public int open ( ) { open = true ; setParentShell ( getDisplay ( ) . getActiveShell ( ) ) ; if ( actionCancelled ) { getDisplay ( ) . beep ( ) ; } getDisplay ( ) . timerExec ( CLOSE_TIMEOUT , new Runnable ( ) { public void run ( ) { NagPopUp . this . close ( ) ; } } ) ; addCloseOnActionListeners ( ) ; return super . open ( ) ; } @ Override public boolean close ( ) { open = false ; removeCloseOnActionListeners ( ) ; return super . close ( ) ; } private void addCloseOnActionListeners ( ) { getDisplay ( ) . timerExec ( CLOSE_LISTENER_TIMEOUT , new Runnable ( ) { public void run ( ) { if ( ! open ) { return ; } final Listener l = closeOnActionListener ; getDisplay ( ) . addFilter ( SWT . MouseDown , l ) ; getDisplay ( ) . addFilter ( SWT . Selection , l ) ; getDisplay ( ) . addFilter ( SWT . KeyDown , l ) ; } } ) ; } private void removeCloseOnActionListeners ( ) { final Display d = PlatformUI . getWorkbench ( ) . getDisplay ( ) ; d . removeFilter ( SWT . MouseDown , closeOnActionListener ) ; d . removeFilter ( SWT . Selection , closeOnActionListener ) ; d . removeFilter ( SWT . KeyDown , closeOnActionListener ) ; } private Display getDisplay ( ) { return PlatformUI . getWorkbench ( ) . getDisplay ( ) ; } @ Override protected Point getInitialLocation ( final Point initialSize ) { final Point p = getDisplay ( ) . getCursorLocation ( ) ; p . x += DISTANCE_TO_CURSOR ; p . y = Math . max ( p . y - initialSize . y / <NUM_LIT:2> , <NUM_LIT:0> ) ; return p ; } private static String getTitleText ( final boolean canceled ) { return canceled ? MESSAGES . get ( "<STR_LIT>" ) : MESSAGES . get ( "<STR_LIT>" ) ; } private static String getActionConfigurationReminder ( ) { return REMINDER_FACTORY . getText ( ) ; } } </s>
|
<s> package com . mousefeed . eclipse ; import static org . apache . commons . lang . StringUtils . isBlank ; import static org . apache . commons . lang . StringUtils . isNotBlank ; import static org . apache . commons . lang . Validate . isTrue ; import com . mousefeed . client . collector . AbstractActionDesc ; public class ActionDescImpl extends AbstractActionDesc { private String className ; private String def ; public ActionDescImpl ( ) { } @ Override public String getId ( ) { if ( isNotBlank ( getDef ( ) ) ) { return getDef ( ) ; } if ( isNotBlank ( getClassName ( ) ) ) { return getClassName ( ) ; } return super . getId ( ) ; } public String getClassName ( ) { return className ; } public void setClassName ( final String className ) { if ( isBlank ( className ) ) { return ; } isNullOrNotEqual ( this . className , className ) ; this . className = className ; } public String getDef ( ) { return def ; } public void setDef ( final String def ) { if ( isBlank ( def ) ) { return ; } isNullOrNotEqual ( this . def , def ) ; this . def = def ; } private void isNullOrNotEqual ( final String val1 , final String val2 ) { isTrue ( val1 == null || val2 . equals ( val1 ) , "<STR_LIT>" + val2 + "<STR_LIT:U+0020andU+0020>" + val1 ) ; } } </s>
|
<s> package com . mousefeed . eclipse ; import static org . apache . commons . lang . Validate . notNull ; import java . lang . reflect . Field ; import org . eclipse . core . commands . Command ; import org . eclipse . core . commands . ParameterizedCommand ; import org . eclipse . e4 . ui . model . application . ui . menu . MHandledItem ; import org . eclipse . e4 . ui . workbench . renderers . swt . HandledContributionItem ; @ SuppressWarnings ( "<STR_LIT>" ) public class HandledContributionItemCommandLocator { private static final String MODEL_FIELD = "<STR_LIT>" ; public HandledContributionItemCommandLocator ( ) { } public Command get ( final HandledContributionItem item ) { final ParameterizedCommand parCommand = getItemParCommand ( item ) ; return parCommand == null ? null : parCommand . getCommand ( ) ; } private ParameterizedCommand getItemParCommand ( final HandledContributionItem item ) { final Field modelField = getModelField ( ) ; try { modelField . setAccessible ( true ) ; final MHandledItem mItem = ( MHandledItem ) modelField . get ( item ) ; return mItem . getWbCommand ( ) ; } catch ( final SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( final IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( final IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } private Field getModelField ( ) { try { final Field modelField = HandledContributionItem . class . getDeclaredField ( MODEL_FIELD ) ; notNull ( modelField ) ; return modelField ; } catch ( final SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( final NoSuchFieldException e ) { throw new RuntimeException ( e ) ; } } } </s>
|
<s> package com . mousefeed . eclipse ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . collector . AbstractActionDesc ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . Map ; import org . apache . commons . lang . StringUtils ; import org . eclipse . core . commands . Command ; import org . eclipse . core . commands . IHandler ; import org . eclipse . jface . action . ExternalActionManager ; import org . eclipse . jface . action . ExternalActionManager . ICallback ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . bindings . Binding ; import org . eclipse . jface . bindings . TriggerSequence ; import org . eclipse . jface . bindings . keys . KeySequence ; import org . eclipse . jface . bindings . keys . SWTKeySupport ; import org . eclipse . jface . commands . ActionHandler ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . RetargetAction ; import org . eclipse . ui . activities . IActivityManager ; import org . eclipse . ui . internal . keys . BindingService ; import org . eclipse . ui . keys . IBindingService ; @ SuppressWarnings ( "<STR_LIT>" ) public class ActionActionDescGenerator { private ActionDescImpl actionDesc ; private final TextActionHandlerActionLocator actionSearcher = new TextActionHandlerActionLocator ( ) ; private final IBindingService bindingService ; private final IActivityManager activityManager ; public ActionActionDescGenerator ( ) { bindingService = ( IBindingService ) getWorkbench ( ) . getAdapter ( IBindingService . class ) ; activityManager = getWorkbench ( ) . getActivitySupport ( ) . getActivityManager ( ) ; } public AbstractActionDesc generate ( final IAction action ) { notNull ( action ) ; actionDesc = new ActionDescImpl ( ) ; final String text = action . getText ( ) ; final String toolTipText = action . getToolTipText ( ) ; if ( text != null ) { actionDesc . setLabel ( text ) ; } else if ( toolTipText != null ) { actionDesc . setLabel ( toolTipText ) ; } else { actionDesc . setLabel ( action . getClass ( ) . getSimpleName ( ) ) ; } actionDesc . setClassName ( action . getClass ( ) . getName ( ) ) ; extractActionData ( action ) ; return actionDesc ; } public void extractActionData ( final IAction action ) { notNull ( action ) ; fromActionAccelerator ( action . getAccelerator ( ) ) ; fromActionDefinition ( action . getActionDefinitionId ( ) ) ; if ( action instanceof RetargetAction ) { final RetargetAction a = ( RetargetAction ) action ; if ( a . getActionHandler ( ) != null ) { extractActionData ( a . getActionHandler ( ) ) ; } } fromActionBinding ( action ) ; } private void fromActionDefinition ( final String definitionId ) { if ( definitionId == null ) { return ; } actionDesc . setDef ( definitionId ) ; final String s = findAcceleratorForActionDefinition ( definitionId ) ; if ( s != null ) { actionDesc . setAccelerator ( s ) ; } } private void fromActionAccelerator ( final int accelerator ) { if ( accelerator != <NUM_LIT:0> ) { actionDesc . setAccelerator ( keyToStr ( accelerator ) ) ; } } private String findAcceleratorForActionDefinition ( final String definitionId ) { if ( StringUtils . isBlank ( definitionId ) ) { return null ; } final ICallback callback = ExternalActionManager . getInstance ( ) . getCallback ( ) ; return callback . getAcceleratorText ( definitionId ) ; } private String fromActionBinding ( final IAction action ) { if ( action == null ) { return null ; } if ( action instanceof RetargetAction ) { return fromActionBinding ( ( ( RetargetAction ) action ) . getActionHandler ( ) ) ; } return scanBindings ( action ) ; } @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) private String scanBindings ( final IAction action ) { final KeySequence keySequence = KeySequence . getInstance ( ) ; if ( bindingService instanceof BindingService ) { final BindingService theBindingService = ( BindingService ) bindingService ; final Map matches = theBindingService . getBindingManager ( ) . getPartialMatches ( keySequence ) ; final Class < ? extends IAction > actionClass = action . getClass ( ) ; for ( Object o : matches . keySet ( ) ) { final TriggerSequence triggerSequence = ( TriggerSequence ) o ; final Binding binding = ( Binding ) matches . get ( triggerSequence ) ; final Command command = binding . getParameterizedCommand ( ) . getCommand ( ) ; final IHandler handler = getCommandHandler ( command ) ; if ( ! ( handler instanceof ActionHandler ) ) { continue ; } if ( isCommandEnabled ( command ) ) { final String accelerator = getFromBindingData ( action , actionClass , triggerSequence , handler ) ; if ( accelerator != null ) { return accelerator ; } } } } return null ; } private String getFromBindingData ( final IAction action , final Class < ? extends IAction > actionClass , final TriggerSequence triggerSequence , final IHandler handler ) { final ActionHandler actionHandler = ( ActionHandler ) handler ; final IAction boundAction = actionHandler . getAction ( ) ; if ( boundAction == null ) { return null ; } if ( boundAction . getClass ( ) . equals ( actionClass ) ) { return triggerSequence . toString ( ) ; } if ( ! ( boundAction instanceof RetargetAction ) ) { return null ; } final IAction searchTarget = ( ( RetargetAction ) boundAction ) . getActionHandler ( ) ; if ( searchTarget == null ) { return null ; } if ( searchTarget . getClass ( ) . equals ( actionClass ) ) { return triggerSequence . toString ( ) ; } if ( actionSearcher . isSearchable ( searchTarget ) ) { final String id = actionSearcher . findActionDefinitionId ( action , searchTarget ) ; return findAcceleratorForActionDefinition ( id ) ; } return null ; } private String keyToStr ( final int accelerator ) { return SWTKeySupport . convertAcceleratorToKeyStroke ( accelerator ) . format ( ) ; } private IWorkbench getWorkbench ( ) { return PlatformUI . getWorkbench ( ) ; } private IHandler getCommandHandler ( final Command command ) { try { final Method method = Command . class . getDeclaredMethod ( "<STR_LIT>" ) ; method . setAccessible ( true ) ; return ( IHandler ) method . invoke ( command ) ; } catch ( final SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( final NoSuchMethodException e ) { throw new AssertionError ( e ) ; } catch ( final IllegalAccessException e ) { throw new AssertionError ( e ) ; } catch ( final InvocationTargetException e ) { throw new AssertionError ( e ) ; } } private boolean isCommandEnabled ( final Command command ) { return command . isDefined ( ) && activityManager . getIdentifier ( command . getId ( ) ) . isEnabled ( ) ; } } </s>
|
<s> package com . mousefeed . eclipse ; import static org . apache . commons . lang . Validate . isTrue ; import static org . apache . commons . lang . Validate . notNull ; import com . mousefeed . client . OnWrongInvocationMode ; import com . mousefeed . client . collector . AbstractActionDesc ; import com . mousefeed . client . collector . Collector ; import com . mousefeed . eclipse . preferences . PreferenceAccessor ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import org . apache . commons . lang . StringUtils ; import org . eclipse . core . commands . Command ; import org . eclipse . core . commands . ParameterizedCommand ; import org . eclipse . core . commands . common . NotDefinedException ; import org . eclipse . e4 . ui . workbench . renderers . swt . HandledContributionItem ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IContributionItem ; import org . eclipse . jface . action . SubContributionItem ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . MenuItem ; import org . eclipse . swt . widgets . ToolItem ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . commands . ICommandService ; import org . eclipse . ui . menus . CommandContributionItem ; @ SuppressWarnings ( "<STR_LIT>" ) public class GlobalSelectionListener implements Listener { private static final String CONFIGURE_ACTION_INVOCATION_DEF = "<STR_LIT>" ; private final PreferenceAccessor preferences = PreferenceAccessor . getInstance ( ) ; private final ActionActionDescGenerator actionActionDescGenerator = new ActionActionDescGenerator ( ) ; private final CommandActionDescGenerator commandActionDescGenerator = new CommandActionDescGenerator ( ) ; private final HandledActionDescGenerator handledActionDescGenerator = new HandledActionDescGenerator ( ) ; private final Collector collector = Activator . getDefault ( ) . getCollector ( ) ; private final ICommandService commandService = ( ICommandService ) getWorkbench ( ) . getService ( ICommandService . class ) ; private final Map < String , Integer > actionUsageMonitor = new HashMap < String , Integer > ( ) ; public GlobalSelectionListener ( ) { } @ Override public void handleEvent ( final Event event ) { final Widget widget = event . widget ; if ( widget instanceof ToolItem || widget instanceof MenuItem ) { final Object data = widget . getData ( ) ; if ( data instanceof IContributionItem ) { processContributionItem ( ( IContributionItem ) data , event ) ; } } else { } } private void processContributionItem ( final IContributionItem contributionItem , final Event event ) { if ( contributionItem instanceof SubContributionItem ) { final SubContributionItem subCI = ( SubContributionItem ) contributionItem ; processContributionItem ( subCI . getInnerItem ( ) , event ) ; } else if ( contributionItem instanceof ActionContributionItem ) { final ActionContributionItem item = ( ActionContributionItem ) contributionItem ; final AbstractActionDesc actionDesc = actionActionDescGenerator . generate ( item . getAction ( ) ) ; processActionDesc ( actionDesc , event ) ; } else if ( contributionItem instanceof CommandContributionItem ) { final AbstractActionDesc actionDesc = commandActionDescGenerator . generate ( ( CommandContributionItem ) contributionItem ) ; processActionDesc ( actionDesc , event ) ; } else if ( contributionItem instanceof HandledContributionItem ) { final AbstractActionDesc actionDesc = handledActionDescGenerator . generate ( ( HandledContributionItem ) contributionItem ) ; processActionDesc ( actionDesc , event ) ; } else { } } private void processActionDesc ( final AbstractActionDesc actionDesc , final Event event ) { if ( CONFIGURE_ACTION_INVOCATION_DEF . equals ( actionDesc . getId ( ) ) ) { return ; } giveActionFeedback ( actionDesc , event ) ; logUserAction ( actionDesc ) ; commandService . refreshElements ( CONFIGURE_ACTION_INVOCATION_DEF , null ) ; } private IWorkbench getWorkbench ( ) { return PlatformUI . getWorkbench ( ) ; } private void logUserAction ( final AbstractActionDesc actionDesc ) { collector . onAction ( actionDesc ) ; } private void giveActionFeedback ( final AbstractActionDesc actionDesc , final Event event ) { notNull ( actionDesc ) ; isTrue ( StringUtils . isNotBlank ( actionDesc . getLabel ( ) ) ) ; if ( ! preferences . isInvocationControlEnabled ( ) ) { return ; } final String id = actionDesc . getId ( ) ; if ( ! actionDesc . hasAccelerator ( ) ) { Integer currentCount = actionUsageMonitor . get ( id ) ; if ( currentCount == null ) { currentCount = Integer . valueOf ( <NUM_LIT:0> ) ; } currentCount = currentCount + <NUM_LIT:1> ; actionUsageMonitor . put ( id , currentCount ) ; if ( isConfigureKeyboardShortcutEnabled ( currentCount . intValue ( ) ) && isConfigurableAction ( actionDesc ) ) { new NagPopUp ( actionDesc . getLabel ( ) , actionDesc . getId ( ) ) . open ( ) ; } return ; } switch ( getOnWrongInvocationMode ( id ) ) { case DO_NOTHING : break ; case REMIND : new NagPopUp ( actionDesc . getLabel ( ) , actionDesc . getAccelerator ( ) , false ) . open ( ) ; break ; case ENFORCE : cancelEvent ( event ) ; new NagPopUp ( actionDesc . getLabel ( ) , actionDesc . getAccelerator ( ) + "<STR_LIT>" , true ) . open ( ) ; break ; default : throw new AssertionError ( ) ; } } @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) protected boolean isConfigurableAction ( final AbstractActionDesc actionDesc ) { final String actionId = actionDesc . getId ( ) ; final Command command = commandService . getCommand ( actionId ) ; if ( command != null ) { final HashSet allParameterizedCommands = new HashSet ( ) ; try { allParameterizedCommands . addAll ( ParameterizedCommand . generateCombinations ( command ) ) ; } catch ( final NotDefinedException e ) { } return ! allParameterizedCommands . isEmpty ( ) ; } return false ; } public boolean isConfigureKeyboardShortcutEnabled ( final int currentCount ) { final boolean isConfigureKeyboardShortcutEnabled = preferences . isConfigureKeyboardShortcutEnabled ( ) ; final boolean isCounterAboveThreshold = currentCount > preferences . getConfigureKeyboardShortcutThreshold ( ) ; return isConfigureKeyboardShortcutEnabled && isCounterAboveThreshold ; } private OnWrongInvocationMode getOnWrongInvocationMode ( final String id ) { final OnWrongInvocationMode mode = preferences . getOnWrongInvocationMode ( id ) ; return mode == null ? preferences . getOnWrongInvocationMode ( ) : mode ; } private void cancelEvent ( final Event event ) { event . type = SWT . None ; event . doit = false ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . test ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . List ; import org . junit . Test ; import ch . ethz . inf . vs . californium . coap . LinkFormat ; import ch . ethz . inf . vs . californium . coap . Option ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . endpoint . RemoteResource ; import ch . ethz . inf . vs . californium . endpoint . Resource ; public class ResourceTest { @ Test public void simpleTest ( ) { System . out . println ( "<STR_LIT>" ) ; String input = "<STR_LIT>" ; Resource root = RemoteResource . newRoot ( input ) ; root . prettyPrint ( ) ; Resource res = root . getResource ( "<STR_LIT>" ) ; assertNotNull ( res ) ; System . out . println ( res . getName ( ) ) ; assertEquals ( "<STR_LIT>" , res . getName ( ) ) ; assertEquals ( Integer . valueOf ( <NUM_LIT> ) , res . getContentTypeCode ( ) . get ( <NUM_LIT:0> ) ) ; assertEquals ( "<STR_LIT>" , res . getResourceType ( ) . get ( <NUM_LIT:0> ) ) ; } @ Test public void extendedTest ( ) { System . out . println ( "<STR_LIT>" ) ; String input = "<STR_LIT>" ; Resource root = RemoteResource . newRoot ( input ) ; RemoteResource my = new RemoteResource ( "<STR_LIT>" ) ; my . setResourceType ( "<STR_LIT>" ) ; root . add ( my ) ; root . prettyPrint ( ) ; Resource res = root . getResource ( "<STR_LIT>" ) ; assertNotNull ( res ) ; res = root . getResource ( "<STR_LIT>" ) ; assertNotNull ( res ) ; res = root . getResource ( "<STR_LIT>" ) ; res = res . getResource ( "<STR_LIT>" ) ; assertNotNull ( res ) ; res = res . getResource ( "<STR_LIT>" ) ; assertNotNull ( res ) ; assertEquals ( "<STR_LIT>" , res . getName ( ) ) ; assertEquals ( "<STR_LIT>" , res . getPath ( ) ) ; assertEquals ( "<STR_LIT>" , res . getResourceType ( ) . get ( <NUM_LIT:0> ) ) ; assertEquals ( "<STR_LIT>" , res . getInterfaceDescription ( ) . get ( <NUM_LIT:0> ) ) ; assertEquals ( <NUM_LIT> , res . getContentTypeCode ( ) . get ( <NUM_LIT:0> ) . intValue ( ) ) ; assertEquals ( <NUM_LIT:10> , res . getMaximumSizeEstimate ( ) ) ; assertTrue ( res . isObservable ( ) ) ; res = root . getResource ( "<STR_LIT>" ) ; assertNotNull ( res ) ; assertEquals ( "<STR_LIT>" , res . getResourceType ( ) . get ( <NUM_LIT:0> ) ) ; } @ Test public void conversionTest ( ) { System . out . println ( "<STR_LIT>" ) ; String link1 = "<STR_LIT>" ; String link2 = "<STR_LIT>" ; String link3 = "<STR_LIT>" ; String format = link1 + "<STR_LIT:U+002C>" + link2 + "<STR_LIT:U+002C>" + link3 ; Resource res = RemoteResource . newRoot ( format ) ; res . prettyPrint ( ) ; String result = LinkFormat . serialize ( res , null , true ) ; System . out . println ( link3 + "<STR_LIT:U+002C>" + link2 + "<STR_LIT:U+002C>" + link1 ) ; System . out . println ( result ) ; assertEquals ( link3 + "<STR_LIT:U+002C>" + link2 + "<STR_LIT:U+002C>" + link1 , result ) ; } @ Test public void concreteTest ( ) { System . out . println ( "<STR_LIT>" ) ; String link = "<STR_LIT>" ; Resource res = RemoteResource . newRoot ( link ) ; String result = LinkFormat . serialize ( res , null , true ) ; System . out . println ( link ) ; System . out . println ( result ) ; assertEquals ( link , result ) ; } @ Test public void matchTest ( ) { System . out . println ( "<STR_LIT>" ) ; String link1 = "<STR_LIT>" ; String link2 = "<STR_LIT>" ; String link3 = "<STR_LIT>" ; String format = link1 + "<STR_LIT:U+002C>" + link2 + "<STR_LIT:U+002C>" + link3 ; Resource res = RemoteResource . newRoot ( format ) ; res . prettyPrint ( ) ; List < Option > query = new ArrayList < Option > ( ) ; query . add ( new Option ( "<STR_LIT>" , OptionNumberRegistry . URI_QUERY ) ) ; System . out . println ( LinkFormat . matches ( res . getResource ( "<STR_LIT>" ) , query ) ) ; String queried = LinkFormat . serialize ( res , query , true ) ; assertEquals ( link2 + "<STR_LIT:U+002C>" + link1 , queried ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . test ; import static org . junit . Assert . * ; import org . junit . Test ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . Message ; import ch . ethz . inf . vs . californium . coap . Option ; import ch . ethz . inf . vs . californium . coap . Message . messageType ; public class MessageTest { @ Test public void testMessage ( ) { Message msg = new Message ( ) ; msg . setCode ( CodeRegistry . METHOD_GET ) ; msg . setType ( messageType . CON ) ; msg . setMID ( <NUM_LIT> ) ; msg . setPayload ( "<STR_LIT>" . getBytes ( ) ) ; System . out . println ( msg . toString ( ) ) ; byte [ ] data = msg . toByteArray ( ) ; Message convMsg = Message . fromByteArray ( data ) ; assertEquals ( msg . getCode ( ) , convMsg . getCode ( ) ) ; assertEquals ( msg . getType ( ) , convMsg . getType ( ) ) ; assertEquals ( msg . getMID ( ) , convMsg . getMID ( ) ) ; assertEquals ( msg . getOptionCount ( ) , convMsg . getOptionCount ( ) ) ; assertArrayEquals ( msg . getPayload ( ) , convMsg . getPayload ( ) ) ; } @ Test public void testOptionMessage ( ) { Message msg = new Message ( ) ; msg . setCode ( CodeRegistry . METHOD_GET ) ; msg . setType ( messageType . CON ) ; msg . setMID ( <NUM_LIT> ) ; msg . setPayload ( "<STR_LIT>" . getBytes ( ) ) ; msg . addOption ( new Option ( "<STR_LIT:a>" . getBytes ( ) , <NUM_LIT:1> ) ) ; msg . addOption ( new Option ( "<STR_LIT:b>" . getBytes ( ) , <NUM_LIT:2> ) ) ; byte [ ] data = msg . toByteArray ( ) ; Message convMsg = Message . fromByteArray ( data ) ; assertEquals ( msg . getCode ( ) , convMsg . getCode ( ) ) ; assertEquals ( msg . getType ( ) , convMsg . getType ( ) ) ; assertEquals ( msg . getMID ( ) , convMsg . getMID ( ) ) ; assertEquals ( msg . getOptionCount ( ) , convMsg . getOptionCount ( ) ) ; assertArrayEquals ( msg . getPayload ( ) , convMsg . getPayload ( ) ) ; } @ Test public void testExtendedOptionMessage ( ) { Message msg = new Message ( ) ; msg . setCode ( CodeRegistry . METHOD_GET ) ; msg . setType ( messageType . CON ) ; msg . setMID ( <NUM_LIT> ) ; msg . addOption ( new Option ( "<STR_LIT:a>" . getBytes ( ) , <NUM_LIT:1> ) ) ; msg . addOption ( new Option ( "<STR_LIT>" . getBytes ( ) , <NUM_LIT> ) ) ; byte [ ] data = msg . toByteArray ( ) ; try { System . out . printf ( "<STR_LIT>" , getHexString ( data ) , data . length ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } Message convMsg = Message . fromByteArray ( data ) ; assertEquals ( msg . getCode ( ) , convMsg . getCode ( ) ) ; assertEquals ( msg . getType ( ) , convMsg . getType ( ) ) ; assertEquals ( msg . getMID ( ) , convMsg . getMID ( ) ) ; assertEquals ( msg . getOptionCount ( ) , convMsg . getOptionCount ( ) ) ; } public static String getHexString ( byte [ ] b ) throws Exception { String result = "<STR_LIT>" ; for ( int i = <NUM_LIT:0> ; i < b . length ; i ++ ) { result += Integer . toString ( ( b [ i ] & <NUM_LIT> ) + <NUM_LIT> , <NUM_LIT:16> ) . substring ( <NUM_LIT:1> ) ; } return result ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . test ; import static org . junit . Assert . * ; import org . junit . Test ; import ch . ethz . inf . vs . californium . coap . Option ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; public class TokenEqualityTest { @ Test public void testEmptyToken ( ) { Option t1 = new Option ( new byte [ <NUM_LIT:0> ] , OptionNumberRegistry . TOKEN ) ; Option t2 = new Option ( new byte [ <NUM_LIT:0> ] , OptionNumberRegistry . TOKEN ) ; assertEquals ( t1 , t2 ) ; assertEquals ( <NUM_LIT:0> , t1 . getLength ( ) ) ; Option t3 = new Option ( "<STR_LIT>" , OptionNumberRegistry . TOKEN ) ; assertFalse ( t1 . equals ( t3 ) ) ; } @ Test public void testOneByteToken ( ) { Option t1 = new Option ( <NUM_LIT> , OptionNumberRegistry . TOKEN ) ; Option t2 = new Option ( <NUM_LIT> , OptionNumberRegistry . TOKEN ) ; assertEquals ( t1 , t2 ) ; assertEquals ( <NUM_LIT:1> , t1 . getLength ( ) ) ; Option t3 = new Option ( <NUM_LIT> , OptionNumberRegistry . TOKEN ) ; assertFalse ( t1 . equals ( t3 ) ) ; } @ Test public void testTwoByteToken ( ) { Option t1 = new Option ( <NUM_LIT> , OptionNumberRegistry . TOKEN ) ; Option t2 = new Option ( <NUM_LIT> , OptionNumberRegistry . TOKEN ) ; assertEquals ( t1 , t2 ) ; assertEquals ( <NUM_LIT:2> , t1 . getLength ( ) ) ; Option t3 = new Option ( <NUM_LIT> , OptionNumberRegistry . TOKEN ) ; assertFalse ( t1 . equals ( t3 ) ) ; } @ Test public void testFourByteToken ( ) { Option t1 = new Option ( <NUM_LIT> , OptionNumberRegistry . TOKEN ) ; Option t2 = new Option ( <NUM_LIT> , OptionNumberRegistry . TOKEN ) ; assertEquals ( t1 , t2 ) ; assertEquals ( <NUM_LIT:4> , t1 . getLength ( ) ) ; Option t3 = new Option ( <NUM_LIT> , OptionNumberRegistry . TOKEN ) ; assertFalse ( t1 . equals ( t3 ) ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . test ; import static org . junit . Assert . * ; import java . util . HashSet ; import java . util . Set ; import java . util . Timer ; import java . util . TimerTask ; import org . junit . Test ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; public class RequestTest { class RespondTask extends TimerTask { RespondTask ( Request request , Response response ) { this . request = request ; this . response = response ; } @ Override public void run ( ) { request . respond ( response ) ; } Request request ; Response response ; } Response handledResponse ; Timer timer = new Timer ( ) ; @ Test public void testRespond ( ) { Request request = new GETRequest ( ) { @ Override protected void handleResponse ( Response response ) { handledResponse = response ; } } ; Response response = new Response ( ) ; request . respond ( response ) ; assertSame ( response , handledResponse ) ; } @ Test public void testReceiveResponse ( ) throws InterruptedException { Request request = new GETRequest ( ) ; request . enableResponseQueue ( true ) ; Response response = new Response ( ) ; timer . schedule ( new RespondTask ( request , response ) , <NUM_LIT> ) ; Response receivedResponse = request . receiveResponse ( ) ; assertSame ( response , receivedResponse ) ; } @ Test public void testTokenManager ( ) { Set < byte [ ] > acquiredTokens = new HashSet < byte [ ] > ( ) ; final byte [ ] emptyToken = new byte [ <NUM_LIT:0> ] ; acquiredTokens . add ( emptyToken ) ; System . out . println ( "<STR_LIT>" + acquiredTokens . contains ( emptyToken ) ) ; acquiredTokens . remove ( emptyToken ) ; System . out . println ( "<STR_LIT>" + acquiredTokens . contains ( emptyToken ) ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . test ; import static org . junit . Assert . * ; import java . nio . ByteBuffer ; import java . nio . ByteOrder ; import org . junit . Test ; import ch . ethz . inf . vs . californium . util . DatagramReader ; import ch . ethz . inf . vs . californium . util . DatagramWriter ; public class DatagramReadWriteTest { @ Test public void test32BitInt ( ) { final int intIn = <NUM_LIT> ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( intIn , <NUM_LIT:32> ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int intOut = reader . read ( <NUM_LIT:32> ) ; assertEquals ( intIn , intOut ) ; } @ Test public void test32BitIntZero ( ) { final int intIn = <NUM_LIT> ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( intIn , <NUM_LIT:32> ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int intOut = reader . read ( <NUM_LIT:32> ) ; assertEquals ( intIn , intOut ) ; } @ Test public void test32BitIntOne ( ) { final int intIn = <NUM_LIT> ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( intIn , <NUM_LIT:32> ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int intOut = reader . read ( <NUM_LIT:32> ) ; assertEquals ( intIn , intOut ) ; } @ Test public void test16BitInt ( ) { final int intIn = <NUM_LIT> ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( intIn , <NUM_LIT:16> ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int intOut = reader . read ( <NUM_LIT:16> ) ; assertEquals ( intIn , intOut ) ; } @ Test public void test8BitInt ( ) { final int intIn = <NUM_LIT> ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( intIn , <NUM_LIT:8> ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int intOut = reader . read ( <NUM_LIT:8> ) ; assertEquals ( intIn , intOut ) ; } @ Test public void test4BitInt ( ) { final int intIn = <NUM_LIT> ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( intIn , <NUM_LIT:4> ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int intOut = reader . read ( <NUM_LIT:4> ) ; assertEquals ( intIn , intOut ) ; } @ Test public void test2BitInt ( ) { final int intIn = <NUM_LIT> ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( intIn , <NUM_LIT:2> ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int intOut = reader . read ( <NUM_LIT:2> ) ; assertEquals ( intIn , intOut ) ; } @ Test public void test1BitInt ( ) { final int intIn = <NUM_LIT> ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( intIn , <NUM_LIT:1> ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int intOut = reader . read ( <NUM_LIT:1> ) ; assertEquals ( intIn , intOut ) ; } @ Test public void testByteOrder ( ) { final int intIn = <NUM_LIT> ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( intIn , <NUM_LIT:32> ) ; final byte [ ] data = writer . toByteArray ( ) ; ByteBuffer buf = ByteBuffer . wrap ( data ) ; buf . order ( ByteOrder . BIG_ENDIAN ) ; int intTrans = buf . getInt ( ) ; assertEquals ( intIn , intTrans ) ; DatagramReader reader = new DatagramReader ( data ) ; int intOut = reader . read ( <NUM_LIT:32> ) ; assertEquals ( intIn , intOut ) ; } @ Test public void testAlignedBytes ( ) { final byte [ ] bytesIn = "<STR_LIT>" . getBytes ( ) ; DatagramWriter writer = new DatagramWriter ( ) ; writer . writeBytes ( bytesIn ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; byte [ ] bytesOut = reader . readBytes ( bytesIn . length ) ; assertArrayEquals ( bytesIn , bytesOut ) ; } @ Test public void testUnalignedBytes1 ( ) { final int bitCount = <NUM_LIT:1> ; final int bitsIn = <NUM_LIT> ; final byte [ ] bytesIn = "<STR_LIT>" . getBytes ( ) ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( bitsIn , bitCount ) ; writer . writeBytes ( bytesIn ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int bitsOut = reader . read ( bitCount ) ; byte [ ] bytesOut = reader . readBytes ( bytesIn . length ) ; assertEquals ( bitsIn , bitsOut ) ; assertArrayEquals ( bytesIn , bytesOut ) ; } @ Test public void testUnalignedBytes3 ( ) { final int bitCount = <NUM_LIT:3> ; final int bitsIn = <NUM_LIT> ; final byte [ ] bytesIn = "<STR_LIT>" . getBytes ( ) ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( bitsIn , bitCount ) ; writer . writeBytes ( bytesIn ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int bitsOut = reader . read ( bitCount ) ; byte [ ] bytesOut = reader . readBytes ( bytesIn . length ) ; assertEquals ( bitsIn , bitsOut ) ; assertArrayEquals ( bytesIn , bytesOut ) ; } @ Test public void testUnalignedBytes7 ( ) { final int bitCount = <NUM_LIT:7> ; final int bitsIn = <NUM_LIT> ; final byte [ ] bytesIn = "<STR_LIT>" . getBytes ( ) ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( bitsIn , bitCount ) ; writer . writeBytes ( bytesIn ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int bitsOut = reader . read ( bitCount ) ; byte [ ] bytesOut = reader . readBytes ( bytesIn . length ) ; assertEquals ( bitsIn , bitsOut ) ; assertArrayEquals ( bytesIn , bytesOut ) ; } @ Test public void testBytesLeft ( ) { final int bitCount = <NUM_LIT:8> ; final int bitsIn = <NUM_LIT> ; final byte [ ] bytesIn = "<STR_LIT>" . getBytes ( ) ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( bitsIn , bitCount ) ; writer . writeBytes ( bytesIn ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int bitsOut = reader . read ( bitCount ) ; byte [ ] bytesOut = reader . readBytesLeft ( ) ; assertEquals ( bitsIn , bitsOut ) ; assertArrayEquals ( bytesIn , bytesOut ) ; } @ Test public void testBytesLeftUnaligned ( ) { final int bitCount = <NUM_LIT:7> ; final int bitsIn = <NUM_LIT> ; final byte [ ] bytesIn = "<STR_LIT>" . getBytes ( ) ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( bitsIn , bitCount ) ; writer . writeBytes ( bytesIn ) ; DatagramReader reader = new DatagramReader ( writer . toByteArray ( ) ) ; int bitsOut = reader . read ( bitCount ) ; byte [ ] bytesOut = reader . readBytesLeft ( ) ; assertEquals ( bitsIn , bitsOut ) ; assertArrayEquals ( bytesIn , bytesOut ) ; } @ Test public void testGETRequestHeader ( ) { final int versionIn = <NUM_LIT:1> ; final int versionSz = <NUM_LIT:2> ; final int typeIn = <NUM_LIT:0> ; final int typeSz = <NUM_LIT:2> ; final int optionCntIn = <NUM_LIT:1> ; final int optionCntSz = <NUM_LIT:4> ; final int codeIn = <NUM_LIT:1> ; final int codeSz = <NUM_LIT:8> ; final int msgIdIn = <NUM_LIT> ; final int msgIdSz = <NUM_LIT:16> ; DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( versionIn , versionSz ) ; writer . write ( typeIn , typeSz ) ; writer . write ( optionCntIn , optionCntSz ) ; writer . write ( codeIn , codeSz ) ; writer . write ( msgIdIn , msgIdSz ) ; final byte [ ] data = writer . toByteArray ( ) ; final byte [ ] dataRef = { <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> } ; assertArrayEquals ( dataRef , data ) ; DatagramReader reader = new DatagramReader ( data ) ; int versionOut = reader . read ( versionSz ) ; int typeOut = reader . read ( typeSz ) ; int optionCntOut = reader . read ( optionCntSz ) ; int codeOut = reader . read ( codeSz ) ; int msgIdOut = reader . read ( msgIdSz ) ; assertEquals ( versionIn , versionOut ) ; assertEquals ( typeIn , typeOut ) ; assertEquals ( optionCntIn , optionCntOut ) ; assertEquals ( codeIn , codeOut ) ; assertEquals ( msgIdIn , msgIdOut ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . test ; import static org . junit . Assert . * ; import org . junit . Test ; import ch . ethz . inf . vs . californium . coap . Option ; public class OptionTest { @ Test public void testRawOption ( ) { byte [ ] dataRef = "<STR_LIT:test>" . getBytes ( ) ; int nrRef = <NUM_LIT:1> ; Option opt = new Option ( dataRef , nrRef ) ; assertArrayEquals ( dataRef , opt . getRawValue ( ) ) ; assertEquals ( dataRef . length , opt . getLength ( ) ) ; } @ Test public void testIntOption ( ) { int oneByteValue = <NUM_LIT:255> ; int twoBytesValue = <NUM_LIT> ; int nrRef = <NUM_LIT:1> ; Option optOneByte = new Option ( oneByteValue , nrRef ) ; Option optTwoBytes = new Option ( twoBytesValue , nrRef ) ; assertEquals ( <NUM_LIT:1> , optOneByte . getLength ( ) ) ; assertEquals ( <NUM_LIT:2> , optTwoBytes . getLength ( ) ) ; assertEquals ( <NUM_LIT:255> , optOneByte . getIntValue ( ) ) ; assertEquals ( <NUM_LIT> , optTwoBytes . getIntValue ( ) ) ; } @ Test public void testStringOption ( ) { String strRef = "<STR_LIT:test>" ; int nrRef = <NUM_LIT:1> ; Option opt = new Option ( strRef , nrRef ) ; assertEquals ( strRef , opt . getStringValue ( ) ) ; assertEquals ( strRef . getBytes ( ) . length , opt . getLength ( ) ) ; } @ Test public void testOptionNr ( ) { byte [ ] dataRef = "<STR_LIT:test>" . getBytes ( ) ; int nrRef = <NUM_LIT:1> ; Option opt = new Option ( dataRef , nrRef ) ; assertEquals ( nrRef , opt . getOptionNumber ( ) ) ; } @ Test public void equalityTest ( ) { int oneByteValue = <NUM_LIT:255> ; int twoBytesValue = <NUM_LIT> ; int nrRef = <NUM_LIT:1> ; Option optOneByte = new Option ( oneByteValue , nrRef ) ; Option optTwoBytes = new Option ( twoBytesValue , nrRef ) ; Option optTwoBytesRef = new Option ( twoBytesValue , nrRef ) ; assertTrue ( optTwoBytes . equals ( optTwoBytesRef ) ) ; assertFalse ( optTwoBytes . equals ( optOneByte ) ) ; } public static String getHexString ( byte [ ] b ) throws Exception { String result = "<STR_LIT>" ; for ( int i = <NUM_LIT:0> ; i < b . length ; i ++ ) { result += Integer . toString ( ( b [ i ] & <NUM_LIT> ) + <NUM_LIT> , <NUM_LIT:16> ) . substring ( <NUM_LIT:1> ) ; } return result ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . layers ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; import java . util . Timer ; import java . util . TimerTask ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . Message ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . coap . TokenManager ; import ch . ethz . inf . vs . californium . util . Properties ; public class TokenLayer extends UpperLayer { private Map < String , RequestResponseSequence > exchanges = new HashMap < String , RequestResponseSequence > ( ) ; private Timer timer = new Timer ( true ) ; private int sequenceTimeout ; private static class RequestResponseSequence { public String key ; public Request request ; public TimerTask timeoutTask ; } private class TimeoutTask extends TimerTask { private RequestResponseSequence sequence ; public TimeoutTask ( RequestResponseSequence sequence ) { this . sequence = sequence ; } @ Override public void run ( ) { transferTimedOut ( sequence ) ; } } public TokenLayer ( int sequenceTimeout ) { this . sequenceTimeout = sequenceTimeout ; } public TokenLayer ( ) { this ( Properties . std . getInt ( "<STR_LIT>" ) ) ; } @ Override protected void doSendMessage ( Message msg ) throws IOException { if ( msg . requiresToken ( ) ) { msg . setToken ( TokenManager . getInstance ( ) . acquireToken ( true ) ) ; } if ( msg instanceof Request ) { LOG . info ( String . format ( "<STR_LIT>" , ( ( Request ) msg ) . getUriPath ( ) , msg . sequenceKey ( ) ) ) ; addExchange ( ( Request ) msg ) ; } else if ( msg . getCode ( ) == CodeRegistry . EMPTY_MESSAGE ) { LOG . info ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; } else { LOG . info ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) ) ) ; } sendMessageOverLowerLayer ( msg ) ; } @ Override protected void doReceiveMessage ( Message msg ) { if ( msg instanceof Response ) { Response response = ( Response ) msg ; RequestResponseSequence sequence = getExchange ( msg . sequenceKey ( ) ) ; if ( sequence == null && response . getToken ( ) . length == <NUM_LIT:0> ) { LOG . warning ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; return ; } if ( sequence != null ) { sequence . timeoutTask . cancel ( ) ; if ( msg . getFirstOption ( OptionNumberRegistry . OBSERVE ) == null ) { removeExchange ( msg . sequenceKey ( ) ) ; } LOG . info ( String . format ( "<STR_LIT>" , ( ( Response ) msg ) . getRequest ( ) . getUriPath ( ) , msg . sequenceKey ( ) , ( ( Response ) msg ) . getRTT ( ) ) ) ; deliverMessage ( msg ) ; } else { LOG . warning ( String . format ( "<STR_LIT>" , response . sequenceKey ( ) ) ) ; } } else if ( msg instanceof Request ) { LOG . info ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) ) ) ; deliverMessage ( msg ) ; } } private synchronized RequestResponseSequence addExchange ( Request request ) { removeExchange ( request . sequenceKey ( ) ) ; RequestResponseSequence sequence = new RequestResponseSequence ( ) ; sequence . key = request . sequenceKey ( ) ; sequence . request = request ; sequence . timeoutTask = new TimeoutTask ( sequence ) ; exchanges . put ( sequence . key , sequence ) ; timer . schedule ( sequence . timeoutTask , sequenceTimeout ) ; LOG . fine ( String . format ( "<STR_LIT>" , sequence . key ) ) ; return sequence ; } private RequestResponseSequence getExchange ( String key ) { return exchanges . get ( key ) ; } private synchronized void removeExchange ( String key ) { RequestResponseSequence exchange = exchanges . remove ( key ) ; if ( exchange != null ) { exchange . timeoutTask . cancel ( ) ; TokenManager . getInstance ( ) . releaseToken ( exchange . request . getToken ( ) ) ; LOG . finer ( String . format ( "<STR_LIT>" , exchange . key ) ) ; } } private void transferTimedOut ( RequestResponseSequence exchange ) { removeExchange ( exchange . key ) ; LOG . warning ( String . format ( "<STR_LIT>" , exchange . request . sequenceKey ( ) ) ) ; exchange . request . handleTimeout ( ) ; } public String getStats ( ) { StringBuilder stats = new StringBuilder ( ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( exchanges . size ( ) ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( numMessagesSent ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( numMessagesReceived ) ; return stats . toString ( ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . layers ; import java . io . IOException ; import ch . ethz . inf . vs . californium . coap . Message ; public class AdverseLayer extends UpperLayer { public AdverseLayer ( double txPacketLossProbability , double rxPacketLossProbability ) { this . txPacketLossProbability = txPacketLossProbability ; this . rxPacketLossProbability = rxPacketLossProbability ; } public AdverseLayer ( ) { this ( <NUM_LIT> , <NUM_LIT> ) ; } @ Override protected void doSendMessage ( Message msg ) throws IOException { if ( Math . random ( ) >= txPacketLossProbability ) { sendMessageOverLowerLayer ( msg ) ; } else { System . err . printf ( "<STR_LIT>" , getClass ( ) . getName ( ) , msg . key ( ) ) ; } } @ Override protected void doReceiveMessage ( Message msg ) { if ( Math . random ( ) >= rxPacketLossProbability ) { deliverMessage ( msg ) ; } else { System . err . printf ( "<STR_LIT>" , getClass ( ) . getName ( ) , msg . key ( ) ) ; } } private double txPacketLossProbability ; private double rxPacketLossProbability ; } </s>
|
<s> package ch . ethz . inf . vs . californium . layers ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import java . util . logging . Logger ; import ch . ethz . inf . vs . californium . coap . Message ; import ch . ethz . inf . vs . californium . coap . MessageReceiver ; public abstract class Layer implements MessageReceiver { protected static final Logger LOG = Logger . getLogger ( Layer . class . getName ( ) ) ; private List < MessageReceiver > receivers ; protected int numMessagesSent ; protected int numMessagesReceived ; public void sendMessage ( Message msg ) throws IOException { if ( msg != null ) { doSendMessage ( msg ) ; ++ numMessagesSent ; } } @ Override public void receiveMessage ( Message msg ) { if ( msg != null ) { ++ numMessagesReceived ; doReceiveMessage ( msg ) ; } } protected abstract void doSendMessage ( Message msg ) throws IOException ; protected abstract void doReceiveMessage ( Message msg ) ; protected void deliverMessage ( Message msg ) { if ( receivers != null ) { for ( MessageReceiver receiver : receivers ) { receiver . receiveMessage ( msg ) ; } } } public void registerReceiver ( MessageReceiver receiver ) { if ( receiver != null && receiver != this ) { if ( receivers == null ) { receivers = new ArrayList < MessageReceiver > ( ) ; } receivers . add ( receiver ) ; } } public void unregisterReceiver ( MessageReceiver receiver ) { if ( receivers != null ) { receivers . remove ( receiver ) ; } } public int getNumMessagesSent ( ) { return numMessagesSent ; } public int getNumMessagesReceived ( ) { return numMessagesReceived ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . layers ; import java . io . IOException ; import java . net . DatagramPacket ; import java . net . DatagramSocket ; import java . net . SocketException ; import java . util . Arrays ; import ch . ethz . inf . vs . californium . coap . EndpointAddress ; import ch . ethz . inf . vs . californium . coap . Message ; import ch . ethz . inf . vs . californium . util . Properties ; public class UDPLayer extends Layer { private DatagramSocket socket ; private ReceiverThread receiverThread ; class ReceiverThread extends Thread { public ReceiverThread ( ) { super ( "<STR_LIT>" ) ; } @ Override public void run ( ) { while ( true ) { byte [ ] buffer = new byte [ Properties . std . getInt ( "<STR_LIT>" ) + <NUM_LIT:1> ] ; DatagramPacket datagram = new DatagramPacket ( buffer , buffer . length ) ; try { socket . receive ( datagram ) ; } catch ( IOException e ) { LOG . severe ( "<STR_LIT>" + e . getMessage ( ) ) ; e . printStackTrace ( ) ; continue ; } datagramReceived ( datagram ) ; } } } public UDPLayer ( int port , boolean daemon ) throws SocketException { this . socket = new DatagramSocket ( port ) ; this . receiverThread = new ReceiverThread ( ) ; receiverThread . setDaemon ( daemon ) ; this . receiverThread . start ( ) ; } public UDPLayer ( ) throws SocketException { this ( <NUM_LIT:0> , true ) ; } public void setDaemon ( boolean on ) { receiverThread . setDaemon ( on ) ; } @ Override protected void doSendMessage ( Message msg ) throws IOException { byte [ ] payload = msg . toByteArray ( ) ; DatagramPacket datagram = new DatagramPacket ( payload , payload . length , msg . getPeerAddress ( ) . getAddress ( ) , msg . getPeerAddress ( ) . getPort ( ) ) ; if ( msg . getTimestamp ( ) == - <NUM_LIT:1> ) { msg . setTimestamp ( System . nanoTime ( ) ) ; } socket . send ( datagram ) ; } @ Override protected void doReceiveMessage ( Message msg ) { deliverMessage ( msg ) ; } private void datagramReceived ( DatagramPacket datagram ) { if ( datagram . getLength ( ) > <NUM_LIT:0> ) { long timestamp = System . nanoTime ( ) ; byte [ ] data = Arrays . copyOfRange ( datagram . getData ( ) , datagram . getOffset ( ) , datagram . getLength ( ) ) ; Message msg = Message . fromByteArray ( data ) ; if ( msg != null ) { msg . setTimestamp ( timestamp ) ; msg . setPeerAddress ( new EndpointAddress ( datagram . getAddress ( ) , datagram . getPort ( ) ) ) ; if ( datagram . getLength ( ) > Properties . std . getInt ( "<STR_LIT>" ) ) { LOG . info ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; msg . requiresBlockwise ( true ) ; } try { receiveMessage ( msg ) ; } catch ( Exception e ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( e . getMessage ( ) ) ; builder . append ( '<STR_LIT:\n>' ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( e . getClass ( ) . getName ( ) ) ; builder . append ( "<STR_LIT>" ) ; for ( StackTraceElement elem : e . getStackTrace ( ) ) { builder . append ( "<STR_LIT>" ) ; builder . append ( elem . getClassName ( ) ) ; builder . append ( '<CHAR_LIT:.>' ) ; builder . append ( elem . getMethodName ( ) ) ; builder . append ( '<CHAR_LIT:(>' ) ; builder . append ( elem . getFileName ( ) ) ; builder . append ( '<CHAR_LIT::>' ) ; builder . append ( elem . getLineNumber ( ) ) ; builder . append ( "<STR_LIT>" ) ; } LOG . severe ( builder . toString ( ) ) ; } } else { LOG . severe ( "<STR_LIT>" + data . toString ( ) ) ; } } else { LOG . info ( String . format ( "<STR_LIT>" , datagram . getAddress ( ) . getHostName ( ) , datagram . getPort ( ) ) ) ; } } public boolean isDaemon ( ) { return receiverThread . isDaemon ( ) ; } public int getPort ( ) { return socket . getLocalPort ( ) ; } public String getStats ( ) { StringBuilder stats = new StringBuilder ( ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( getPort ( ) ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( numMessagesSent ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( numMessagesReceived ) ; return stats . toString ( ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . layers ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; import ch . ethz . inf . vs . californium . coap . Message ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; public class MatchingLayer extends UpperLayer { private Map < String , RequestResponsePair > pairs = new HashMap < String , RequestResponsePair > ( ) ; private static class RequestResponsePair { public String key ; public Request request ; } public MatchingLayer ( ) { } @ Override protected void doSendMessage ( Message msg ) throws IOException { if ( msg instanceof Request ) { addOpenRequest ( ( Request ) msg ) ; } sendMessageOverLowerLayer ( msg ) ; } @ Override protected void doReceiveMessage ( Message msg ) { if ( msg instanceof Response ) { Response response = ( Response ) msg ; RequestResponsePair pair = getOpenRequest ( msg . sequenceKey ( ) ) ; if ( pair == null && response . getToken ( ) . length == <NUM_LIT:0> ) { LOG . info ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; return ; } if ( pair != null ) { response . setRequest ( pair . request ) ; pair . request . setResponse ( response ) ; LOG . finer ( String . format ( "<STR_LIT>" , response . sequenceKey ( ) ) ) ; if ( msg . getFirstOption ( OptionNumberRegistry . OBSERVE ) == null ) { removeOpenRequest ( response . sequenceKey ( ) ) ; } } else { LOG . info ( String . format ( "<STR_LIT>" , response . sequenceKey ( ) ) ) ; return ; } } deliverMessage ( msg ) ; } private RequestResponsePair addOpenRequest ( Request request ) { RequestResponsePair exchange = new RequestResponsePair ( ) ; exchange . key = request . sequenceKey ( ) ; exchange . request = request ; LOG . finer ( String . format ( "<STR_LIT>" , exchange . key ) ) ; pairs . put ( exchange . key , exchange ) ; return exchange ; } private RequestResponsePair getOpenRequest ( String key ) { return pairs . get ( key ) ; } private void removeOpenRequest ( String key ) { RequestResponsePair exchange = pairs . remove ( key ) ; LOG . finer ( String . format ( "<STR_LIT>" , exchange . key ) ) ; } public String getStats ( ) { StringBuilder stats = new StringBuilder ( ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( pairs . size ( ) ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( numMessagesSent ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( numMessagesReceived ) ; return stats . toString ( ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . layers ; import java . io . IOException ; import ch . ethz . inf . vs . californium . coap . Message ; public abstract class UpperLayer extends Layer { public void sendMessageOverLowerLayer ( Message msg ) throws IOException { if ( lowerLayer != null ) { lowerLayer . sendMessage ( msg ) ; } else { System . out . printf ( "<STR_LIT>" , getClass ( ) . getName ( ) ) ; } } public void setLowerLayer ( Layer layer ) { if ( lowerLayer != null ) { lowerLayer . unregisterReceiver ( this ) ; } lowerLayer = layer ; if ( lowerLayer != null ) { lowerLayer . registerReceiver ( this ) ; } } public Layer getLowerLayer ( ) { return lowerLayer ; } private Layer lowerLayer ; } </s>
|
<s> package ch . ethz . inf . vs . californium . layers ; import java . io . IOException ; import java . util . HashMap ; import java . util . LinkedHashMap ; import java . util . Map ; import java . util . Timer ; import java . util . TimerTask ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . Message ; import ch . ethz . inf . vs . californium . coap . ObservingManager ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . coap . UnsupportedRequest ; import ch . ethz . inf . vs . californium . util . Properties ; public class TransactionLayer extends UpperLayer { private static int currentMID = ( int ) ( Math . random ( ) * <NUM_LIT> ) ; public static int nextMessageID ( ) { currentMID = ++ currentMID % <NUM_LIT> ; return currentMID ; } private Timer timer = new Timer ( true ) ; private Map < String , Transaction > transactionTable = new HashMap < String , Transaction > ( ) ; private MessageCache dupCache = new MessageCache ( ) ; private MessageCache replyCache = new MessageCache ( ) ; private static class Transaction { Message msg ; RetransmitTask retransmitTask ; int numRetransmit ; int timeout ; } @ SuppressWarnings ( "<STR_LIT:serial>" ) private static class MessageCache extends LinkedHashMap < String , Message > { @ Override protected boolean removeEldestEntry ( Map . Entry < String , Message > eldest ) { return size ( ) > Properties . std . getInt ( "<STR_LIT>" ) ; } } private class RetransmitTask extends TimerTask { private Transaction transaction ; RetransmitTask ( Transaction transaction ) { this . transaction = transaction ; } @ Override public void run ( ) { handleResponseTimeout ( transaction ) ; } } private static int initialTimeout ( ) { final double min = Properties . std . getDbl ( "<STR_LIT>" ) ; final double f = Properties . std . getDbl ( "<STR_LIT>" ) ; return ( int ) ( min + ( min * ( f - <NUM_LIT> ) * Math . random ( ) ) ) ; } public TransactionLayer ( ) { } @ Override protected void doSendMessage ( Message msg ) throws IOException { if ( msg . getMID ( ) < <NUM_LIT:0> ) { msg . setMID ( nextMessageID ( ) ) ; } if ( msg . isConfirmable ( ) ) { addTransaction ( msg ) ; } else if ( msg . isReply ( ) ) { replyCache . put ( msg . transactionKey ( ) , msg ) ; } sendMessageOverLowerLayer ( msg ) ; } @ Override protected void doReceiveMessage ( Message msg ) { if ( msg instanceof UnsupportedRequest ) { try { Message reply = msg . newReply ( msg . isConfirmable ( ) ) ; reply . setCode ( CodeRegistry . RESP_METHOD_NOT_ALLOWED ) ; reply . setPayload ( String . format ( "<STR_LIT>" , msg . getCode ( ) ) ) ; sendMessageOverLowerLayer ( reply ) ; LOG . info ( String . format ( "<STR_LIT>" , msg . getCode ( ) , msg . key ( ) ) ) ; } catch ( IOException e ) { LOG . severe ( String . format ( "<STR_LIT>" , msg . key ( ) , e . getMessage ( ) ) ) ; } return ; } if ( dupCache . containsKey ( msg . key ( ) ) ) { if ( msg . isConfirmable ( ) ) { Message reply = replyCache . get ( msg . transactionKey ( ) ) ; if ( reply != null ) { try { sendMessageOverLowerLayer ( reply ) ; LOG . info ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; } catch ( IOException e ) { LOG . severe ( String . format ( "<STR_LIT>" , msg . key ( ) , e . getMessage ( ) ) ) ; } } else { LOG . info ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; } return ; } else { LOG . info ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; return ; } } else { dupCache . put ( msg . key ( ) , msg ) ; } if ( msg . isReply ( ) ) { Transaction transaction = getTransaction ( msg ) ; if ( transaction != null ) { removeTransaction ( transaction ) ; if ( msg . isEmptyACK ( ) ) { return ; } else if ( msg . getType ( ) == Message . messageType . RST ) { handleIncomingReset ( msg ) ; return ; } } else if ( msg . getType ( ) == Message . messageType . RST ) { handleIncomingReset ( msg ) ; return ; } else { LOG . warning ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; return ; } } if ( msg instanceof Response && msg . isConfirmable ( ) ) { try { LOG . info ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; sendMessageOverLowerLayer ( msg . newAccept ( ) ) ; } catch ( IOException e ) { LOG . severe ( String . format ( "<STR_LIT>" , msg . key ( ) , e . getMessage ( ) ) ) ; } } deliverMessage ( msg ) ; } private void handleIncomingReset ( Message msg ) { ObservingManager . getInstance ( ) . removeObserver ( msg . getPeerAddress ( ) . toString ( ) , msg . getMID ( ) ) ; } private void handleResponseTimeout ( Transaction transaction ) { final int max = Properties . std . getInt ( "<STR_LIT>" ) ; if ( transaction . numRetransmit < max ) { transaction . msg . setRetransmissioned ( ++ transaction . numRetransmit ) ; LOG . info ( String . format ( "<STR_LIT>" , transaction . msg . key ( ) , transaction . numRetransmit , max ) ) ; try { sendMessageOverLowerLayer ( transaction . msg ) ; } catch ( IOException e ) { LOG . severe ( String . format ( "<STR_LIT>" , e . getMessage ( ) ) ) ; removeTransaction ( transaction ) ; return ; } scheduleRetransmission ( transaction ) ; } else { removeTransaction ( transaction ) ; ObservingManager . getInstance ( ) . removeObserver ( transaction . msg . getPeerAddress ( ) . toString ( ) ) ; transaction . msg . handleTimeout ( ) ; } } private synchronized Transaction addTransaction ( Message msg ) { Transaction transaction = new Transaction ( ) ; transaction . msg = msg ; transaction . numRetransmit = <NUM_LIT:0> ; transaction . retransmitTask = null ; transactionTable . put ( msg . transactionKey ( ) , transaction ) ; scheduleRetransmission ( transaction ) ; LOG . finest ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; return transaction ; } private synchronized Transaction getTransaction ( Message msg ) { return transactionTable . get ( msg . transactionKey ( ) ) ; } private synchronized void removeTransaction ( Transaction transaction ) { transaction . retransmitTask . cancel ( ) ; transaction . retransmitTask = null ; transactionTable . remove ( transaction . msg . transactionKey ( ) ) ; LOG . finest ( String . format ( "<STR_LIT>" , transaction . msg . key ( ) ) ) ; } private void scheduleRetransmission ( Transaction transaction ) { if ( transaction . retransmitTask != null ) { transaction . retransmitTask . cancel ( ) ; } transaction . retransmitTask = new RetransmitTask ( transaction ) ; if ( transaction . timeout == <NUM_LIT:0> ) { transaction . timeout = initialTimeout ( ) ; } else { transaction . timeout *= <NUM_LIT:2> ; } timer . schedule ( transaction . retransmitTask , transaction . timeout ) ; } public String getStats ( ) { StringBuilder stats = new StringBuilder ( ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( currentMID ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( transactionTable . size ( ) ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( numMessagesSent ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( numMessagesReceived ) ; return stats . toString ( ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . layers ; import java . io . IOException ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Map ; import ch . ethz . inf . vs . californium . coap . BlockOption ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . Message ; import ch . ethz . inf . vs . californium . coap . Option ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . coap . Message . messageType ; import ch . ethz . inf . vs . californium . util . Properties ; public class TransferLayer extends UpperLayer { private class TransferContext { public Message cache ; public String uriPath ; public BlockOption current ; TransferContext ( Message msg ) { if ( msg instanceof Request ) { this . cache = msg ; this . uriPath = msg . getUriPath ( ) ; this . current = ( BlockOption ) msg . getFirstOption ( OptionNumberRegistry . BLOCK1 ) ; } else if ( msg instanceof Response ) { msg . requiresToken ( false ) ; this . cache = msg ; this . uriPath = ( ( Response ) msg ) . getRequest ( ) . getUriPath ( ) ; this . current = ( BlockOption ) msg . getFirstOption ( OptionNumberRegistry . BLOCK2 ) ; } LOG . finest ( String . format ( "<STR_LIT>" , this . uriPath , msg . sequenceKey ( ) ) ) ; } } private Map < String , TransferContext > incoming = new HashMap < String , TransferContext > ( ) ; private Map < String , TransferContext > outgoing = new HashMap < String , TransferContext > ( ) ; private int defaultSZX ; public TransferLayer ( int defaultBlockSize ) { if ( defaultBlockSize == <NUM_LIT:0> ) { defaultBlockSize = Properties . std . getInt ( "<STR_LIT>" ) ; } if ( defaultBlockSize > <NUM_LIT:0> ) { defaultSZX = BlockOption . encodeSZX ( defaultBlockSize ) ; if ( ! BlockOption . validSZX ( defaultSZX ) ) { defaultSZX = defaultBlockSize > <NUM_LIT> ? <NUM_LIT:6> : BlockOption . encodeSZX ( defaultBlockSize & <NUM_LIT> ) ; LOG . warning ( String . format ( "<STR_LIT>" , defaultBlockSize , BlockOption . decodeSZX ( defaultSZX ) ) ) ; } } else { defaultSZX = - <NUM_LIT:1> ; } } public TransferLayer ( ) { this ( <NUM_LIT:0> ) ; } @ Override protected void doSendMessage ( Message msg ) throws IOException { int sendSZX = defaultSZX ; int sendNUM = <NUM_LIT:0> ; if ( msg instanceof Response && ( ( Response ) msg ) . getRequest ( ) != null ) { BlockOption buddyBlock = ( BlockOption ) ( ( Response ) msg ) . getRequest ( ) . getFirstOption ( OptionNumberRegistry . BLOCK2 ) ; if ( buddyBlock != null ) { if ( buddyBlock . getSZX ( ) < defaultSZX ) { sendSZX = buddyBlock . getSZX ( ) ; } sendNUM = buddyBlock . getNUM ( ) ; } } if ( msg . payloadSize ( ) > BlockOption . decodeSZX ( sendSZX ) ) { Message msgBlock = getBlock ( msg , sendNUM , sendSZX ) ; if ( msgBlock != null ) { BlockOption block1 = ( BlockOption ) msgBlock . getFirstOption ( OptionNumberRegistry . BLOCK1 ) ; BlockOption block2 = ( BlockOption ) msgBlock . getFirstOption ( OptionNumberRegistry . BLOCK2 ) ; if ( block1 != null && block1 . getM ( ) || block2 != null && block2 . getM ( ) ) { msg . setOption ( block1 ) ; msg . setOption ( block2 ) ; TransferContext transfer = new TransferContext ( msg ) ; outgoing . put ( msg . sequenceKey ( ) , transfer ) ; LOG . fine ( String . format ( "<STR_LIT>" , sendNUM , msg . sequenceKey ( ) ) ) ; } else { LOG . finer ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) , block2 ) ) ; } sendMessageOverLowerLayer ( msgBlock ) ; } else { LOG . info ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) , sendNUM , sendSZX , BlockOption . decodeSZX ( sendSZX ) , msg . payloadSize ( ) ) ) ; handleOutOfScopeError ( msg . newReply ( true ) ) ; } } else { sendMessageOverLowerLayer ( msg ) ; } } @ Override protected void doReceiveMessage ( Message msg ) { BlockOption blockIn = null ; BlockOption blockOut = null ; if ( msg instanceof Request ) { blockIn = ( BlockOption ) msg . getFirstOption ( OptionNumberRegistry . BLOCK1 ) ; blockOut = ( BlockOption ) msg . getFirstOption ( OptionNumberRegistry . BLOCK2 ) ; } else if ( msg instanceof Response ) { blockIn = ( BlockOption ) msg . getFirstOption ( OptionNumberRegistry . BLOCK2 ) ; blockOut = ( BlockOption ) msg . getFirstOption ( OptionNumberRegistry . BLOCK1 ) ; if ( blockOut != null ) { blockOut . setNUM ( blockOut . getNUM ( ) + <NUM_LIT:1> ) ; } } else { LOG . warning ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; return ; } if ( blockIn == null && msg . requiresBlockwise ( ) ) { blockIn = new BlockOption ( OptionNumberRegistry . BLOCK1 , <NUM_LIT:0> , defaultSZX , true ) ; handleIncomingPayload ( msg , blockIn ) ; return ; } else if ( blockIn != null ) { handleIncomingPayload ( msg , blockIn ) ; return ; } else if ( blockOut != null ) { LOG . finer ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) , blockOut ) ) ; TransferContext transfer = outgoing . get ( msg . sequenceKey ( ) ) ; if ( transfer != null ) { if ( msg instanceof Request && ! msg . getUriPath ( ) . equals ( transfer . uriPath ) ) { outgoing . remove ( msg . sequenceKey ( ) ) ; LOG . fine ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) ) ) ; } else { if ( msg instanceof Request ) { transfer . cache . setMID ( msg . getMID ( ) ) ; } Message next = getBlock ( transfer . cache , blockOut . getNUM ( ) , blockOut . getSZX ( ) ) ; if ( next != null ) { try { LOG . finer ( String . format ( "<STR_LIT>" , next . sequenceKey ( ) , blockOut ) ) ; sendMessageOverLowerLayer ( next ) ; } catch ( IOException e ) { LOG . severe ( String . format ( "<STR_LIT>" , e . getMessage ( ) ) ) ; } BlockOption respBlock = ( BlockOption ) next . getFirstOption ( blockOut . getOptionNumber ( ) ) ; if ( ! respBlock . getM ( ) && msg instanceof Request ) { outgoing . remove ( msg . sequenceKey ( ) ) ; LOG . fine ( String . format ( "<STR_LIT>" , next . sequenceKey ( ) ) ) ; } return ; } else if ( msg instanceof Response && ! blockOut . getM ( ) ) { outgoing . remove ( msg . sequenceKey ( ) ) ; LOG . fine ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) ) ) ; ( ( Response ) msg ) . setRequest ( ( Request ) transfer . cache ) ; } else { LOG . warning ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) , blockOut , transfer . cache . payloadSize ( ) ) ) ; outgoing . remove ( msg . sequenceKey ( ) ) ; handleOutOfScopeError ( msg . newReply ( true ) ) ; return ; } } } } else if ( msg instanceof Response ) { TransferContext transfer = outgoing . get ( msg . sequenceKey ( ) ) ; if ( transfer != null ) { ( ( Response ) msg ) . setRequest ( ( Request ) transfer . cache ) ; outgoing . remove ( msg . sequenceKey ( ) ) ; LOG . fine ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) ) ) ; } transfer = incoming . get ( msg . sequenceKey ( ) ) ; if ( transfer != null ) { ( ( Response ) msg ) . setRequest ( ( Request ) transfer . cache ) ; incoming . remove ( msg . sequenceKey ( ) ) ; LOG . fine ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) ) ) ; } } deliverMessage ( msg ) ; } private void handleIncomingPayload ( Message msg , BlockOption blockOpt ) { TransferContext transfer = incoming . get ( msg . sequenceKey ( ) ) ; if ( blockOpt . getNUM ( ) > <NUM_LIT:0> && transfer != null ) { if ( blockOpt . getNUM ( ) * blockOpt . getSize ( ) == ( transfer . current . getNUM ( ) + <NUM_LIT:1> ) * transfer . current . getSize ( ) ) { transfer . cache . appendPayload ( msg . getPayload ( ) ) ; transfer . cache . setMID ( msg . getMID ( ) ) ; LOG . fine ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) , blockOpt ) ) ; } else { LOG . info ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) , blockOpt ) ) ; } } else if ( blockOpt . getNUM ( ) == <NUM_LIT:0> && msg . payloadSize ( ) > <NUM_LIT:0> ) { if ( msg . payloadSize ( ) > blockOpt . getSize ( ) ) { int newNUM = msg . payloadSize ( ) / blockOpt . getSize ( ) ; blockOpt . setNUM ( newNUM - <NUM_LIT:1> ) ; msg . setPayload ( Arrays . copyOf ( msg . getPayload ( ) , newNUM ) ) ; } transfer = new TransferContext ( msg ) ; incoming . put ( msg . sequenceKey ( ) , transfer ) ; LOG . fine ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) , blockOpt ) ) ; } else { LOG . info ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) , blockOpt ) ) ; handleIncompleteError ( msg . newReply ( true ) ) ; return ; } if ( blockOpt . getM ( ) ) { Message reply = null ; int demandSZX = blockOpt . getSZX ( ) ; int demandNUM = blockOpt . getNUM ( ) ; if ( demandSZX > defaultSZX ) { demandNUM = demandSZX / defaultSZX * demandNUM ; demandSZX = defaultSZX ; } if ( msg instanceof Response ) { reply = new Request ( CodeRegistry . METHOD_GET , ! msg . isNonConfirmable ( ) ) ; reply . setURI ( "<STR_LIT>" + msg . getPeerAddress ( ) . toString ( ) + transfer . uriPath ) ; ++ demandNUM ; } else if ( msg instanceof Request ) { reply = new Response ( CodeRegistry . RESP_VALID ) ; reply . setType ( msg . isConfirmable ( ) ? messageType . ACK : messageType . NON ) ; reply . setPeerAddress ( msg . getPeerAddress ( ) ) ; if ( msg . isConfirmable ( ) ) reply . setMID ( msg . getMID ( ) ) ; } else { LOG . severe ( String . format ( "<STR_LIT>" , msg . key ( ) ) ) ; return ; } BlockOption next = new BlockOption ( blockOpt . getOptionNumber ( ) , demandNUM , demandSZX , blockOpt . getOptionNumber ( ) == OptionNumberRegistry . BLOCK1 ) ; reply . setOption ( msg . getFirstOption ( OptionNumberRegistry . TOKEN ) ) ; reply . setOption ( next ) ; try { LOG . fine ( String . format ( "<STR_LIT>" , reply . sequenceKey ( ) , next ) ) ; sendMessageOverLowerLayer ( reply ) ; } catch ( IOException e ) { LOG . severe ( String . format ( "<STR_LIT>" , e . getMessage ( ) ) ) ; } transfer . current = blockOpt ; } else { transfer . cache . setOption ( blockOpt ) ; LOG . fine ( String . format ( "<STR_LIT>" , msg . sequenceKey ( ) ) ) ; incoming . remove ( msg . sequenceKey ( ) ) ; deliverMessage ( transfer . cache ) ; } } private void handleOutOfScopeError ( Message resp ) { resp . setCode ( CodeRegistry . RESP_BAD_REQUEST ) ; resp . setPayload ( "<STR_LIT>" ) ; try { sendMessageOverLowerLayer ( resp ) ; } catch ( IOException e ) { LOG . severe ( String . format ( "<STR_LIT>" , e . getMessage ( ) ) ) ; } } private void handleIncompleteError ( Message resp ) { resp . setCode ( CodeRegistry . RESP_REQUEST_ENTITY_INCOMPLETE ) ; resp . setPayload ( "<STR_LIT>" ) ; try { sendMessageOverLowerLayer ( resp ) ; } catch ( IOException e ) { LOG . severe ( String . format ( "<STR_LIT>" , e . getMessage ( ) ) ) ; } } private static Message getBlock ( Message msg , int num , int szx ) { int blockSize = <NUM_LIT:1> << ( szx + <NUM_LIT:4> ) ; int payloadOffset = num * blockSize ; int payloadLeft = msg . payloadSize ( ) - payloadOffset ; if ( payloadLeft > <NUM_LIT:0> ) { Message block = null ; if ( msg instanceof Request ) { block = new Request ( msg . getCode ( ) , msg . isConfirmable ( ) ) ; } else { block = new Response ( msg . getCode ( ) ) ; if ( num == <NUM_LIT:0> && msg . getType ( ) == Message . messageType . CON ) { block . setType ( Message . messageType . CON ) ; } else { block . setType ( msg . isNonConfirmable ( ) ? Message . messageType . NON : Message . messageType . ACK ) ; } block . setMID ( msg . getMID ( ) ) ; } block . setPeerAddress ( msg . getPeerAddress ( ) ) ; for ( Option opt : msg . getOptions ( ) ) { block . addOption ( opt ) ; } boolean m = blockSize < payloadLeft ; if ( ! m ) { blockSize = payloadLeft ; } byte [ ] blockPayload = new byte [ blockSize ] ; System . arraycopy ( msg . getPayload ( ) , payloadOffset , blockPayload , <NUM_LIT:0> , blockSize ) ; block . setPayload ( blockPayload ) ; Option blockOpt = null ; if ( msg instanceof Request ) { blockOpt = new BlockOption ( OptionNumberRegistry . BLOCK1 , num , szx , m ) ; } else { blockOpt = new BlockOption ( OptionNumberRegistry . BLOCK2 , num , szx , m ) ; } block . setOption ( blockOpt ) ; return block ; } else { return null ; } } public String getStats ( ) { StringBuilder stats = new StringBuilder ( ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( BlockOption . decodeSZX ( defaultSZX ) ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( outgoing . size ( ) ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( incoming . size ( ) ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( numMessagesSent ) ; stats . append ( '<STR_LIT:\n>' ) ; stats . append ( "<STR_LIT>" ) ; stats . append ( numMessagesReceived ) ; return stats . toString ( ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public interface ResponseHandler { void handleResponse ( Response response ) ; } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; import java . io . ByteArrayOutputStream ; import java . util . HashSet ; import java . util . Set ; import java . util . logging . Logger ; public class TokenManager { private static final Logger LOG = Logger . getLogger ( TokenManager . class . getName ( ) ) ; public static final byte [ ] emptyToken = new byte [ <NUM_LIT:0> ] ; private static TokenManager singleton = new TokenManager ( ) ; private Set < byte [ ] > acquiredTokens = new HashSet < byte [ ] > ( ) ; private long currentToken ; private TokenManager ( ) { this . currentToken = ( long ) ( Math . random ( ) * <NUM_LIT> ) ; } public static TokenManager getInstance ( ) { if ( singleton == null ) { synchronized ( Communicator . class ) { if ( singleton == null ) { singleton = new TokenManager ( ) ; } } } return singleton ; } private byte [ ] nextToken ( ) { ++ this . currentToken ; LOG . fine ( "<STR_LIT>" + currentToken ) ; long temp = this . currentToken ; ByteArrayOutputStream byteStream = new ByteArrayOutputStream ( OptionNumberRegistry . TOKEN_LEN ) ; while ( temp > <NUM_LIT:0> && byteStream . size ( ) < OptionNumberRegistry . TOKEN_LEN ) { byteStream . write ( ( int ) ( temp & <NUM_LIT> ) ) ; temp >>>= <NUM_LIT:8> ; } return byteStream . toByteArray ( ) ; } public synchronized byte [ ] acquireToken ( boolean preferEmptyToken ) { byte [ ] token = null ; if ( preferEmptyToken && acquiredTokens . add ( emptyToken ) ) { token = emptyToken ; } else { do { token = nextToken ( ) ; } while ( ! acquiredTokens . add ( token ) ) ; } return token ; } public byte [ ] acquireToken ( ) { return acquireToken ( false ) ; } public synchronized void releaseToken ( byte [ ] token ) { if ( ! acquiredTokens . remove ( token ) ) { LOG . warning ( String . format ( "<STR_LIT>" , Option . hex ( token ) ) ) ; } } public synchronized boolean isAcquired ( byte [ ] token ) { return acquiredTokens . contains ( token ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; import java . util . HashMap ; import java . util . Map ; import java . util . logging . Logger ; import ch . ethz . inf . vs . californium . coap . Message . messageType ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; import ch . ethz . inf . vs . californium . layers . TransactionLayer ; import ch . ethz . inf . vs . californium . util . Properties ; public class ObservingManager { private static final Logger LOG = Logger . getLogger ( ObservingManager . class . getName ( ) ) ; private class ObservingRelationship { public String clientID ; public String resourcePath ; public GETRequest request ; public int lastMID ; public ObservingRelationship ( GETRequest request ) { request . setMID ( - <NUM_LIT:1> ) ; this . clientID = request . getPeerAddress ( ) . toString ( ) ; this . resourcePath = request . getUriPath ( ) ; this . request = request ; this . lastMID = - <NUM_LIT:1> ; } } private static ObservingManager singleton = new ObservingManager ( ) ; private Map < String , Map < String , ObservingRelationship > > observersByResource = new HashMap < String , Map < String , ObservingRelationship > > ( ) ; private Map < String , Map < String , ObservingRelationship > > observersByClient = new HashMap < String , Map < String , ObservingRelationship > > ( ) ; private int checkInterval = Properties . std . getInt ( "<STR_LIT>" ) ; private Map < String , Integer > intervalByResource = new HashMap < String , Integer > ( ) ; private ObservingManager ( ) { } public static ObservingManager getInstance ( ) { return singleton ; } public void setRefreshInterval ( int interval ) { this . checkInterval = interval ; } public synchronized void notifyObservers ( LocalResource resource ) { Map < String , ObservingRelationship > resourceObservers = observersByResource . get ( resource . getPath ( ) ) ; synchronized ( this ) { if ( resourceObservers != null && resourceObservers . size ( ) > <NUM_LIT:0> ) { LOG . info ( String . format ( "<STR_LIT>" , resourceObservers . size ( ) , resource . getPath ( ) ) ) ; int check = - <NUM_LIT:1> ; if ( ! intervalByResource . containsKey ( resource . getPath ( ) ) ) { check = checkInterval ; } else { check = intervalByResource . get ( resource . getPath ( ) ) - <NUM_LIT:1> ; } if ( check <= <NUM_LIT:0> ) { intervalByResource . put ( resource . getPath ( ) , checkInterval ) ; LOG . info ( String . format ( "<STR_LIT>" , resource . getPath ( ) ) ) ; } else { intervalByResource . put ( resource . getPath ( ) , check ) ; } for ( ObservingRelationship observer : resourceObservers . values ( ) ) { GETRequest request = observer . request ; if ( check <= <NUM_LIT:0> ) { request . setType ( messageType . CON ) ; } else { request . setType ( messageType . NON ) ; } resource . performGET ( request ) ; prepareResponse ( request ) ; if ( request . getPeerAddress ( ) != null ) { request . getResponse ( ) . send ( ) ; } else { request . handleResponse ( request . getResponse ( ) ) ; } } } } } private void prepareResponse ( Request request ) { if ( request . getResponse ( ) . getMID ( ) == - <NUM_LIT:1> ) { request . getResponse ( ) . setMID ( TransactionLayer . nextMessageID ( ) ) ; } int secs = ( int ) ( ( System . currentTimeMillis ( ) - request . startTime ) / <NUM_LIT:1000> ) & <NUM_LIT> ; request . getResponse ( ) . setOption ( new Option ( secs , OptionNumberRegistry . OBSERVE ) ) ; updateLastMID ( request . getPeerAddress ( ) . toString ( ) , request . getUriPath ( ) , request . getResponse ( ) . getMID ( ) ) ; } public void addObserver ( GETRequest request , LocalResource resource ) { synchronized ( this ) { request . setObserving ( true ) ; ObservingRelationship toAdd = new ObservingRelationship ( request ) ; Map < String , ObservingRelationship > resourceObservers = observersByResource . get ( resource . getPath ( ) ) ; if ( resourceObservers == null ) { resourceObservers = new HashMap < String , ObservingRelationship > ( ) ; observersByResource . put ( resource . getPath ( ) , resourceObservers ) ; } Map < String , ObservingRelationship > clientObservees = observersByClient . get ( request . getPeerAddress ( ) . toString ( ) ) ; if ( clientObservees == null ) { clientObservees = new HashMap < String , ObservingRelationship > ( ) ; observersByClient . put ( request . getPeerAddress ( ) . toString ( ) , clientObservees ) ; } resourceObservers . put ( request . getPeerAddress ( ) . toString ( ) , toAdd ) ; clientObservees . put ( resource . getPath ( ) , toAdd ) ; LOG . info ( String . format ( "<STR_LIT>" , request . getPeerAddress ( ) . toString ( ) , resource . getPath ( ) ) ) ; prepareResponse ( request ) ; } } public synchronized void removeObserver ( String clientID ) { Map < String , ObservingRelationship > clientObservees = observersByClient . get ( clientID ) ; if ( clientObservees != null ) { synchronized ( this ) { for ( Map < String , ObservingRelationship > entry : observersByResource . values ( ) ) { entry . remove ( clientID ) ; } observersByClient . remove ( clientID ) ; } LOG . info ( String . format ( "<STR_LIT>" , clientID ) ) ; } } public synchronized void removeObserver ( String clientID , LocalResource resource ) { Map < String , ObservingRelationship > resourceObservers = observersByResource . get ( resource . getPath ( ) ) ; Map < String , ObservingRelationship > clientObservees = observersByClient . get ( clientID ) ; if ( resourceObservers != null && clientObservees != null ) { synchronized ( this ) { if ( resourceObservers . remove ( clientID ) != null && clientObservees . remove ( resource . getPath ( ) ) != null ) { LOG . info ( String . format ( "<STR_LIT>" , clientID , resource . getPath ( ) ) ) ; return ; } } } LOG . warning ( String . format ( "<STR_LIT>" , clientID , resource . getPath ( ) ) ) ; } public void removeObserver ( String clientID , int mid ) { ObservingRelationship toRemove = null ; Map < String , ObservingRelationship > clientObservees = observersByClient . get ( clientID ) ; if ( clientObservees != null ) { for ( ObservingRelationship entry : clientObservees . values ( ) ) { if ( mid == entry . lastMID && clientID . equals ( entry . clientID ) ) { toRemove = entry ; break ; } } } if ( toRemove != null ) { synchronized ( this ) { Map < String , ObservingRelationship > resourceObservers = observersByResource . get ( toRemove . resourcePath ) ; if ( resourceObservers == null ) { LOG . severe ( String . format ( "<STR_LIT>" , clientID , toRemove . resourcePath ) ) ; } if ( resourceObservers . remove ( clientID ) != null && clientObservees . remove ( toRemove . resourcePath ) != null ) { LOG . info ( String . format ( "<STR_LIT>" , clientID , toRemove . resourcePath ) ) ; return ; } } } LOG . warning ( String . format ( "<STR_LIT>" , clientID , mid ) ) ; } public boolean isObserved ( String clientID , LocalResource resource ) { return observersByClient . containsKey ( clientID ) && observersByClient . get ( clientID ) . containsKey ( resource . getPath ( ) ) ; } public void updateLastMID ( String clientID , String path , int mid ) { Map < String , ObservingRelationship > clientObservees = observersByClient . get ( clientID ) ; if ( clientObservees != null ) { ObservingRelationship toUpdate = clientObservees . get ( path ) ; if ( toUpdate != null ) { toUpdate . lastMID = mid ; LOG . finer ( String . format ( "<STR_LIT>" , clientID , toUpdate . resourcePath ) ) ; return ; } } LOG . warning ( String . format ( "<STR_LIT>" , clientID , path ) ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; import java . util . ArrayList ; import java . util . List ; import java . util . Scanner ; import java . util . Set ; import java . util . logging . Logger ; import java . util . regex . Pattern ; import ch . ethz . inf . vs . californium . endpoint . RemoteResource ; import ch . ethz . inf . vs . californium . endpoint . Resource ; public class LinkFormat { protected static final Logger LOG = Logger . getLogger ( LinkFormat . class . getName ( ) ) ; public static final String RESOURCE_TYPE = "<STR_LIT>" ; public static final String INTERFACE_DESCRIPTION = "<STR_LIT>" ; public static final String CONTENT_TYPE = "<STR_LIT>" ; public static final String MAX_SIZE_ESTIMATE = "<STR_LIT>" ; public static final String TITLE = "<STR_LIT:title>" ; public static final String OBSERVABLE = "<STR_LIT>" ; public static final Pattern DELIMITER = Pattern . compile ( "<STR_LIT>" ) ; public static String serialize ( Resource resource , List < Option > query , boolean recursive ) { StringBuilder linkFormat = new StringBuilder ( ) ; if ( ( ! resource . isHidden ( ) && ( ! resource . getName ( ) . equals ( "<STR_LIT>" ) ) || ! recursive ) && matches ( resource , query ) ) { LOG . finer ( "<STR_LIT>" + resource . getPath ( ) ) ; linkFormat . append ( "<STR_LIT:<>" ) ; linkFormat . append ( resource . getPath ( ) ) ; linkFormat . append ( "<STR_LIT:>>" ) ; for ( LinkAttribute attrib : resource . getAttributes ( ) ) { linkFormat . append ( '<CHAR_LIT:;>' ) ; linkFormat . append ( attrib . serialize ( ) ) ; } } if ( recursive ) { for ( Resource sub : resource . getSubResources ( ) ) { String next = LinkFormat . serialize ( sub , query , true ) ; if ( ! next . equals ( "<STR_LIT>" ) ) { if ( linkFormat . length ( ) > <NUM_LIT:3> ) linkFormat . append ( '<CHAR_LIT:U+002C>' ) ; linkFormat . append ( next ) ; } } } return linkFormat . toString ( ) ; } public static RemoteResource parse ( String linkFormat ) { Scanner scanner = new Scanner ( linkFormat ) ; RemoteResource root = new RemoteResource ( "<STR_LIT>" ) ; String path = null ; while ( ( path = scanner . findInLine ( "<STR_LIT>" ) ) != null ) { path = path . substring ( <NUM_LIT:1> , path . length ( ) - <NUM_LIT:1> ) ; LOG . finer ( String . format ( "<STR_LIT>" , path ) ) ; RemoteResource resource = new RemoteResource ( path ) ; LinkAttribute attr = null ; while ( scanner . findWithinHorizon ( LinkFormat . DELIMITER , <NUM_LIT:1> ) == null && ( attr = LinkAttribute . parse ( scanner ) ) != null ) { addAttribute ( resource . getAttributes ( ) , attr ) ; } root . add ( resource ) ; } return root ; } public static boolean isSingle ( String name ) { return name . matches ( String . format ( "<STR_LIT>" , TITLE , MAX_SIZE_ESTIMATE , OBSERVABLE ) ) ; } public static boolean addAttribute ( Set < LinkAttribute > attributes , LinkAttribute add ) { if ( isSingle ( add . getName ( ) ) ) { for ( LinkAttribute attrib : attributes ) { if ( attrib . getName ( ) . equals ( add . getName ( ) ) ) { LOG . finest ( String . format ( "<STR_LIT>" , attrib . getName ( ) ) ) ; return false ; } } } if ( add . getName ( ) . equals ( "<STR_LIT>" ) && add . getIntValue ( ) < <NUM_LIT:0> ) return false ; if ( add . getName ( ) . equals ( "<STR_LIT>" ) && add . getIntValue ( ) < <NUM_LIT:0> ) return false ; LOG . finest ( String . format ( "<STR_LIT>" , add . getName ( ) , add . getValue ( ) ) ) ; return attributes . add ( add ) ; } public static List < String > getStringValues ( List < LinkAttribute > attributes ) { List < String > values = new ArrayList < String > ( ) ; for ( LinkAttribute attrib : attributes ) { values . add ( attrib . getStringValue ( ) ) ; } return values ; } public static List < Integer > getIntValues ( List < LinkAttribute > attributes ) { List < Integer > values = new ArrayList < Integer > ( ) ; for ( LinkAttribute attrib : attributes ) { values . add ( attrib . getIntValue ( ) ) ; } return values ; } public static boolean matches ( Resource resource , List < Option > query ) { if ( resource == null ) return false ; if ( query == null || query . size ( ) == <NUM_LIT:0> ) return true ; for ( Option q : query ) { String s = q . getStringValue ( ) ; int delim = s . indexOf ( "<STR_LIT:=>" ) ; if ( delim != - <NUM_LIT:1> ) { String attrName = s . substring ( <NUM_LIT:0> , delim ) ; String expected = s . substring ( delim + <NUM_LIT:1> ) ; for ( LinkAttribute attrib : resource . getAttributes ( attrName ) ) { String actual = attrib . getValue ( ) . toString ( ) ; int prefixLength = expected . indexOf ( '<CHAR_LIT>' ) ; if ( prefixLength >= <NUM_LIT:0> && prefixLength < actual . length ( ) ) { expected = expected . substring ( <NUM_LIT:0> , prefixLength ) ; actual = actual . substring ( <NUM_LIT:0> , prefixLength ) ; } if ( expected . equals ( actual ) ) { return true ; } } } else { if ( resource . getAttributes ( s ) . size ( ) > <NUM_LIT:0> ) { return true ; } } } return false ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public class CodeRegistry { public static final int EMPTY_MESSAGE = <NUM_LIT:0> ; public static final int METHOD_GET = <NUM_LIT:1> ; public static final int METHOD_POST = <NUM_LIT:2> ; public static final int METHOD_PUT = <NUM_LIT:3> ; public static final int METHOD_DELETE = <NUM_LIT:4> ; public static final int CLASS_SUCCESS = <NUM_LIT:2> ; public static final int CLASS_CLIENT_ERROR = <NUM_LIT:4> ; public static final int CLASS_SERVER_ERROR = <NUM_LIT:5> ; public static final int RESP_CREATED = <NUM_LIT> ; public static final int RESP_DELETED = <NUM_LIT> ; public static final int RESP_VALID = <NUM_LIT> ; public static final int RESP_CHANGED = <NUM_LIT> ; public static final int RESP_CONTENT = <NUM_LIT> ; public static final int RESP_BAD_REQUEST = <NUM_LIT> ; public static final int RESP_UNAUTHORIZED = <NUM_LIT> ; public static final int RESP_BAD_OPTION = <NUM_LIT> ; public static final int RESP_FORBIDDEN = <NUM_LIT> ; public static final int RESP_NOT_FOUND = <NUM_LIT> ; public static final int RESP_METHOD_NOT_ALLOWED = <NUM_LIT> ; public static final int RESP_NOT_ACCEPTABLE = <NUM_LIT> ; public static final int RESP_PRECONDITION_FAILED = <NUM_LIT> ; public static final int RESP_REQUEST_ENTITY_TOO_LARGE = <NUM_LIT> ; public static final int RESP_UNSUPPORTED_MEDIA_TYPE = <NUM_LIT> ; public static final int RESP_INTERNAL_SERVER_ERROR = <NUM_LIT> ; public static final int RESP_NOT_IMPLEMENTED = <NUM_LIT> ; public static final int RESP_BAD_GATEWAY = <NUM_LIT> ; public static final int RESP_SERVICE_UNAVAILABLE = <NUM_LIT> ; public static final int RESP_GATEWAY_TIMEOUT = <NUM_LIT> ; public static final int RESP_PROXYING_NOT_SUPPORTED = <NUM_LIT> ; public static final int RESP_REQUEST_ENTITY_INCOMPLETE = <NUM_LIT> ; public static boolean isRequest ( int code ) { return ( code >= <NUM_LIT:1> ) && ( code <= <NUM_LIT:31> ) ; } public static boolean isResponse ( int code ) { return ( code >= <NUM_LIT> ) && ( code <= <NUM_LIT> ) ; } public static boolean isValid ( int code ) { return ( code >= <NUM_LIT:0> ) && ( code <= <NUM_LIT:255> ) ; } public static int responseClass ( int code ) { return ( code > > <NUM_LIT:5> ) & <NUM_LIT> ; } public static Message getMessageSubClass ( int code ) { if ( isRequest ( code ) ) { switch ( code ) { case METHOD_GET : return new GETRequest ( ) ; case METHOD_POST : return new POSTRequest ( ) ; case METHOD_PUT : return new PUTRequest ( ) ; case METHOD_DELETE : return new DELETERequest ( ) ; default : return new UnsupportedRequest ( code ) ; } } else if ( isResponse ( code ) || code == EMPTY_MESSAGE ) { return new Response ( code ) ; } else { return new Message ( null , code ) ; } } public static String toString ( int code ) { switch ( code ) { case EMPTY_MESSAGE : return "<STR_LIT>" ; case METHOD_GET : return "<STR_LIT:GET>" ; case METHOD_POST : return "<STR_LIT:POST>" ; case METHOD_PUT : return "<STR_LIT>" ; case METHOD_DELETE : return "<STR_LIT>" ; case RESP_CREATED : return "<STR_LIT>" ; case RESP_DELETED : return "<STR_LIT>" ; case RESP_VALID : return "<STR_LIT>" ; case RESP_CHANGED : return "<STR_LIT>" ; case RESP_CONTENT : return "<STR_LIT>" ; case RESP_BAD_REQUEST : return "<STR_LIT>" ; case RESP_UNAUTHORIZED : return "<STR_LIT>" ; case RESP_BAD_OPTION : return "<STR_LIT>" ; case RESP_FORBIDDEN : return "<STR_LIT>" ; case RESP_NOT_FOUND : return "<STR_LIT>" ; case RESP_METHOD_NOT_ALLOWED : return "<STR_LIT>" ; case RESP_NOT_ACCEPTABLE : return "<STR_LIT>" ; case RESP_REQUEST_ENTITY_INCOMPLETE : return "<STR_LIT>" ; case RESP_PRECONDITION_FAILED : return "<STR_LIT>" ; case RESP_REQUEST_ENTITY_TOO_LARGE : return "<STR_LIT>" ; case RESP_UNSUPPORTED_MEDIA_TYPE : return "<STR_LIT>" ; case RESP_INTERNAL_SERVER_ERROR : return "<STR_LIT>" ; case RESP_NOT_IMPLEMENTED : return "<STR_LIT>" ; case RESP_BAD_GATEWAY : return "<STR_LIT>" ; case RESP_SERVICE_UNAVAILABLE : return "<STR_LIT>" ; case RESP_GATEWAY_TIMEOUT : return "<STR_LIT>" ; case RESP_PROXYING_NOT_SUPPORTED : return "<STR_LIT>" ; } if ( isValid ( code ) ) { if ( isRequest ( code ) ) { return String . format ( "<STR_LIT>" , code ) ; } else if ( isResponse ( code ) ) { return String . format ( "<STR_LIT>" , code ) ; } else { return String . format ( "<STR_LIT>" , code ) ; } } else { return String . format ( "<STR_LIT>" , code ) ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; import java . io . IOException ; import java . net . SocketException ; import ch . ethz . inf . vs . californium . layers . AdverseLayer ; import ch . ethz . inf . vs . californium . layers . TokenLayer ; import ch . ethz . inf . vs . californium . layers . TransactionLayer ; import ch . ethz . inf . vs . californium . layers . MatchingLayer ; import ch . ethz . inf . vs . californium . layers . TransferLayer ; import ch . ethz . inf . vs . californium . layers . UDPLayer ; import ch . ethz . inf . vs . californium . layers . UpperLayer ; public class Communicator extends UpperLayer { private volatile static Communicator singleton = null ; private static int udpPort = <NUM_LIT:0> ; private static boolean runAsDaemon = true ; private static int transferBlockSize = <NUM_LIT:0> ; protected TokenLayer tokenLayer ; protected TransferLayer transferLayer ; protected MatchingLayer matchingLayer ; protected TransactionLayer transactionLayer ; protected AdverseLayer adverseLayer ; protected UDPLayer udpLayer ; private Communicator ( ) throws SocketException { tokenLayer = new TokenLayer ( ) ; transferLayer = new TransferLayer ( transferBlockSize ) ; matchingLayer = new MatchingLayer ( ) ; transactionLayer = new TransactionLayer ( ) ; adverseLayer = new AdverseLayer ( ) ; udpLayer = new UDPLayer ( udpPort , runAsDaemon ) ; buildStack ( ) ; } public static Communicator getInstance ( ) { if ( singleton == null ) { synchronized ( Communicator . class ) { if ( singleton == null ) { try { singleton = new Communicator ( ) ; } catch ( SocketException e ) { LOG . severe ( String . format ( "<STR_LIT>" , e . getMessage ( ) ) ) ; System . exit ( - <NUM_LIT:1> ) ; } } } } return singleton ; } public static void setupPort ( int port ) { if ( port != udpPort && singleton == null ) { synchronized ( Communicator . class ) { if ( singleton == null ) { udpPort = port ; LOG . config ( String . format ( "<STR_LIT>" , udpPort ) ) ; } else { LOG . severe ( "<STR_LIT>" ) ; } } } } public static void setupTransfer ( int defaultBlockSize ) { if ( defaultBlockSize != transferBlockSize && singleton == null ) { synchronized ( Communicator . class ) { if ( singleton == null ) { transferBlockSize = defaultBlockSize ; LOG . config ( String . format ( "<STR_LIT>" , transferBlockSize ) ) ; } else { LOG . severe ( "<STR_LIT>" ) ; } } } } public static void setupDeamon ( boolean daemon ) { if ( daemon != runAsDaemon && singleton == null ) { synchronized ( Communicator . class ) { if ( singleton == null ) { runAsDaemon = daemon ; LOG . config ( String . format ( "<STR_LIT>" , runAsDaemon ) ) ; } else { LOG . severe ( "<STR_LIT>" ) ; } } } } private void buildStack ( ) { this . setLowerLayer ( tokenLayer ) ; tokenLayer . setLowerLayer ( transferLayer ) ; transferLayer . setLowerLayer ( matchingLayer ) ; matchingLayer . setLowerLayer ( transactionLayer ) ; transactionLayer . setLowerLayer ( udpLayer ) ; } @ Override protected void doSendMessage ( Message msg ) throws IOException { if ( msg != null ) { if ( msg . getPeerAddress ( ) . getAddress ( ) == null ) { throw new IOException ( "<STR_LIT>" ) ; } sendMessageOverLowerLayer ( msg ) ; } } @ Override protected void doReceiveMessage ( Message msg ) { if ( msg instanceof Response ) { Response response = ( Response ) msg ; if ( response . getRequest ( ) != null ) { response . getRequest ( ) . handleResponse ( response ) ; } } deliverMessage ( msg ) ; } public int port ( ) { return udpLayer . getPort ( ) ; } public TokenLayer getTokenLayer ( ) { return this . tokenLayer ; } public TransferLayer getTransferLayer ( ) { return this . transferLayer ; } public MatchingLayer getMatchingLayer ( ) { return this . matchingLayer ; } public TransactionLayer getTransactionLayer ( ) { return this . transactionLayer ; } public UDPLayer getUDPLayer ( ) { return this . udpLayer ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public class GETRequest extends Request { public GETRequest ( ) { super ( CodeRegistry . METHOD_GET , true ) ; } @ Override public void dispatch ( RequestHandler handler ) { handler . performGET ( this ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public class OptionNumberRegistry { public static final int RESERVED_0 = <NUM_LIT:0> ; public static final int CONTENT_TYPE = <NUM_LIT:1> ; public static final int MAX_AGE = <NUM_LIT:2> ; public static final int PROXY_URI = <NUM_LIT:3> ; public static final int ETAG = <NUM_LIT:4> ; public static final int URI_HOST = <NUM_LIT:5> ; public static final int LOCATION_PATH = <NUM_LIT:6> ; public static final int URI_PORT = <NUM_LIT:7> ; public static final int LOCATION_QUERY = <NUM_LIT:8> ; public static final int URI_PATH = <NUM_LIT:9> ; public static final int OBSERVE = <NUM_LIT:10> ; public static final int TOKEN = <NUM_LIT:11> ; public static final int ACCEPT = <NUM_LIT:12> ; public static final int IF_MATCH = <NUM_LIT> ; public static final int URI_QUERY = <NUM_LIT:15> ; public static final int BLOCK2 = <NUM_LIT> ; public static final int BLOCK1 = <NUM_LIT> ; public static final int IF_NONE_MATCH = <NUM_LIT> ; public static final int FENCEPOST_DIVISOR = <NUM_LIT> ; public static final int TOKEN_LEN = <NUM_LIT:8> ; public static enum optionFormats { INTEGER , STRING , OPAQUE , UNKNOWN , ERROR } public static boolean isElective ( int optionNumber ) { return ( optionNumber & <NUM_LIT:1> ) == <NUM_LIT:0> ; } public static boolean isCritical ( int optionNumber ) { return ( optionNumber & <NUM_LIT:1> ) == <NUM_LIT:1> ; } public static boolean isFencepost ( int optionNumber ) { return optionNumber % FENCEPOST_DIVISOR == <NUM_LIT:0> ; } public static int nextFencepost ( int optionNumber ) { return ( optionNumber / FENCEPOST_DIVISOR + <NUM_LIT:1> ) * FENCEPOST_DIVISOR ; } public static String toString ( int optionNumber ) { switch ( optionNumber ) { case RESERVED_0 : return "<STR_LIT>" ; case CONTENT_TYPE : return "<STR_LIT:Content-Type>" ; case MAX_AGE : return "<STR_LIT>" ; case PROXY_URI : return "<STR_LIT>" ; case ETAG : return "<STR_LIT>" ; case URI_HOST : return "<STR_LIT>" ; case LOCATION_PATH : return "<STR_LIT>" ; case URI_PORT : return "<STR_LIT>" ; case LOCATION_QUERY : return "<STR_LIT>" ; case URI_PATH : return "<STR_LIT>" ; case OBSERVE : return "<STR_LIT>" ; case TOKEN : return "<STR_LIT>" ; case ACCEPT : return "<STR_LIT>" ; case IF_MATCH : return "<STR_LIT>" ; case URI_QUERY : return "<STR_LIT>" ; case BLOCK2 : return "<STR_LIT>" ; case BLOCK1 : return "<STR_LIT>" ; case IF_NONE_MATCH : return "<STR_LIT>" ; } return String . format ( "<STR_LIT>" , optionNumber ) ; } public static optionFormats getFormatByNr ( int optionNumber ) { switch ( optionNumber ) { case RESERVED_0 : return optionFormats . UNKNOWN ; case CONTENT_TYPE : return optionFormats . INTEGER ; case PROXY_URI : return optionFormats . STRING ; case ETAG : return optionFormats . OPAQUE ; case URI_HOST : return optionFormats . STRING ; case LOCATION_PATH : return optionFormats . STRING ; case URI_PORT : return optionFormats . INTEGER ; case LOCATION_QUERY : return optionFormats . STRING ; case URI_PATH : return optionFormats . STRING ; case TOKEN : return optionFormats . OPAQUE ; case URI_QUERY : return optionFormats . STRING ; default : return optionFormats . ERROR ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; import java . io . IOException ; import java . io . PrintStream ; import java . io . UnsupportedEncodingException ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import java . util . logging . Logger ; import ch . ethz . inf . vs . californium . layers . UpperLayer ; import ch . ethz . inf . vs . californium . util . DatagramReader ; import ch . ethz . inf . vs . californium . util . DatagramWriter ; public class Message { protected static final Logger LOG = Logger . getLogger ( Message . class . getName ( ) ) ; public static final int VERSION_BITS = <NUM_LIT:2> ; public static final int TYPE_BITS = <NUM_LIT:2> ; public static final int OPTIONCOUNT_BITS = <NUM_LIT:4> ; public static final int CODE_BITS = <NUM_LIT:8> ; public static final int ID_BITS = <NUM_LIT:16> ; public static final int OPTIONDELTA_BITS = <NUM_LIT:4> ; public static final int OPTIONLENGTH_BASE_BITS = <NUM_LIT:4> ; public static final int OPTIONLENGTH_EXTENDED_BITS = <NUM_LIT:8> ; public enum messageType { CON , NON , ACK , RST } public static final int SUPPORTED_VERSION = <NUM_LIT:1> ; public static final int MAX_OPTIONDELTA = ( <NUM_LIT:1> << OPTIONDELTA_BITS ) - <NUM_LIT:1> ; public static final int MAX_OPTIONLENGTH_BASE = ( <NUM_LIT:1> << OPTIONLENGTH_BASE_BITS ) - <NUM_LIT:2> ; private EndpointAddress peerAddress = null ; private byte [ ] payload = null ; private int version = SUPPORTED_VERSION ; private messageType type = null ; private int code = <NUM_LIT:0> ; private int messageID = - <NUM_LIT:1> ; private Map < Integer , List < Option > > optionMap = new TreeMap < Integer , List < Option > > ( ) ; private long timestamp = - <NUM_LIT:1> ; private int retransmissioned = <NUM_LIT:0> ; protected boolean requiresToken = true ; protected boolean requiresBlockwise = false ; public static messageType getTypeByValue ( int numeric ) { switch ( numeric ) { case <NUM_LIT:0> : return messageType . CON ; case <NUM_LIT:1> : return messageType . NON ; case <NUM_LIT:2> : return messageType . ACK ; case <NUM_LIT:3> : return messageType . RST ; default : return messageType . CON ; } } public Message ( ) { } public Message ( messageType type , int code ) { this . type = type ; this . code = code ; } public byte [ ] toByteArray ( ) { DatagramWriter optWriter = new DatagramWriter ( ) ; int optionCount = <NUM_LIT:0> ; int lastOptionNumber = <NUM_LIT:0> ; for ( Option opt : getOptions ( ) ) { if ( opt . isDefaultValue ( ) ) continue ; int optionDelta = opt . getOptionNumber ( ) - lastOptionNumber ; while ( optionDelta > MAX_OPTIONDELTA ) { int fencepostNumber = OptionNumberRegistry . nextFencepost ( lastOptionNumber ) ; int fencepostDelta = fencepostNumber - lastOptionNumber ; if ( fencepostDelta <= <NUM_LIT:0> ) { LOG . warning ( String . format ( "<STR_LIT>" , fencepostDelta ) ) ; } if ( fencepostDelta > MAX_OPTIONDELTA ) { LOG . warning ( String . format ( "<STR_LIT>" , fencepostDelta ) ) ; } optWriter . write ( fencepostDelta , OPTIONDELTA_BITS ) ; optWriter . write ( <NUM_LIT:0> , OPTIONLENGTH_BASE_BITS ) ; ++ optionCount ; lastOptionNumber = fencepostNumber ; optionDelta -= fencepostDelta ; } optWriter . write ( optionDelta , OPTIONDELTA_BITS ) ; int length = opt . getLength ( ) ; if ( length <= MAX_OPTIONLENGTH_BASE ) { optWriter . write ( length , OPTIONLENGTH_BASE_BITS ) ; } else { int baseLength = MAX_OPTIONLENGTH_BASE + <NUM_LIT:1> ; optWriter . write ( baseLength , OPTIONLENGTH_BASE_BITS ) ; int extLength = length - baseLength ; optWriter . write ( extLength , OPTIONLENGTH_EXTENDED_BITS ) ; } optWriter . writeBytes ( opt . getRawValue ( ) ) ; ++ optionCount ; lastOptionNumber = opt . getOptionNumber ( ) ; } DatagramWriter writer = new DatagramWriter ( ) ; writer . write ( version , VERSION_BITS ) ; writer . write ( type . ordinal ( ) , TYPE_BITS ) ; writer . write ( optionCount , OPTIONCOUNT_BITS ) ; writer . write ( code , CODE_BITS ) ; writer . write ( messageID , ID_BITS ) ; writer . writeBytes ( optWriter . toByteArray ( ) ) ; writer . writeBytes ( payload ) ; return writer . toByteArray ( ) ; } public static Message fromByteArray ( byte [ ] byteArray ) { DatagramReader datagram = new DatagramReader ( byteArray ) ; int version = datagram . read ( VERSION_BITS ) ; if ( version != SUPPORTED_VERSION ) { return null ; } messageType type = getTypeByValue ( datagram . read ( TYPE_BITS ) ) ; int optionCount = datagram . read ( OPTIONCOUNT_BITS ) ; Message msg = CodeRegistry . getMessageSubClass ( datagram . read ( CODE_BITS ) ) ; msg . type = type ; msg . messageID = datagram . read ( ID_BITS ) ; int currentOption = <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < optionCount ; i ++ ) { int optionDelta = datagram . read ( OPTIONDELTA_BITS ) ; currentOption += optionDelta ; if ( OptionNumberRegistry . isFencepost ( currentOption ) ) { datagram . read ( OPTIONLENGTH_BASE_BITS ) ; } else { int length = datagram . read ( OPTIONLENGTH_BASE_BITS ) ; if ( length > MAX_OPTIONLENGTH_BASE ) { length += datagram . read ( OPTIONLENGTH_EXTENDED_BITS ) ; } Option opt = Option . fromNumber ( currentOption ) ; opt . setValue ( datagram . readBytes ( length ) ) ; msg . addOption ( opt ) ; } } msg . payload = datagram . readBytesLeft ( ) ; msg . requiresToken = false ; return msg ; } public void send ( ) { try { Communicator . getInstance ( ) . sendMessage ( this ) ; } catch ( IOException e ) { LOG . severe ( String . format ( "<STR_LIT>" , key ( ) , e . getMessage ( ) ) ) ; } } public void accept ( ) { if ( isConfirmable ( ) ) { Message ack = newAccept ( ) ; ack . send ( ) ; } } public Message newAccept ( ) { Message ack = new Message ( messageType . ACK , CodeRegistry . EMPTY_MESSAGE ) ; ack . setPeerAddress ( getPeerAddress ( ) ) ; ack . setMID ( getMID ( ) ) ; return ack ; } public void reject ( ) { Message rst = newReject ( ) ; rst . send ( ) ; } public Message newReject ( ) { Message rst = new Message ( messageType . RST , CodeRegistry . EMPTY_MESSAGE ) ; rst . setPeerAddress ( getPeerAddress ( ) ) ; rst . setMID ( getMID ( ) ) ; return rst ; } public Message newReply ( boolean ack ) { Message reply = new Message ( ) ; if ( type == messageType . CON ) { reply . type = ack ? messageType . ACK : messageType . RST ; } else { reply . type = messageType . NON ; } reply . messageID = this . messageID ; reply . peerAddress = this . peerAddress ; reply . setOption ( getFirstOption ( OptionNumberRegistry . TOKEN ) ) ; reply . requiresToken = requiresToken ; reply . code = CodeRegistry . EMPTY_MESSAGE ; return reply ; } public void handleBy ( MessageHandler handler ) { } public int getVersion ( ) { return this . version ; } public int getCode ( ) { return this . code ; } public int getMID ( ) { return this . messageID ; } public void setMID ( int mid ) { this . messageID = mid ; } public EndpointAddress getPeerAddress ( ) { return this . peerAddress ; } public void setPeerAddress ( EndpointAddress a ) { this . peerAddress = a ; } public boolean setURI ( String uri ) { try { setURI ( new URI ( uri ) ) ; return true ; } catch ( URISyntaxException e ) { LOG . warning ( String . format ( "<STR_LIT>" , e . getMessage ( ) ) ) ; return false ; } } public void setURI ( URI uri ) { if ( this instanceof Request ) { String path = uri . getPath ( ) ; if ( path != null && path . length ( ) > <NUM_LIT:1> ) { List < Option > uriPath = Option . split ( OptionNumberRegistry . URI_PATH , path , "<STR_LIT:/>" ) ; setOptions ( uriPath ) ; } String query = uri . getQuery ( ) ; if ( query != null ) { List < Option > uriQuery = Option . split ( OptionNumberRegistry . URI_QUERY , query , "<STR_LIT:&>" ) ; setOptions ( uriQuery ) ; } } this . setPeerAddress ( new EndpointAddress ( uri ) ) ; } public String getUriPath ( ) { return Option . join ( getOptions ( OptionNumberRegistry . URI_PATH ) , "<STR_LIT:/>" ) ; } public String getQuery ( ) { return Option . join ( getOptions ( OptionNumberRegistry . URI_QUERY ) , "<STR_LIT:&>" ) ; } public int getContentType ( ) { Option opt = getFirstOption ( OptionNumberRegistry . CONTENT_TYPE ) ; return opt != null ? opt . getIntValue ( ) : MediaTypeRegistry . UNDEFINED ; } public void setContentType ( int ct ) { if ( ct != MediaTypeRegistry . UNDEFINED ) { setOption ( new Option ( ct , OptionNumberRegistry . CONTENT_TYPE ) ) ; } else { removeOptions ( OptionNumberRegistry . CONTENT_TYPE ) ; } } public int getFirstAccept ( ) { Option opt = getFirstOption ( OptionNumberRegistry . ACCEPT ) ; return opt != null ? opt . getIntValue ( ) : MediaTypeRegistry . UNDEFINED ; } public void setAccept ( int ct ) { if ( ct != MediaTypeRegistry . UNDEFINED ) { addOption ( new Option ( ct , OptionNumberRegistry . ACCEPT ) ) ; } else { removeOptions ( OptionNumberRegistry . ACCEPT ) ; } } public byte [ ] getToken ( ) { Option opt = getFirstOption ( OptionNumberRegistry . TOKEN ) ; return opt != null ? opt . getRawValue ( ) : TokenManager . emptyToken ; } public String getTokenString ( ) { return Option . hex ( getToken ( ) ) ; } public void setToken ( byte [ ] token ) { setOption ( new Option ( token , OptionNumberRegistry . TOKEN ) ) ; } public int getMaxAge ( ) { Option opt = getFirstOption ( OptionNumberRegistry . MAX_AGE ) ; return opt != null ? opt . getIntValue ( ) : Option . DEFAULT_MAX_AGE ; } public void setMaxAge ( int timeInSec ) { setOption ( new Option ( timeInSec , OptionNumberRegistry . MAX_AGE ) ) ; } public String getLocationPath ( ) { return Option . join ( getOptions ( OptionNumberRegistry . LOCATION_PATH ) , "<STR_LIT:/>" ) ; } public void setLocationPath ( String locationPath ) { setOptions ( Option . split ( OptionNumberRegistry . LOCATION_PATH , locationPath , "<STR_LIT:/>" ) ) ; } public byte [ ] getPayload ( ) { return this . payload ; } public String getPayloadString ( ) { try { return payload != null ? new String ( payload , "<STR_LIT:UTF-8>" ) : null ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; return null ; } } public void setPayload ( byte [ ] payload ) { this . payload = payload ; } public synchronized void appendPayload ( byte [ ] block ) { if ( block != null ) { if ( payload != null ) { byte [ ] oldPayload = payload ; payload = new byte [ oldPayload . length + block . length ] ; System . arraycopy ( oldPayload , <NUM_LIT:0> , payload , <NUM_LIT:0> , oldPayload . length ) ; System . arraycopy ( block , <NUM_LIT:0> , payload , oldPayload . length , block . length ) ; } else { payload = block . clone ( ) ; } notifyAll ( ) ; payloadAppended ( block ) ; } } public void setPayload ( String payload ) { setPayload ( payload , MediaTypeRegistry . UNDEFINED ) ; } public void setPayload ( String payload , int mediaType ) { if ( payload != null ) { try { setPayload ( payload . getBytes ( "<STR_LIT:UTF-8>" ) ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; return ; } if ( mediaType != MediaTypeRegistry . UNDEFINED ) { setOption ( new Option ( mediaType , OptionNumberRegistry . CONTENT_TYPE ) ) ; } } } public int payloadSize ( ) { return payload != null ? payload . length : <NUM_LIT:0> ; } public String key ( ) { return String . format ( "<STR_LIT>" , peerAddress != null ? peerAddress . toString ( ) : "<STR_LIT>" , messageID , typeString ( ) ) ; } public String transactionKey ( ) { return String . format ( "<STR_LIT>" , peerAddress != null ? peerAddress . toString ( ) : "<STR_LIT>" , messageID ) ; } public String sequenceKey ( ) { return String . format ( "<STR_LIT>" , peerAddress != null ? peerAddress . toString ( ) : "<STR_LIT>" , getTokenString ( ) ) ; } public messageType getType ( ) { return this . type ; } public void setType ( messageType msgType ) { this . type = msgType ; } public void setCode ( int code ) { this . code = code ; } public void addOption ( Option option ) { if ( option == null ) throw new NullPointerException ( ) ; int optionNumber = option . getOptionNumber ( ) ; List < Option > list = optionMap . get ( optionNumber ) ; if ( list == null ) { list = new ArrayList < Option > ( ) ; optionMap . put ( optionNumber , list ) ; } list . add ( option ) ; if ( optionNumber == OptionNumberRegistry . TOKEN ) { requiresToken = false ; } } public void removeOptions ( int optionNumber ) { optionMap . remove ( optionNumber ) ; } public List < Option > getOptions ( int optionNumber ) { List < Option > ret = optionMap . get ( optionNumber ) ; if ( ret != null ) { return ret ; } else { return Collections . emptyList ( ) ; } } public void setOption ( Option option ) { if ( option != null ) { removeOptions ( option . getOptionNumber ( ) ) ; addOption ( option ) ; } } public void setOptions ( List < Option > options ) { for ( Option option : options ) { removeOptions ( option . getOptionNumber ( ) ) ; } addOptions ( options ) ; } public void addOptions ( List < Option > options ) { for ( Option option : options ) { addOption ( option ) ; } } public Option getFirstOption ( int optionNumber ) { List < Option > list = getOptions ( optionNumber ) ; return list != null && ! list . isEmpty ( ) ? list . get ( <NUM_LIT:0> ) : null ; } public List < Option > getOptions ( ) { List < Option > list = new ArrayList < Option > ( ) ; for ( List < Option > option : optionMap . values ( ) ) { list . addAll ( option ) ; } return list ; } public int getOptionCount ( ) { return getOptions ( ) . size ( ) ; } public long getTimestamp ( ) { return this . timestamp ; } public void setTimestamp ( long timestamp ) { this . timestamp = timestamp ; } public int getRetransmissioned ( ) { return retransmissioned ; } public void setRetransmissioned ( int retransmissioned ) { this . retransmissioned = retransmissioned ; } public void handleTimeout ( ) { } protected void payloadAppended ( byte [ ] block ) { } public boolean isConfirmable ( ) { return this . type == messageType . CON ; } public boolean isNonConfirmable ( ) { return this . type == messageType . NON ; } public boolean isAcknowledgement ( ) { return this . type == messageType . ACK ; } public boolean isReset ( ) { return this . type == messageType . RST ; } public boolean isReply ( ) { return isAcknowledgement ( ) || isReset ( ) ; } public boolean isEmptyACK ( ) { return isAcknowledgement ( ) && getCode ( ) == CodeRegistry . EMPTY_MESSAGE ; } public boolean hasOption ( int optionNumber ) { return getFirstOption ( optionNumber ) != null ; } public boolean requiresToken ( ) { return requiresToken && this . getCode ( ) != CodeRegistry . EMPTY_MESSAGE ; } public void requiresToken ( boolean value ) { requiresToken = value ; } public boolean requiresBlockwise ( ) { return requiresBlockwise ; } public void requiresBlockwise ( boolean value ) { requiresBlockwise = value ; } @ Override public String toString ( ) { String typeStr = "<STR_LIT>" ; if ( type != null ) switch ( type ) { case CON : typeStr = "<STR_LIT>" ; break ; case NON : typeStr = "<STR_LIT>" ; break ; case ACK : typeStr = "<STR_LIT>" ; break ; case RST : typeStr = "<STR_LIT>" ; break ; default : typeStr = "<STR_LIT>" ; break ; } String payloadStr = payload != null ? new String ( payload ) : null ; return String . format ( "<STR_LIT>" , key ( ) , typeStr , CodeRegistry . toString ( code ) , payloadStr , payloadSize ( ) ) ; } public String typeString ( ) { if ( type != null ) switch ( type ) { case CON : return "<STR_LIT>" ; case NON : return "<STR_LIT>" ; case ACK : return "<STR_LIT>" ; case RST : return "<STR_LIT>" ; default : return "<STR_LIT>" ; } return null ; } public void prettyPrint ( ) { prettyPrint ( System . out ) ; } public void prettyPrint ( PrintStream out ) { String kind = "<STR_LIT>" ; if ( this instanceof Request ) { kind = "<STR_LIT>" ; } else if ( this instanceof Response ) { kind = "<STR_LIT>" ; } out . printf ( "<STR_LIT>" , kind ) ; List < Option > options = getOptions ( ) ; out . printf ( "<STR_LIT>" , peerAddress . toString ( ) ) ; out . printf ( "<STR_LIT>" , messageID ) ; out . printf ( "<STR_LIT>" , typeString ( ) ) ; out . printf ( "<STR_LIT>" , CodeRegistry . toString ( code ) ) ; out . printf ( "<STR_LIT>" , options . size ( ) ) ; for ( Option opt : options ) { out . printf ( "<STR_LIT>" , opt . getName ( ) , opt . toString ( ) , opt . getLength ( ) ) ; } out . printf ( "<STR_LIT>" , payloadSize ( ) ) ; if ( payloadSize ( ) > <NUM_LIT:0> && MediaTypeRegistry . isPrintable ( getContentType ( ) ) ) { out . println ( "<STR_LIT>" ) ; out . println ( getPayloadString ( ) ) ; } out . println ( "<STR_LIT>" ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; import java . util . Scanner ; import java . util . logging . Logger ; import java . util . regex . Pattern ; public class LinkAttribute implements Comparable < LinkAttribute > { protected static final Logger LOG = Logger . getLogger ( LinkFormat . class . getName ( ) ) ; public static final Pattern SEPARATOR = Pattern . compile ( "<STR_LIT>" ) ; public static final Pattern ATTRIBUTE_NAME = Pattern . compile ( "<STR_LIT>" ) ; public static final Pattern QUOTED_STRING = Pattern . compile ( "<STR_LIT>" ) ; public static final Pattern CARDINAL = Pattern . compile ( "<STR_LIT>" ) ; private String name ; private Object value ; public LinkAttribute ( ) { } public LinkAttribute ( String name , Object value ) { this . name = name ; this . value = value ; } public LinkAttribute ( String name , String value ) { this . name = name ; this . value = value ; } public LinkAttribute ( String name , int value ) { this . name = name ; this . value = Integer . valueOf ( value ) ; } public LinkAttribute ( String name ) { this . name = name ; this . value = Boolean . valueOf ( true ) ; } public static LinkAttribute parse ( String str ) { return parse ( new Scanner ( str ) ) ; } public static LinkAttribute parse ( Scanner scanner ) { String name = scanner . findInLine ( ATTRIBUTE_NAME ) ; if ( name != null ) { LOG . finest ( String . format ( "<STR_LIT>" , name ) ) ; LinkAttribute attr = new LinkAttribute ( ) ; attr . name = name ; if ( scanner . findWithinHorizon ( "<STR_LIT:=>" , <NUM_LIT:1> ) != null ) { String value = null ; if ( ( value = scanner . findInLine ( QUOTED_STRING ) ) != null ) { attr . value = value . substring ( <NUM_LIT:1> , value . length ( ) - <NUM_LIT:1> ) ; } else if ( ( value = scanner . findInLine ( CARDINAL ) ) != null ) { attr . value = Integer . parseInt ( value ) ; } else if ( scanner . hasNext ( ) ) { attr . value = scanner . next ( ) ; } else { attr . value = null ; } } else { attr . value = Boolean . valueOf ( true ) ; } return attr ; } return null ; } public String serialize ( ) { StringBuilder builder = new StringBuilder ( ) ; if ( name != null && value != null ) { LOG . finest ( String . format ( "<STR_LIT>" , name ) ) ; if ( value instanceof Boolean ) { if ( ( Boolean ) value ) { builder . append ( name ) ; } } else { builder . append ( name ) ; builder . append ( '<CHAR_LIT:=>' ) ; if ( value instanceof String ) { builder . append ( '<CHAR_LIT:">' ) ; builder . append ( ( String ) value ) ; builder . append ( '<CHAR_LIT:">' ) ; } else if ( value instanceof Integer ) { builder . append ( ( ( Integer ) value ) ) ; } else { LOG . severe ( String . format ( "<STR_LIT>" , name , value , value . getClass ( ) . getName ( ) ) ) ; } } } return builder . toString ( ) ; } public String getName ( ) { return name ; } public Object getValue ( ) { return value ; } @ Override public String toString ( ) { return serialize ( ) ; } public int getIntValue ( ) { if ( value instanceof Integer ) { return ( Integer ) value ; } return - <NUM_LIT:1> ; } public String getStringValue ( ) { if ( value instanceof String ) { return ( String ) value ; } return null ; } @ Override public int compareTo ( LinkAttribute o ) { int ret = this . name . compareTo ( o . getName ( ) ) ; if ( ret == <NUM_LIT:0> ) { if ( value instanceof String ) { return this . getStringValue ( ) . compareTo ( o . getStringValue ( ) ) ; } else if ( value instanceof Integer ) { return this . getIntValue ( ) - o . getIntValue ( ) ; } else { return <NUM_LIT:0> ; } } else { return ret ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public class UnsupportedRequest extends Request { public UnsupportedRequest ( int code ) { super ( code ) ; } @ Override public void send ( ) { LOG . severe ( "<STR_LIT>" ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; import java . io . UnsupportedEncodingException ; import java . nio . ByteBuffer ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; public class Option { public static final int DEFAULT_MAX_AGE = <NUM_LIT> ; private int optionNr ; private ByteBuffer value ; public Option ( int nr ) { setOptionNumber ( nr ) ; } public Option ( byte [ ] raw , int nr ) { setValue ( raw ) ; setOptionNumber ( nr ) ; } public Option ( String str , int nr ) { setStringValue ( str ) ; setOptionNumber ( nr ) ; } public Option ( int val , int nr ) { setIntValue ( val ) ; setOptionNumber ( nr ) ; } static Option fromNumber ( int nr ) { switch ( nr ) { case OptionNumberRegistry . BLOCK1 : case OptionNumberRegistry . BLOCK2 : return new BlockOption ( nr ) ; default : return new Option ( nr ) ; } } public static List < Option > split ( int optionNumber , String s , String delimiter ) { List < Option > options = new ArrayList < Option > ( ) ; if ( s != null ) { for ( String segment : s . split ( delimiter ) ) { if ( ! segment . isEmpty ( ) ) { options . add ( new Option ( segment , optionNumber ) ) ; } } } return options ; } public static String join ( List < Option > options , String delimiter ) { if ( options != null ) { StringBuilder builder = new StringBuilder ( ) ; for ( Option opt : options ) { builder . append ( delimiter ) ; builder . append ( opt . getStringValue ( ) ) ; } return builder . toString ( ) ; } else { return "<STR_LIT>" ; } } public int getOptionNumber ( ) { return optionNr ; } public void setOptionNumber ( int nr ) { optionNr = nr ; } public byte [ ] getRawValue ( ) { return value . array ( ) ; } public void setValue ( byte [ ] value ) { this . value = ByteBuffer . wrap ( value ) ; } public int getIntValue ( ) { int byteLength = value . capacity ( ) ; ByteBuffer temp = ByteBuffer . allocate ( <NUM_LIT:4> ) ; for ( int i = <NUM_LIT:0> ; i < ( <NUM_LIT:4> - byteLength ) ; i ++ ) { temp . put ( ( byte ) <NUM_LIT:0> ) ; } for ( int i = <NUM_LIT:0> ; i < byteLength ; i ++ ) { temp . put ( value . get ( i ) ) ; } int val = temp . getInt ( <NUM_LIT:0> ) ; return val ; } public void setIntValue ( int val ) { int neededBytes = <NUM_LIT:4> ; if ( val == <NUM_LIT:0> ) { value = ByteBuffer . allocate ( <NUM_LIT:1> ) ; value . put ( ( byte ) <NUM_LIT:0> ) ; } else { ByteBuffer aux = ByteBuffer . allocate ( <NUM_LIT:4> ) ; aux . putInt ( val ) ; for ( int i = <NUM_LIT:3> ; i >= <NUM_LIT:0> ; i -- ) { if ( aux . get ( <NUM_LIT:3> - i ) == <NUM_LIT:0x00> ) { neededBytes -- ; } else { break ; } } value = ByteBuffer . allocate ( neededBytes ) ; for ( int i = neededBytes - <NUM_LIT:1> ; i >= <NUM_LIT:0> ; i -- ) { value . put ( aux . get ( <NUM_LIT:3> - i ) ) ; } } } public String getStringValue ( ) { String result = "<STR_LIT>" ; try { result = new String ( value . array ( ) , "<STR_LIT>" ) ; } catch ( UnsupportedEncodingException e ) { System . err . println ( "<STR_LIT>" ) ; } return result ; } public void setStringValue ( String str ) { value = ByteBuffer . wrap ( str . getBytes ( ) ) ; } public String getName ( ) { return OptionNumberRegistry . toString ( optionNr ) ; } public int getLength ( ) { return value != null ? value . capacity ( ) : <NUM_LIT:0> ; } @ Override public int hashCode ( ) { final int prime = <NUM_LIT:31> ; int result = <NUM_LIT:1> ; result = prime * result + optionNr ; result = prime * result + Arrays . hashCode ( getRawValue ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Option other = ( Option ) obj ; if ( optionNr != other . optionNr ) return false ; if ( getRawValue ( ) == null ) { if ( other . getRawValue ( ) != null ) return false ; } else if ( ! Arrays . equals ( this . getRawValue ( ) , other . getRawValue ( ) ) ) return false ; return true ; } public static String hex ( byte [ ] data ) { if ( data != null && data . length != <NUM_LIT:0> ) { StringBuilder builder = new StringBuilder ( data . length * <NUM_LIT:3> ) ; for ( int i = <NUM_LIT:0> ; i < data . length ; i ++ ) { builder . append ( String . format ( "<STR_LIT>" , ( <NUM_LIT> & data [ i ] ) ) ) ; if ( i < data . length - <NUM_LIT:1> ) { builder . append ( '<CHAR_LIT:U+0020>' ) ; } } return builder . toString ( ) ; } else { return "<STR_LIT:-->" ; } } @ Override public String toString ( ) { switch ( optionNr ) { case OptionNumberRegistry . CONTENT_TYPE : return MediaTypeRegistry . toString ( getIntValue ( ) ) ; case OptionNumberRegistry . MAX_AGE : return String . format ( "<STR_LIT>" , getIntValue ( ) ) ; case OptionNumberRegistry . PROXY_URI : return getStringValue ( ) ; case OptionNumberRegistry . ETAG : return hex ( getRawValue ( ) ) ; case OptionNumberRegistry . URI_HOST : return getStringValue ( ) ; case OptionNumberRegistry . LOCATION_PATH : return getStringValue ( ) ; case OptionNumberRegistry . URI_PORT : return String . valueOf ( getIntValue ( ) ) ; case OptionNumberRegistry . LOCATION_QUERY : return getStringValue ( ) ; case OptionNumberRegistry . URI_PATH : return getStringValue ( ) ; case OptionNumberRegistry . OBSERVE : return String . valueOf ( getIntValue ( ) ) ; case OptionNumberRegistry . TOKEN : return hex ( getRawValue ( ) ) ; case OptionNumberRegistry . URI_QUERY : return getStringValue ( ) ; case OptionNumberRegistry . BLOCK1 : case OptionNumberRegistry . BLOCK2 : return String . valueOf ( getIntValue ( ) ) ; default : return hex ( getRawValue ( ) ) ; } } public boolean isDefaultValue ( ) { switch ( optionNr ) { case OptionNumberRegistry . MAX_AGE : return getIntValue ( ) == DEFAULT_MAX_AGE ; case OptionNumberRegistry . TOKEN : return getLength ( ) == <NUM_LIT:0> ; default : return false ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public class DELETERequest extends Request { public DELETERequest ( ) { super ( CodeRegistry . METHOD_DELETE , true ) ; } @ Override public void dispatch ( RequestHandler handler ) { handler . performDELETE ( this ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public class POSTRequest extends Request { public POSTRequest ( ) { super ( CodeRegistry . METHOD_POST , true ) ; } @ Override public void dispatch ( RequestHandler handler ) { handler . performPOST ( this ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public interface MessageHandler { public void handleRequest ( Request request ) ; public void handleResponse ( Response response ) ; } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public class PUTRequest extends Request { public PUTRequest ( ) { super ( CodeRegistry . METHOD_PUT , true ) ; } @ Override public void dispatch ( RequestHandler handler ) { handler . performPUT ( this ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; import java . util . HashMap ; import java . util . List ; public class MediaTypeRegistry { public static final int TEXT_PLAIN = <NUM_LIT:0> ; public static final int TEXT_XML = <NUM_LIT:1> ; public static final int TEXT_CSV = <NUM_LIT:2> ; public static final int TEXT_HTML = <NUM_LIT:3> ; public static final int IMAGE_GIF = <NUM_LIT> ; public static final int IMAGE_JPEG = <NUM_LIT> ; public static final int IMAGE_PNG = <NUM_LIT> ; public static final int IMAGE_TIFF = <NUM_LIT:24> ; public static final int AUDIO_RAW = <NUM_LIT> ; public static final int VIDEO_RAW = <NUM_LIT> ; public static final int APPLICATION_LINK_FORMAT = <NUM_LIT> ; public static final int APPLICATION_XML = <NUM_LIT> ; public static final int APPLICATION_OCTET_STREAM = <NUM_LIT> ; public static final int APPLICATION_RDF_XML = <NUM_LIT> ; public static final int APPLICATION_SOAP_XML = <NUM_LIT> ; public static final int APPLICATION_ATOM_XML = <NUM_LIT> ; public static final int APPLICATION_XMPP_XML = <NUM_LIT> ; public static final int APPLICATION_EXI = <NUM_LIT> ; public static final int APPLICATION_FASTINFOSET = <NUM_LIT> ; public static final int APPLICATION_SOAP_FASTINFOSET = <NUM_LIT> ; public static final int APPLICATION_JSON = <NUM_LIT> ; public static final int APPLICATION_X_OBIX_BINARY = <NUM_LIT> ; public static final int UNDEFINED = - <NUM_LIT:1> ; private static final HashMap < Integer , String [ ] > registry = new HashMap < Integer , String [ ] > ( ) ; static { add ( UNDEFINED , "<STR_LIT:unknown>" , "<STR_LIT>" ) ; add ( TEXT_PLAIN , "<STR_LIT:text/plain>" , "<STR_LIT>" ) ; add ( TEXT_CSV , "<STR_LIT>" , "<STR_LIT>" ) ; add ( TEXT_HTML , "<STR_LIT:text/html>" , "<STR_LIT>" ) ; add ( IMAGE_GIF , "<STR_LIT>" , "<STR_LIT>" ) ; add ( IMAGE_JPEG , "<STR_LIT>" , "<STR_LIT>" ) ; add ( IMAGE_PNG , "<STR_LIT>" , "<STR_LIT>" ) ; add ( IMAGE_TIFF , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_LINK_FORMAT , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_XML , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_OCTET_STREAM , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_RDF_XML , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_SOAP_XML , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_ATOM_XML , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_XMPP_XML , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_EXI , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_FASTINFOSET , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_SOAP_FASTINFOSET , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_JSON , "<STR_LIT>" , "<STR_LIT>" ) ; add ( APPLICATION_X_OBIX_BINARY , "<STR_LIT>" , "<STR_LIT>" ) ; } private static void add ( int mediaType , String string , String extension ) { registry . put ( mediaType , new String [ ] { string , extension } ) ; } public static String toString ( int mediaType ) { String texts [ ] = registry . get ( mediaType ) ; if ( texts != null ) { return texts [ <NUM_LIT:0> ] ; } else { return "<STR_LIT>" + mediaType ; } } public static String toFileExtension ( int mediaType ) { String texts [ ] = registry . get ( mediaType ) ; if ( texts != null ) { return texts [ <NUM_LIT:1> ] ; } else { return "<STR_LIT:unknown>" ; } } public static boolean isPrintable ( int mediaType ) { switch ( mediaType ) { case TEXT_PLAIN : case TEXT_XML : case TEXT_CSV : case TEXT_HTML : case APPLICATION_LINK_FORMAT : case APPLICATION_XML : case APPLICATION_RDF_XML : case APPLICATION_SOAP_XML : case APPLICATION_ATOM_XML : case APPLICATION_XMPP_XML : case APPLICATION_JSON : case UNDEFINED : return true ; case IMAGE_GIF : case IMAGE_JPEG : case IMAGE_PNG : case IMAGE_TIFF : case AUDIO_RAW : case VIDEO_RAW : case APPLICATION_OCTET_STREAM : case APPLICATION_EXI : case APPLICATION_FASTINFOSET : case APPLICATION_SOAP_FASTINFOSET : case APPLICATION_X_OBIX_BINARY : default : return false ; } } public static int contentNegotiation ( int defaultCt , List < Integer > supported , List < Option > accepted ) { if ( accepted . size ( ) == <NUM_LIT:0> ) { return defaultCt ; } for ( Option accept : accepted ) { if ( supported . contains ( accept . getIntValue ( ) ) ) { return accept . getIntValue ( ) ; } } return UNDEFINED ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public class Response extends Message { public Response ( ) { this ( CodeRegistry . RESP_VALID ) ; } public Response ( int status ) { setCode ( status ) ; } public void setRequest ( Request request ) { this . request = request ; } public Request getRequest ( ) { return request ; } public double getRTT ( ) { if ( request != null ) { return ( double ) ( getTimestamp ( ) - request . getTimestamp ( ) ) / <NUM_LIT> ; } else { return - <NUM_LIT> ; } } @ Override protected void payloadAppended ( byte [ ] block ) { if ( request != null ) { request . responsePayloadAppended ( this , block ) ; } } @ Override public void handleBy ( MessageHandler handler ) { handler . handleResponse ( this ) ; } public boolean isPiggyBacked ( ) { return isAcknowledgement ( ) && getCode ( ) != CodeRegistry . EMPTY_MESSAGE ; } private Request request ; } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . LinkedBlockingQueue ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class Request extends Message { private static final Response TIMEOUT_RESPONSE = new Response ( ) ; public final long startTime = System . currentTimeMillis ( ) ; private List < ResponseHandler > responseHandlers ; private BlockingQueue < Response > responseQueue ; private LocalResource resource = null ; private Response currentResponse = null ; private int responseCount ; private boolean isObserving = false ; public Request ( int method ) { super ( ) ; this . setCode ( method ) ; } public Request ( int method , boolean confirmable ) { super ( confirmable ? messageType . CON : messageType . NON , method ) ; } public void execute ( ) throws IOException { this . send ( ) ; } public void setResource ( LocalResource resouce ) { this . resource = resouce ; } @ Override public void accept ( ) { ++ this . responseCount ; super . accept ( ) ; } public Response getResponse ( ) { return this . currentResponse ; } public void setResponse ( Response response ) { this . currentResponse = response ; } public void respond ( Response response ) { response . setRequest ( this ) ; response . setPeerAddress ( getPeerAddress ( ) ) ; if ( responseCount == <NUM_LIT:0> && isConfirmable ( ) ) { response . setMID ( getMID ( ) ) ; } if ( response . getType ( ) == null ) { if ( responseCount == <NUM_LIT:0> && isConfirmable ( ) ) { response . setType ( messageType . ACK ) ; } else { response . setType ( getType ( ) ) ; } } if ( response . getCode ( ) != CodeRegistry . EMPTY_MESSAGE ) { response . setToken ( this . getToken ( ) ) ; BlockOption block1 = ( BlockOption ) this . getFirstOption ( OptionNumberRegistry . BLOCK1 ) ; if ( block1 != null ) { response . addOption ( block1 ) ; } } else { LOG . severe ( "<STR_LIT>" ) ; } ++ this . responseCount ; setResponse ( response ) ; sendResponse ( ) ; } public void respond ( int code , String message , int contentType ) { Response response = new Response ( code ) ; if ( message != null ) { response . setPayload ( message ) ; response . setContentType ( contentType ) ; LOG . finest ( String . format ( "<STR_LIT>" , contentType , message . length ( ) ) ) ; } respond ( response ) ; } public void respond ( int code , String message ) { Response response = new Response ( code ) ; if ( message != null ) { response . setPayload ( message ) ; } respond ( response ) ; } public void respond ( int code ) { respond ( code , null ) ; } private void sendResponse ( ) { if ( currentResponse != null ) { if ( ! this . isObserving ) { if ( this . resource != null && resource . isObservable ( ) && this instanceof GETRequest && CodeRegistry . responseClass ( this . getResponse ( ) . getCode ( ) ) == CodeRegistry . CLASS_SUCCESS ) { if ( this . hasOption ( OptionNumberRegistry . OBSERVE ) ) { ObservingManager . getInstance ( ) . addObserver ( ( GETRequest ) this , this . resource ) ; } else if ( ObservingManager . getInstance ( ) . isObserved ( this . getPeerAddress ( ) . toString ( ) , this . resource ) ) { ObservingManager . getInstance ( ) . removeObserver ( this . getPeerAddress ( ) . toString ( ) , this . resource ) ; } } if ( this . getPeerAddress ( ) != null ) { currentResponse . send ( ) ; } else { handleResponse ( currentResponse ) ; } } } else { LOG . warning ( String . format ( "<STR_LIT>" , key ( ) , getUriPath ( ) ) ) ; } } public Response receiveResponse ( ) throws InterruptedException { if ( ! responseQueueEnabled ( ) ) { LOG . warning ( "<STR_LIT>" ) ; enableResponseQueue ( true ) ; } Response response = responseQueue . take ( ) ; return response != TIMEOUT_RESPONSE ? response : null ; } public void registerResponseHandler ( ResponseHandler handler ) { if ( handler != null ) { if ( responseHandlers == null ) { responseHandlers = new ArrayList < ResponseHandler > ( ) ; } responseHandlers . add ( handler ) ; } } public void unregisterResponseHandler ( ResponseHandler handler ) { if ( handler != null && responseHandlers != null ) { responseHandlers . remove ( handler ) ; } } public void enableResponseQueue ( boolean enable ) { if ( enable != responseQueueEnabled ( ) ) { responseQueue = enable ? new LinkedBlockingQueue < Response > ( ) : null ; } } public boolean responseQueueEnabled ( ) { return responseQueue != null ; } protected void handleResponse ( Response response ) { if ( responseQueueEnabled ( ) ) { if ( ! responseQueue . offer ( response ) ) { System . out . println ( "<STR_LIT>" ) ; } } if ( responseHandlers != null ) { for ( ResponseHandler handler : responseHandlers ) { handler . handleResponse ( response ) ; } } } protected void responsePayloadAppended ( Response response , byte [ ] block ) { } protected void responseCompleted ( Response response ) { } public void dispatch ( RequestHandler handler ) { LOG . info ( String . format ( "<STR_LIT>" , CodeRegistry . toString ( getCode ( ) ) ) ) ; } @ Override public void handleBy ( MessageHandler handler ) { handler . handleRequest ( this ) ; } @ Override public void handleTimeout ( ) { if ( responseQueueEnabled ( ) ) { responseQueue . offer ( TIMEOUT_RESPONSE ) ; } } public void setObserving ( boolean isObserving ) { this . isObserving = isObserving ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; import java . net . Inet6Address ; import java . net . InetAddress ; import java . net . URI ; import java . net . UnknownHostException ; import java . util . logging . Logger ; import ch . ethz . inf . vs . californium . util . Properties ; public class EndpointAddress { protected static final Logger LOG = Logger . getLogger ( EndpointAddress . class . getName ( ) ) ; private InetAddress address = null ; private int port = Properties . std . getInt ( "<STR_LIT>" ) ; public EndpointAddress ( InetAddress address ) { this . address = address ; } public EndpointAddress ( InetAddress address , int port ) { this . address = address ; this . port = port ; } public EndpointAddress ( URI uri ) { try { this . address = InetAddress . getByName ( uri . getHost ( ) ) ; } catch ( UnknownHostException e ) { LOG . warning ( String . format ( "<STR_LIT>" , e . getMessage ( ) ) ) ; } if ( uri . getPort ( ) != - <NUM_LIT:1> ) this . port = uri . getPort ( ) ; } public String toString ( ) { if ( this . address instanceof Inet6Address ) { return String . format ( "<STR_LIT>" , this . address . getHostAddress ( ) , this . port ) ; } else { return String . format ( "<STR_LIT>" , this . address . getHostAddress ( ) , this . port ) ; } } public InetAddress getAddress ( ) { return this . address ; } public int getPort ( ) { return this . port ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public interface RequestHandler { public void performGET ( GETRequest request ) ; public void performPOST ( POSTRequest request ) ; public void performPUT ( PUTRequest request ) ; public void performDELETE ( DELETERequest request ) ; } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public class BlockOption extends Option { private static int encode ( int num , int szx , boolean m ) { int value = <NUM_LIT:0> ; value |= ( szx & <NUM_LIT> ) ; value |= ( m ? <NUM_LIT:1> : <NUM_LIT:0> ) << <NUM_LIT:3> ; value |= num << <NUM_LIT:4> ; return value ; } public BlockOption ( int nr ) { super ( <NUM_LIT:0> , nr ) ; } public BlockOption ( int nr , int num , int szx , boolean m ) { super ( encode ( num , szx , m ) , nr ) ; } public void setValue ( int num , int szx , boolean m ) { setIntValue ( encode ( num , szx , m ) ) ; } public int getNUM ( ) { return getIntValue ( ) > > <NUM_LIT:4> ; } public void setNUM ( int num ) { setValue ( num , getSZX ( ) , getM ( ) ) ; } public int getSZX ( ) { return getIntValue ( ) & <NUM_LIT> ; } public void setSZX ( int szx ) { setValue ( getNUM ( ) , szx , getM ( ) ) ; } public int getSize ( ) { return decodeSZX ( getIntValue ( ) & <NUM_LIT> ) ; } public void setSize ( int size ) { setValue ( getNUM ( ) , encodeSZX ( size ) , getM ( ) ) ; } public boolean getM ( ) { return ( getIntValue ( ) > > <NUM_LIT:3> & <NUM_LIT> ) != <NUM_LIT:0> ; } public void setM ( boolean m ) { setValue ( getNUM ( ) , getSZX ( ) , m ) ; } public static int decodeSZX ( int szx ) { return <NUM_LIT:1> << ( szx + <NUM_LIT:4> ) ; } public static int encodeSZX ( int blockSize ) { return ( int ) ( Math . log ( blockSize ) / Math . log ( <NUM_LIT:2> ) ) - <NUM_LIT:4> ; } public static boolean validSZX ( int szx ) { return ( szx >= <NUM_LIT:0> && szx <= <NUM_LIT:6> ) ; } @ Override public String toString ( ) { return String . format ( "<STR_LIT>" , getNUM ( ) , getSZX ( ) , getSize ( ) , getM ( ) ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . coap ; public interface MessageReceiver { public void receiveMessage ( Message msg ) ; } </s>
|
<s> package ch . ethz . inf . vs . californium . util ; import java . io . ByteArrayInputStream ; public class DatagramReader { public DatagramReader ( byte [ ] byteArray ) { byteStream = new ByteArrayInputStream ( byteArray ) ; currentByte = <NUM_LIT:0> ; currentBitIndex = - <NUM_LIT:1> ; } public int read ( int numBits ) { int bits = <NUM_LIT:0> ; for ( int i = numBits - <NUM_LIT:1> ; i >= <NUM_LIT:0> ; i -- ) { if ( currentBitIndex < <NUM_LIT:0> ) { readCurrentByte ( ) ; } boolean bit = ( currentByte > > currentBitIndex & <NUM_LIT:1> ) != <NUM_LIT:0> ; if ( bit ) { bits |= ( <NUM_LIT:1> << i ) ; } -- currentBitIndex ; } return bits ; } public byte [ ] readBytes ( int count ) { if ( count < <NUM_LIT:0> ) count = byteStream . available ( ) ; byte [ ] bytes = new byte [ count ] ; if ( currentBitIndex >= <NUM_LIT:0> ) { for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { bytes [ i ] = ( byte ) read ( Byte . SIZE ) ; } } else { byteStream . read ( bytes , <NUM_LIT:0> , bytes . length ) ; } return bytes ; } public byte [ ] readBytesLeft ( ) { return readBytes ( - <NUM_LIT:1> ) ; } private void readCurrentByte ( ) { int val = byteStream . read ( ) ; if ( val >= <NUM_LIT:0> ) { currentByte = ( byte ) val ; } else { currentByte = <NUM_LIT:0> ; } currentBitIndex = Byte . SIZE - <NUM_LIT:1> ; } private ByteArrayInputStream byteStream ; private byte currentByte ; private int currentBitIndex ; } </s>
|
<s> package ch . ethz . inf . vs . californium . util ; import java . io . ByteArrayOutputStream ; public class DatagramWriter { public DatagramWriter ( ) { byteStream = new ByteArrayOutputStream ( ) ; currentByte = <NUM_LIT:0> ; currentBitIndex = Byte . SIZE - <NUM_LIT:1> ; } public void write ( int data , int numBits ) { if ( numBits < <NUM_LIT:32> && data >= ( <NUM_LIT:1> << numBits ) ) { System . out . printf ( "<STR_LIT>" , getClass ( ) . getName ( ) , data , numBits ) ; } for ( int i = numBits - <NUM_LIT:1> ; i >= <NUM_LIT:0> ; i -- ) { boolean bit = ( data > > i & <NUM_LIT:1> ) != <NUM_LIT:0> ; if ( bit ) { currentByte |= ( <NUM_LIT:1> << currentBitIndex ) ; } -- currentBitIndex ; if ( currentBitIndex < <NUM_LIT:0> ) { writeCurrentByte ( ) ; } } } public void writeBytes ( byte [ ] bytes ) { if ( bytes == null ) return ; if ( currentBitIndex < Byte . SIZE - <NUM_LIT:1> ) { for ( int i = <NUM_LIT:0> ; i < bytes . length ; i ++ ) { write ( bytes [ i ] , Byte . SIZE ) ; } } else { byteStream . write ( bytes , <NUM_LIT:0> , bytes . length ) ; } } public byte [ ] toByteArray ( ) { writeCurrentByte ( ) ; byte [ ] byteArray = byteStream . toByteArray ( ) ; byteStream . reset ( ) ; return byteArray ; } private void writeCurrentByte ( ) { if ( currentBitIndex < Byte . SIZE - <NUM_LIT:1> ) { byteStream . write ( currentByte ) ; currentByte = <NUM_LIT:0> ; currentBitIndex = Byte . SIZE - <NUM_LIT:1> ; } } private ByteArrayOutputStream byteStream ; private byte currentByte ; private int currentBitIndex ; } </s>
|
<s> package ch . ethz . inf . vs . californium . util ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . logging . Logger ; public class Properties extends java . util . Properties { private static final Logger LOG = Logger . getLogger ( Properties . class . getName ( ) ) ; private static final long serialVersionUID = - <NUM_LIT> ; private static final String HEADER = "<STR_LIT>" ; private static final String DEFAULT_FILENAME = "<STR_LIT>" ; private void init ( ) { set ( "<STR_LIT>" , <NUM_LIT> ) ; set ( "<STR_LIT>" , "<STR_LIT>" ) ; set ( "<STR_LIT>" , <NUM_LIT> ) ; set ( "<STR_LIT>" , <NUM_LIT> ) ; set ( "<STR_LIT>" , <NUM_LIT:4> ) ; set ( "<STR_LIT>" , <NUM_LIT:4> * <NUM_LIT> ) ; set ( "<STR_LIT>" , <NUM_LIT:32> ) ; set ( "<STR_LIT>" , <NUM_LIT> ) ; set ( "<STR_LIT>" , <NUM_LIT> ) ; set ( "<STR_LIT>" , <NUM_LIT:10> ) ; } public static Properties std = new Properties ( DEFAULT_FILENAME ) ; public Properties ( String fileName ) { init ( ) ; initUserDefined ( fileName ) ; } public void set ( String key , String value ) { setProperty ( key , value ) ; } public void set ( String key , int value ) { setProperty ( key , String . valueOf ( value ) ) ; } public void set ( String key , double value ) { setProperty ( key , String . valueOf ( value ) ) ; } public String getStr ( String key ) { String value = getProperty ( key ) ; if ( value == null ) { LOG . severe ( String . format ( "<STR_LIT>" , key ) ) ; } return value ; } public int getInt ( String key ) { String value = getProperty ( key ) ; if ( value != null ) { try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException e ) { LOG . severe ( String . format ( "<STR_LIT>" , key , value ) ) ; } } else { LOG . severe ( String . format ( "<STR_LIT>" , key ) ) ; } return <NUM_LIT:0> ; } public double getDbl ( String key ) { String value = getProperty ( key ) ; if ( value != null ) { try { return Double . parseDouble ( value ) ; } catch ( NumberFormatException e ) { LOG . severe ( String . format ( "<STR_LIT>" , key , value ) ) ; } } else { LOG . severe ( String . format ( "<STR_LIT>" , key ) ) ; } return <NUM_LIT:0.0> ; } public void load ( String fileName ) throws IOException { InputStream in = new FileInputStream ( fileName ) ; load ( in ) ; } public void store ( String fileName ) throws IOException { OutputStream out = new FileOutputStream ( fileName ) ; store ( out , HEADER ) ; } private void initUserDefined ( String fileName ) { try { load ( fileName ) ; } catch ( IOException e ) { try { store ( fileName ) ; } catch ( IOException e1 ) { LOG . warning ( String . format ( "<STR_LIT>" , e1 . getMessage ( ) ) ) ; } } } } </s>
|
<s> package ch . ethz . inf . vs . californium . util ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . logging . ConsoleHandler ; import java . util . logging . FileHandler ; import java . util . logging . Formatter ; import java . util . logging . Handler ; import java . util . logging . Level ; import java . util . logging . LogRecord ; import java . util . logging . Logger ; import ch . ethz . inf . vs . californium . coap . EndpointAddress ; import ch . ethz . inf . vs . californium . coap . LinkFormat ; import ch . ethz . inf . vs . californium . coap . Message ; import ch . ethz . inf . vs . californium . coap . ObservingManager ; import ch . ethz . inf . vs . californium . coap . TokenManager ; import ch . ethz . inf . vs . californium . endpoint . Endpoint ; import ch . ethz . inf . vs . californium . endpoint . Resource ; import ch . ethz . inf . vs . californium . layers . Layer ; public class Log { private static final SimpleDateFormat dateFormat = new SimpleDateFormat ( "<STR_LIT>" ) ; private static Level logLevel = Level . ALL ; private static final Formatter printFormatter = new Formatter ( ) { @ Override public String format ( LogRecord record ) { return String . format ( "<STR_LIT>" , dateFormat . format ( new Date ( record . getMillis ( ) ) ) , record . getSourceClassName ( ) . replace ( "<STR_LIT>" , "<STR_LIT>" ) , record . getLevel ( ) , record . getMessage ( ) ) ; } } ; public static void setLevel ( Level l ) { logLevel = l ; } public static void init ( ) { Logger globalLogger = Logger . getLogger ( "<STR_LIT>" ) ; for ( Handler handler : globalLogger . getHandlers ( ) ) { globalLogger . removeHandler ( handler ) ; } ConsoleHandler cHandler = new ConsoleHandler ( ) ; cHandler . setFormatter ( printFormatter ) ; cHandler . setLevel ( Level . ALL ) ; globalLogger . addHandler ( cHandler ) ; FileHandler fHandler ; try { fHandler = new FileHandler ( "<STR_LIT>" , true ) ; fHandler . setFormatter ( printFormatter ) ; globalLogger . addHandler ( fHandler ) ; } catch ( Exception e ) { globalLogger . severe ( "<STR_LIT>" + e . getMessage ( ) ) ; } Logger . getLogger ( Endpoint . class . getName ( ) ) . setLevel ( logLevel ) ; Logger . getLogger ( EndpointAddress . class . getName ( ) ) . setLevel ( logLevel ) ; Logger . getLogger ( Resource . class . getName ( ) ) . setLevel ( logLevel ) ; Logger . getLogger ( LinkFormat . class . getName ( ) ) . setLevel ( logLevel ) ; Logger . getLogger ( Message . class . getName ( ) ) . setLevel ( logLevel ) ; Logger . getLogger ( TokenManager . class . getName ( ) ) . setLevel ( logLevel ) ; Logger . getLogger ( ObservingManager . class . getName ( ) ) . setLevel ( logLevel ) ; Logger . getLogger ( Layer . class . getName ( ) ) . setLevel ( logLevel ) ; Logger . getLogger ( Properties . class . getName ( ) ) . setLevel ( logLevel ) ; Logger . getLogger ( Log . class . getName ( ) ) . info ( "<STR_LIT>" ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . endpoint ; import java . io . PrintStream ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import java . util . SortedMap ; import java . util . TreeMap ; import java . util . TreeSet ; import java . util . logging . Logger ; import ch . ethz . inf . vs . californium . coap . LinkAttribute ; import ch . ethz . inf . vs . californium . coap . LinkFormat ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . RequestHandler ; public abstract class Resource implements RequestHandler , Comparable < Resource > { protected static final Logger LOG = Logger . getLogger ( Resource . class . getName ( ) ) ; private String resourceIdentifier ; protected Resource parent ; protected SortedMap < String , Resource > subResources ; private int totalSubResourceCount ; protected boolean hidden ; protected TreeSet < LinkAttribute > attributes ; public Resource ( String resourceIdentifier ) { this ( resourceIdentifier , false ) ; } public Resource ( String resourceIdentifier , boolean hidden ) { this . resourceIdentifier = resourceIdentifier ; this . attributes = new TreeSet < LinkAttribute > ( ) ; this . hidden = hidden ; } public String getPath ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( this . getName ( ) ) ; if ( this . parent != null ) { Resource base = this . parent ; while ( base != null ) { builder . insert ( <NUM_LIT:0> , "<STR_LIT:/>" ) ; builder . insert ( <NUM_LIT:0> , base . getName ( ) ) ; base = base . parent ; } } else { builder . append ( "<STR_LIT:/>" ) ; } return builder . toString ( ) ; } public String getName ( ) { return resourceIdentifier ; } public void setName ( String resourceIdentifier ) { this . resourceIdentifier = resourceIdentifier ; } public Set < LinkAttribute > getAttributes ( ) { return attributes ; } public List < LinkAttribute > getAttributes ( String name ) { ArrayList < LinkAttribute > ret = new ArrayList < LinkAttribute > ( ) ; for ( LinkAttribute attrib : attributes ) { if ( attrib . getName ( ) . equals ( name ) ) { ret . add ( attrib ) ; } } return ret ; } public boolean setAttribute ( LinkAttribute attrib ) { return LinkFormat . addAttribute ( attributes , attrib ) ; } public boolean clearAttribute ( String name ) { List < LinkAttribute > toRemove = new ArrayList < LinkAttribute > ( ) ; boolean cleared = false ; for ( LinkAttribute attrib : attributes ) { if ( attrib . getName ( ) . equals ( name ) ) { toRemove . add ( attrib ) ; } } for ( LinkAttribute attrib : toRemove ) { cleared |= attributes . remove ( attrib ) ; } return cleared ; } public String getTitle ( ) { List < LinkAttribute > title = getAttributes ( LinkFormat . TITLE ) ; return title . isEmpty ( ) ? null : title . get ( <NUM_LIT:0> ) . getStringValue ( ) ; } public void setTitle ( String resourceTitle ) { clearAttribute ( LinkFormat . TITLE ) ; setAttribute ( new LinkAttribute ( LinkFormat . TITLE , resourceTitle ) ) ; } public List < String > getResourceType ( ) { return LinkFormat . getStringValues ( getAttributes ( LinkFormat . RESOURCE_TYPE ) ) ; } public void setResourceType ( String resourceType ) { setAttribute ( new LinkAttribute ( LinkFormat . RESOURCE_TYPE , resourceType ) ) ; } public List < String > getInterfaceDescription ( ) { return LinkFormat . getStringValues ( getAttributes ( LinkFormat . INTERFACE_DESCRIPTION ) ) ; } public void setInterfaceDescription ( String description ) { setAttribute ( new LinkAttribute ( LinkFormat . INTERFACE_DESCRIPTION , description ) ) ; } public List < Integer > getContentTypeCode ( ) { return LinkFormat . getIntValues ( getAttributes ( LinkFormat . CONTENT_TYPE ) ) ; } public void setContentTypeCode ( int code ) { setAttribute ( new LinkAttribute ( LinkFormat . CONTENT_TYPE , code ) ) ; } public int getMaximumSizeEstimate ( ) { List < LinkAttribute > sz = getAttributes ( LinkFormat . MAX_SIZE_ESTIMATE ) ; return sz . isEmpty ( ) ? - <NUM_LIT:1> : sz . get ( <NUM_LIT:0> ) . getIntValue ( ) ; } public void setMaximumSizeEstimate ( int size ) { setAttribute ( new LinkAttribute ( LinkFormat . MAX_SIZE_ESTIMATE , size ) ) ; } public boolean isObservable ( ) { return getAttributes ( LinkFormat . OBSERVABLE ) . size ( ) > <NUM_LIT:0> ; } public void isObservable ( boolean observable ) { if ( observable ) { setAttribute ( new LinkAttribute ( LinkFormat . OBSERVABLE ) ) ; } else { clearAttribute ( LinkFormat . OBSERVABLE ) ; } } public boolean isHidden ( ) { return hidden ; } public void isHidden ( boolean change ) { hidden = change ; } public void remove ( ) { if ( parent != null ) { parent . removeSubResource ( this ) ; } } public int subResourceCount ( ) { return subResources != null ? subResources . size ( ) : <NUM_LIT:0> ; } public int totalSubResourceCount ( ) { return totalSubResourceCount ; } public Set < Resource > getSubResources ( ) { if ( subResources == null ) { return Collections . emptySet ( ) ; } TreeSet < Resource > subs = new TreeSet < Resource > ( ) ; for ( Resource sub : subResources . values ( ) ) { subs . add ( sub ) ; } return subs ; } public Resource getResource ( String path ) { return getResource ( path , false ) ; } public Resource getResource ( String path , boolean last ) { if ( path == null ) return this ; if ( path . startsWith ( "<STR_LIT:/>" ) ) { Resource root = this ; while ( root . parent != null ) { root = root . parent ; } path = path . equals ( "<STR_LIT:/>" ) ? null : path . substring ( <NUM_LIT:1> ) ; return root . getResource ( path , last ) ; } int pos = path . indexOf ( '<CHAR_LIT:/>' ) ; String head = null ; String tail = null ; if ( pos != - <NUM_LIT:1> ) { head = path . substring ( <NUM_LIT:0> , pos ) ; tail = path . substring ( pos + <NUM_LIT:1> ) ; } else { head = path ; } Resource sub = subResources ( ) . get ( head ) ; if ( sub != null ) { return sub . getResource ( tail , last ) ; } else if ( last ) { return this ; } else { return null ; } } public void add ( Resource resource ) { if ( resource == null ) throw new NullPointerException ( ) ; while ( resource . getName ( ) . startsWith ( "<STR_LIT:/>" ) ) { if ( parent != null ) { LOG . warning ( String . format ( "<STR_LIT>" , resource . getName ( ) ) ) ; } resource . setName ( resource . getName ( ) . substring ( <NUM_LIT:1> ) ) ; } Resource base = getResource ( resource . getName ( ) , true ) ; String path = this . getPath ( ) ; if ( ! path . endsWith ( "<STR_LIT:/>" ) ) path += "<STR_LIT:/>" ; path += resource . getName ( ) ; path = path . substring ( base . getPath ( ) . length ( ) ) ; if ( path . startsWith ( "<STR_LIT:/>" ) ) path = path . substring ( <NUM_LIT:1> ) ; if ( path . equals ( "<STR_LIT>" ) ) { LOG . config ( String . format ( "<STR_LIT>" , base . getPath ( ) ) ) ; for ( Resource r : base . getSubResources ( ) ) { r . parent = resource ; resource . subResources ( ) . put ( r . getName ( ) , r ) ; } resource . parent = base . parent ; base . parent . subResources ( ) . put ( base . getName ( ) , resource ) ; } else { String [ ] segments = path . split ( "<STR_LIT:/>" ) ; LOG . config ( String . format ( "<STR_LIT>" , segments . length , resource . getName ( ) ) ) ; resource . setName ( segments [ segments . length - <NUM_LIT:1> ] ) ; Resource sub = null ; for ( int i = <NUM_LIT:0> ; i < segments . length - <NUM_LIT:1> ; ++ i ) { if ( base instanceof RemoteResource ) { sub = new RemoteResource ( segments [ i ] ) ; } else { sub = new LocalResource ( segments [ i ] ) ; } sub . isHidden ( true ) ; base . add ( sub ) ; base = sub ; } resource . parent = base ; base . subResources ( ) . put ( resource . getName ( ) , resource ) ; } Resource p = resource . parent ; while ( p != null ) { ++ p . totalSubResourceCount ; p = p . parent ; } } public void removeSubResource ( Resource resource ) { if ( resource != null ) { subResources ( ) . remove ( resource . resourceIdentifier ) ; Resource p = resource . parent ; while ( p != null ) { -- p . totalSubResourceCount ; p = p . parent ; } resource . parent = null ; } } public void removeSubResource ( String resourcePath ) { removeSubResource ( getResource ( resourcePath ) ) ; } public abstract void createSubResource ( Request request , String newIdentifier ) ; public int compareTo ( Resource o ) { return getPath ( ) . compareTo ( o . getPath ( ) ) ; } public void prettyPrint ( PrintStream out , int intend ) { for ( int i = <NUM_LIT:0> ; i < intend ; i ++ ) { out . append ( '<CHAR_LIT:U+0020>' ) ; } out . printf ( "<STR_LIT>" , resourceIdentifier ) ; String title = getTitle ( ) ; if ( title != null ) { out . printf ( "<STR_LIT>" , title ) ; } out . println ( ) ; for ( LinkAttribute attrib : getAttributes ( ) ) { if ( attrib . getName ( ) . equals ( LinkFormat . TITLE ) ) continue ; for ( int i = <NUM_LIT:0> ; i < intend + <NUM_LIT:3> ; i ++ ) { out . append ( '<CHAR_LIT:U+0020>' ) ; } out . printf ( "<STR_LIT>" , attrib . serialize ( ) ) ; } if ( subResources != null ) { for ( Resource sub : subResources . values ( ) ) { sub . prettyPrint ( out , intend + <NUM_LIT:2> ) ; } } } public void prettyPrint ( ) { prettyPrint ( System . out , <NUM_LIT:0> ) ; } private SortedMap < String , Resource > subResources ( ) { if ( subResources == null ) { subResources = new TreeMap < String , Resource > ( ) ; } return subResources ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . endpoint ; import java . io . IOException ; import java . util . logging . Logger ; import ch . ethz . inf . vs . californium . coap . Communicator ; import ch . ethz . inf . vs . californium . coap . Message ; import ch . ethz . inf . vs . californium . coap . MessageHandler ; import ch . ethz . inf . vs . californium . coap . MessageReceiver ; import ch . ethz . inf . vs . californium . coap . Request ; public abstract class Endpoint implements MessageReceiver , MessageHandler { protected static final Logger LOG = Logger . getLogger ( Endpoint . class . getName ( ) ) ; protected Resource rootResource ; public abstract void execute ( Request request ) throws IOException ; public int resourceCount ( ) { return rootResource != null ? rootResource . subResourceCount ( ) + <NUM_LIT:1> : <NUM_LIT:0> ; } @ Override public void receiveMessage ( Message msg ) { msg . handleBy ( this ) ; } public int port ( ) { return Communicator . getInstance ( ) . port ( ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . endpoint ; import java . net . SocketException ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . Communicator ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . ObservingManager ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . PUTRequest ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . util . Properties ; public class LocalEndpoint extends Endpoint { public static final String ENDPOINT_INFO = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT:n>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; private class RootResource extends LocalResource { public RootResource ( ) { super ( "<STR_LIT>" , true ) ; } @ Override public void performGET ( GETRequest request ) { Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; response . setPayload ( ENDPOINT_INFO ) ; request . respond ( response ) ; } } public LocalEndpoint ( int port , int defaultBlockSze , boolean daemon ) throws SocketException { Communicator . setupPort ( port ) ; Communicator . setupTransfer ( defaultBlockSze ) ; Communicator . setupDeamon ( daemon ) ; Communicator . getInstance ( ) . registerReceiver ( this ) ; this . rootResource = new RootResource ( ) ; this . addResource ( new DiscoveryResource ( this . rootResource ) ) ; } public LocalEndpoint ( int port , int defaultBlockSze ) throws SocketException { this ( port , defaultBlockSze , false ) ; } public LocalEndpoint ( int port ) throws SocketException { this ( port , <NUM_LIT:0> ) ; } public LocalEndpoint ( ) throws SocketException { this ( Properties . std . getInt ( "<STR_LIT>" ) ) ; } @ Override public void execute ( Request request ) { if ( request != null ) { String resourcePath = request . getUriPath ( ) ; LocalResource resource = getResource ( resourcePath ) ; if ( resource != null ) { request . setResource ( resource ) ; LOG . info ( String . format ( "<STR_LIT>" , resourcePath ) ) ; request . dispatch ( resource ) ; } else if ( request instanceof PUTRequest ) { this . createByPUT ( ( PUTRequest ) request ) ; } else { LOG . info ( String . format ( "<STR_LIT>" , resourcePath ) ) ; request . respond ( CodeRegistry . RESP_NOT_FOUND ) ; } } } private void createByPUT ( PUTRequest request ) { String path = request . getUriPath ( ) ; String parentIdentifier = new String ( path ) ; String newIdentifier = "<STR_LIT>" ; Resource parent = null ; do { newIdentifier = path . substring ( parentIdentifier . lastIndexOf ( '<CHAR_LIT:/>' ) + <NUM_LIT:1> ) ; parentIdentifier = parentIdentifier . substring ( <NUM_LIT:0> , parentIdentifier . lastIndexOf ( '<CHAR_LIT:/>' ) ) ; } while ( ( parent = getResource ( parentIdentifier ) ) == null ) ; parent . createSubResource ( request , newIdentifier ) ; } public LocalResource getResource ( String resourcePath ) { if ( rootResource != null ) { return ( LocalResource ) rootResource . getResource ( resourcePath ) ; } else { return null ; } } public void addResource ( LocalResource resource ) { if ( rootResource != null ) { rootResource . add ( resource ) ; } } public void removeResource ( String resourceIdentifier ) { if ( rootResource != null ) { rootResource . removeSubResource ( resourceIdentifier ) ; } } @ Override public void handleRequest ( Request request ) { execute ( request ) ; } @ Override public void handleResponse ( Response response ) { } public Resource getRootResource ( ) { return rootResource ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . endpoint ; import java . util . List ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . LinkFormat ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . Option ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . Response ; public class DiscoveryResource extends LocalResource { public static final String DEFAULT_IDENTIFIER = "<STR_LIT>" ; private Resource root ; public DiscoveryResource ( Resource rootResource ) { super ( DEFAULT_IDENTIFIER , true ) ; setContentTypeCode ( MediaTypeRegistry . APPLICATION_LINK_FORMAT ) ; this . root = rootResource ; } @ Override public void performGET ( GETRequest request ) { Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; List < Option > query = request . getOptions ( OptionNumberRegistry . URI_QUERY ) ; response . setPayload ( LinkFormat . serialize ( root , query , true ) , MediaTypeRegistry . APPLICATION_LINK_FORMAT ) ; request . respond ( response ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . endpoint ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . DELETERequest ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . ObservingManager ; import ch . ethz . inf . vs . californium . coap . POSTRequest ; import ch . ethz . inf . vs . californium . coap . PUTRequest ; import ch . ethz . inf . vs . californium . coap . Request ; public class LocalResource extends Resource { public LocalResource ( String resourceIdentifier , boolean hidden ) { super ( resourceIdentifier , hidden ) ; } public LocalResource ( String resourceIdentifier ) { super ( resourceIdentifier , false ) ; } protected void changed ( ) { ObservingManager . getInstance ( ) . notifyObservers ( this ) ; } @ Override public void performGET ( GETRequest request ) { request . respond ( CodeRegistry . RESP_METHOD_NOT_ALLOWED ) ; } @ Override public void performPUT ( PUTRequest request ) { request . respond ( CodeRegistry . RESP_METHOD_NOT_ALLOWED ) ; } @ Override public void performPOST ( POSTRequest request ) { request . respond ( CodeRegistry . RESP_METHOD_NOT_ALLOWED ) ; } @ Override public void performDELETE ( DELETERequest request ) { request . respond ( CodeRegistry . RESP_METHOD_NOT_ALLOWED ) ; } @ Override public void createSubResource ( Request request , String newIdentifier ) { request . respond ( CodeRegistry . RESP_FORBIDDEN ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . endpoint ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import ch . ethz . inf . vs . californium . coap . Communicator ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; public class RemoteEndpoint extends Endpoint { public static Endpoint fromURI ( String uri ) { try { return new RemoteEndpoint ( new URI ( uri ) ) ; } catch ( URISyntaxException e ) { System . out . printf ( "<STR_LIT>" , "<STR_LIT>" , e . getMessage ( ) ) ; return null ; } } public RemoteEndpoint ( URI uri ) { Communicator . setupDeamon ( true ) ; Communicator . getInstance ( ) . registerReceiver ( this ) ; this . uri = uri ; } @ Override public void execute ( Request request ) throws IOException { if ( request != null ) { request . setURI ( this . uri ) ; request . execute ( ) ; } } protected URI uri ; @ Override public void handleRequest ( Request request ) { } @ Override public void handleResponse ( Response response ) { } } </s>
|
<s> package ch . ethz . inf . vs . californium . endpoint ; import ch . ethz . inf . vs . californium . coap . DELETERequest ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . LinkFormat ; import ch . ethz . inf . vs . californium . coap . POSTRequest ; import ch . ethz . inf . vs . californium . coap . PUTRequest ; import ch . ethz . inf . vs . californium . coap . Request ; public class RemoteResource extends Resource { public RemoteResource ( String resourceIdentifier ) { super ( resourceIdentifier ) ; } public static RemoteResource newRoot ( String linkFormat ) { return LinkFormat . parse ( linkFormat ) ; } @ Override public void createSubResource ( Request request , String newIdentifier ) { } @ Override public void performDELETE ( DELETERequest request ) { } @ Override public void performGET ( GETRequest request ) { } @ Override public void performPOST ( POSTRequest request ) { } @ Override public void performPUT ( PUTRequest request ) { } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . resources ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . POSTRequest ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class ToUpperResource extends LocalResource { public ToUpperResource ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; } @ Override public void performPOST ( POSTRequest request ) { if ( request . getContentType ( ) != MediaTypeRegistry . TEXT_PLAIN ) { request . respond ( CodeRegistry . RESP_UNSUPPORTED_MEDIA_TYPE , "<STR_LIT>" ) ; return ; } request . respond ( CodeRegistry . RESP_CONTENT , request . getPayloadString ( ) . toUpperCase ( ) , MediaTypeRegistry . TEXT_PLAIN ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . resources ; import java . text . DateFormat ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . Timer ; import java . util . TimerTask ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class TimeResource extends LocalResource { private String time ; public TimeResource ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; isObservable ( true ) ; Timer timer = new Timer ( ) ; timer . schedule ( new TimeTask ( ) , <NUM_LIT:0> , <NUM_LIT> ) ; } private class TimeTask extends TimerTask { @ Override public void run ( ) { time = getTime ( ) ; changed ( ) ; } } private String getTime ( ) { DateFormat dateFormat = new SimpleDateFormat ( "<STR_LIT>" ) ; Date time = new Date ( ) ; return dateFormat . format ( time ) ; } @ Override public void performGET ( GETRequest request ) { request . respond ( CodeRegistry . RESP_CONTENT , time , MediaTypeRegistry . TEXT_PLAIN ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . resources ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class CarelessResource extends LocalResource { public CarelessResource ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { request . accept ( ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . resources ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import java . io . StringReader ; import java . net . URL ; import java . util . ArrayList ; import java . util . List ; import java . util . Timer ; import java . util . TimerTask ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import org . w3c . dom . Document ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class ZurichWeatherResource extends LocalResource { public static final int WEATHER_MAX_AGE = <NUM_LIT> ; private String weatherXML ; private String weatherPLAIN ; private List < Integer > supported = new ArrayList < Integer > ( ) ; public ZurichWeatherResource ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; isObservable ( true ) ; supported . add ( MediaTypeRegistry . TEXT_PLAIN ) ; supported . add ( MediaTypeRegistry . APPLICATION_XML ) ; for ( int ct : supported ) { setContentTypeCode ( ct ) ; } getZurichWeather ( ) ; Timer timer = new Timer ( ) ; timer . schedule ( new ZurichWeatherTask ( ) , <NUM_LIT:0> , WEATHER_MAX_AGE ) ; } private class ZurichWeatherTask extends TimerTask { @ Override public void run ( ) { String weatherOLD = new String ( weatherXML ) ; getZurichWeather ( ) ; if ( ! weatherOLD . equals ( weatherXML ) ) { changed ( ) ; } } } private void getZurichWeather ( ) { URL url ; String rawWeather = "<STR_LIT>" ; try { url = new URL ( "<STR_LIT>" ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( url . openStream ( ) ) ) ; String inputLine ; while ( ( inputLine = in . readLine ( ) ) != null ) { rawWeather += inputLine + "<STR_LIT:n>" ; } in . close ( ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; } weatherPLAIN = parseWeatherXML ( rawWeather ) ; weatherXML = rawWeather ; } public String parseWeatherXML ( String input ) { String result = "<STR_LIT>" ; try { Document xmlDocument = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) . parse ( new InputSource ( new StringReader ( input ) ) ) ; result = traverseXMLTree ( xmlDocument ) ; } catch ( SAXException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; } catch ( ParserConfigurationException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; } return result ; } private String traverseXMLTree ( Node node ) { StringBuilder weatherResult = new StringBuilder ( ) ; if ( node . getNodeName ( ) . equals ( "<STR_LIT>" ) ) { weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( "<STR_LIT:n>" ) ; for ( int j = <NUM_LIT:0> ; j < node . getAttributes ( ) . getLength ( ) ; j ++ ) { weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( node . getAttributes ( ) . item ( j ) . getNodeName ( ) ) ; weatherResult . append ( "<STR_LIT::U+0020>" ) ; weatherResult . append ( node . getAttributes ( ) . item ( j ) . getNodeValue ( ) ) ; weatherResult . append ( "<STR_LIT:n>" ) ; } weatherResult . append ( "<STR_LIT>" ) ; } else if ( node . getNodeName ( ) . equals ( "<STR_LIT>" ) ) { weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( "<STR_LIT:n>" ) ; for ( int j = <NUM_LIT:0> ; j < node . getAttributes ( ) . getLength ( ) ; j ++ ) { weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( node . getAttributes ( ) . item ( j ) . getNodeName ( ) ) ; weatherResult . append ( "<STR_LIT::U+0020>" ) ; weatherResult . append ( node . getAttributes ( ) . item ( j ) . getNodeValue ( ) ) ; weatherResult . append ( "<STR_LIT:n>" ) ; } weatherResult . append ( "<STR_LIT>" ) ; } else if ( node . getNodeName ( ) . equals ( "<STR_LIT>" ) ) { weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( node . getAttributes ( ) . item ( <NUM_LIT:1> ) . getNodeValue ( ) ) ; weatherResult . append ( "<STR_LIT:n>" ) ; weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( "<STR_LIT:n>" ) ; for ( int j = <NUM_LIT:2> ; j < node . getAttributes ( ) . getLength ( ) ; j ++ ) { weatherResult . append ( "<STR_LIT>" ) ; weatherResult . append ( node . getAttributes ( ) . item ( j ) . getNodeName ( ) ) ; weatherResult . append ( "<STR_LIT::U+0020>" ) ; weatherResult . append ( node . getAttributes ( ) . item ( j ) . getNodeValue ( ) ) ; weatherResult . append ( "<STR_LIT:n>" ) ; } weatherResult . append ( "<STR_LIT>" ) ; } if ( node . hasChildNodes ( ) ) { NodeList children = node . getChildNodes ( ) ; for ( int i = <NUM_LIT:0> ; i < children . getLength ( ) ; i ++ ) { weatherResult . append ( traverseXMLTree ( children . item ( i ) ) ) ; } } return weatherResult . toString ( ) ; } @ Override public void performGET ( GETRequest request ) { int ct = MediaTypeRegistry . TEXT_PLAIN ; if ( ( ct = MediaTypeRegistry . contentNegotiation ( ct , supported , request . getOptions ( OptionNumberRegistry . ACCEPT ) ) ) == MediaTypeRegistry . UNDEFINED ) { request . respond ( CodeRegistry . RESP_NOT_ACCEPTABLE , "<STR_LIT>" ) ; return ; } Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; response . setMaxAge ( WEATHER_MAX_AGE / <NUM_LIT:1000> ) ; if ( ct == MediaTypeRegistry . APPLICATION_XML ) { response . setPayload ( weatherXML , MediaTypeRegistry . APPLICATION_XML ) ; } else { response . setPayload ( weatherPLAIN , MediaTypeRegistry . TEXT_PLAIN ) ; } request . respond ( response ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . resources ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class LargeResource extends LocalResource { public LargeResource ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; request . respond ( CodeRegistry . RESP_CONTENT , builder . toString ( ) ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . resources ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class SeparateResource extends LocalResource { public SeparateResource ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { request . accept ( ) ; try { Thread . sleep ( <NUM_LIT:1000> ) ; } catch ( InterruptedException e ) { } Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; response . setPayload ( "<STR_LIT>" + "<STR_LIT>" ) ; request . respond ( response ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . resources ; import java . util . logging . Logger ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . DELETERequest ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . LinkFormat ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . Option ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . POSTRequest ; import ch . ethz . inf . vs . californium . coap . PUTRequest ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class StorageResource extends LocalResource { public StorageResource ( ) { this ( "<STR_LIT>" ) ; } public StorageResource ( String resourceIdentifier ) { super ( resourceIdentifier ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; isObservable ( true ) ; } @ Override public void performGET ( GETRequest request ) { Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; if ( request . getContentType ( ) == MediaTypeRegistry . APPLICATION_LINK_FORMAT || data == null ) { response . setPayload ( LinkFormat . serialize ( this , request . getOptions ( OptionNumberRegistry . URI_QUERY ) , true ) , MediaTypeRegistry . APPLICATION_LINK_FORMAT ) ; } else { response . setPayload ( data ) ; if ( getContentTypeCode ( ) . size ( ) > <NUM_LIT:0> ) { response . setContentType ( getContentTypeCode ( ) . get ( <NUM_LIT:0> ) ) ; } } request . respond ( response ) ; } @ Override public void performPUT ( PUTRequest request ) { storeData ( request ) ; request . respond ( CodeRegistry . RESP_CHANGED ) ; } @ Override public void performPOST ( POSTRequest request ) { String payload = request . getPayloadString ( ) ; if ( payload != null && ! payload . isEmpty ( ) ) { createSubResource ( request , payload ) ; } else { request . respond ( CodeRegistry . RESP_BAD_REQUEST , "<STR_LIT>" ) ; } } @ Override public void createSubResource ( Request request , String newIdentifier ) { if ( request instanceof PUTRequest ) { request . respond ( CodeRegistry . RESP_FORBIDDEN , "<STR_LIT>" ) ; return ; } if ( newIdentifier . startsWith ( "<STR_LIT:/>" ) ) { newIdentifier = newIdentifier . substring ( <NUM_LIT:1> ) ; } if ( newIdentifier . endsWith ( "<STR_LIT:/>" ) ) { newIdentifier = newIdentifier . substring ( <NUM_LIT:0> , newIdentifier . length ( ) - <NUM_LIT:1> ) ; } if ( newIdentifier . indexOf ( "<STR_LIT:/>" ) != - <NUM_LIT:1> ) { newIdentifier = newIdentifier . substring ( <NUM_LIT:0> , newIdentifier . indexOf ( "<STR_LIT:/>" ) ) ; } if ( newIdentifier . indexOf ( "<STR_LIT:?>" ) != - <NUM_LIT:1> ) { newIdentifier = newIdentifier . substring ( <NUM_LIT:0> , newIdentifier . indexOf ( "<STR_LIT:?>" ) ) ; } if ( newIdentifier . indexOf ( "<STR_LIT:r>" ) != - <NUM_LIT:1> ) { newIdentifier = newIdentifier . substring ( <NUM_LIT:0> , newIdentifier . indexOf ( "<STR_LIT:r>" ) ) ; } if ( newIdentifier . indexOf ( "<STR_LIT:n>" ) != - <NUM_LIT:1> ) { newIdentifier = newIdentifier . substring ( <NUM_LIT:0> , newIdentifier . indexOf ( "<STR_LIT:n>" ) ) ; } if ( newIdentifier . length ( ) > <NUM_LIT:32> ) { request . respond ( CodeRegistry . RESP_FORBIDDEN , "<STR_LIT>" ) ; return ; } String newRtAttribute = null ; for ( Option query : request . getOptions ( OptionNumberRegistry . URI_QUERY ) ) { String keyValue [ ] = query . getStringValue ( ) . split ( "<STR_LIT:=>" ) ; if ( keyValue [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) && keyValue . length == <NUM_LIT:2> ) { newRtAttribute = keyValue [ <NUM_LIT:1> ] ; continue ; } } if ( getResource ( newIdentifier ) == null ) { StorageResource resource = new StorageResource ( newIdentifier ) ; if ( newRtAttribute != null ) { resource . setResourceType ( newRtAttribute ) ; } add ( resource ) ; resource . storeData ( request ) ; Response response = new Response ( CodeRegistry . RESP_CREATED ) ; response . setLocationPath ( resource . getPath ( ) ) ; request . respond ( response ) ; } else { request . respond ( CodeRegistry . RESP_INTERNAL_SERVER_ERROR , "<STR_LIT>" ) ; Logger . getAnonymousLogger ( ) . severe ( String . format ( "<STR_LIT>" , this . getPath ( ) , newIdentifier ) ) ; } } @ Override public void performDELETE ( DELETERequest request ) { if ( parent instanceof StorageResource ) { remove ( ) ; request . respond ( CodeRegistry . RESP_DELETED ) ; } else { request . respond ( CodeRegistry . RESP_FORBIDDEN , "<STR_LIT>" ) ; } } private void storeData ( Request request ) { data = request . getPayload ( ) ; clearAttribute ( LinkFormat . CONTENT_TYPE ) ; setContentTypeCode ( request . getContentType ( ) ) ; changed ( ) ; } private byte [ ] data ; } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . resources ; import java . io . File ; import java . io . FileInputStream ; import java . util . ArrayList ; import java . util . List ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class ImageResource extends LocalResource { private List < Integer > supported = new ArrayList < Integer > ( ) ; public ImageResource ( ) { this ( "<STR_LIT>" ) ; } public ImageResource ( String resourceIdentifier ) { super ( resourceIdentifier ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; supported . add ( MediaTypeRegistry . IMAGE_PNG ) ; supported . add ( MediaTypeRegistry . IMAGE_JPEG ) ; supported . add ( MediaTypeRegistry . IMAGE_GIF ) ; supported . add ( MediaTypeRegistry . IMAGE_TIFF ) ; for ( int ct : supported ) { setContentTypeCode ( ct ) ; } setMaximumSizeEstimate ( <NUM_LIT> ) ; isObservable ( false ) ; } @ Override public void performGET ( GETRequest request ) { String filename = "<STR_LIT>" ; int ct = MediaTypeRegistry . IMAGE_PNG ; if ( ( ct = MediaTypeRegistry . contentNegotiation ( ct , supported , request . getOptions ( OptionNumberRegistry . ACCEPT ) ) ) == MediaTypeRegistry . UNDEFINED ) { request . respond ( CodeRegistry . RESP_NOT_ACCEPTABLE , "<STR_LIT>" ) ; return ; } filename += "<STR_LIT>" + MediaTypeRegistry . toFileExtension ( ct ) ; File file = new File ( filename ) ; if ( ! file . exists ( ) ) { request . respond ( CodeRegistry . RESP_INTERNAL_SERVER_ERROR , "<STR_LIT>" ) ; return ; } int fileLength = ( int ) file . length ( ) ; FileInputStream fileIn = null ; byte [ ] fileData = new byte [ fileLength ] ; try { fileIn = new FileInputStream ( file ) ; fileIn . read ( fileData ) ; fileIn . close ( ) ; } catch ( Exception e ) { request . respond ( CodeRegistry . RESP_INTERNAL_SERVER_ERROR , "<STR_LIT>" ) ; System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; return ; } Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; response . setPayload ( fileData ) ; response . setContentType ( ct ) ; request . respond ( response ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . resources ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class HelloWorldResource extends LocalResource { public HelloWorldResource ( String custom , String title , String rt ) { super ( custom ) ; setTitle ( title ) ; setResourceType ( rt ) ; } public HelloWorldResource ( ) { this ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; response . setPayload ( "<STR_LIT>" ) ; response . setContentType ( MediaTypeRegistry . TEXT_PLAIN ) ; request . respond ( response ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples ; import java . net . SocketException ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . endpoint . Endpoint ; import ch . ethz . inf . vs . californium . endpoint . LocalEndpoint ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; import ch . ethz . inf . vs . californium . examples . resources . CarelessResource ; import ch . ethz . inf . vs . californium . examples . resources . HelloWorldResource ; import ch . ethz . inf . vs . californium . examples . resources . ImageResource ; import ch . ethz . inf . vs . californium . examples . resources . LargeResource ; import ch . ethz . inf . vs . californium . examples . resources . SeparateResource ; import ch . ethz . inf . vs . californium . examples . resources . StorageResource ; import ch . ethz . inf . vs . californium . examples . resources . TimeResource ; import ch . ethz . inf . vs . californium . examples . resources . ToUpperResource ; import ch . ethz . inf . vs . californium . examples . resources . ZurichWeatherResource ; import ch . ethz . inf . vs . californium . util . Log ; public class ExampleServer extends LocalEndpoint { public static final int ERR_INIT_FAILED = <NUM_LIT:1> ; public ExampleServer ( ) throws SocketException { addResource ( new HelloWorldResource ( ) ) ; addResource ( new ToUpperResource ( ) ) ; addResource ( new StorageResource ( ) ) ; addResource ( new SeparateResource ( ) ) ; addResource ( new LargeResource ( ) ) ; addResource ( new TimeResource ( ) ) ; addResource ( new ZurichWeatherResource ( ) ) ; addResource ( new ImageResource ( ) ) ; addResource ( new CarelessResource ( ) ) ; } @ Override public void handleRequest ( Request request ) { request . prettyPrint ( ) ; super . handleRequest ( request ) ; } public static void main ( String [ ] args ) { Log . init ( ) ; try { Endpoint server = new ExampleServer ( ) ; System . out . printf ( "<STR_LIT>" , server . port ( ) ) ; } catch ( SocketException e ) { System . err . printf ( "<STR_LIT>" , e . getMessage ( ) ) ; System . exit ( ERR_INIT_FAILED ) ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples ; import java . awt . BorderLayout ; import java . awt . Dimension ; import java . awt . GridLayout ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . util . ArrayList ; import java . util . List ; import java . util . Scanner ; import java . util . StringTokenizer ; import java . util . regex . Pattern ; import javax . swing . BoxLayout ; import javax . swing . DefaultComboBoxModel ; import javax . swing . JButton ; import javax . swing . JComboBox ; import javax . swing . JFrame ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . JSplitPane ; import javax . swing . JTextArea ; import javax . swing . JTree ; import javax . swing . SwingUtilities ; import javax . swing . UIManager ; import javax . swing . border . EmptyBorder ; import javax . swing . border . TitledBorder ; import javax . swing . event . TreeSelectionEvent ; import javax . swing . event . TreeSelectionListener ; import javax . swing . tree . DefaultMutableTreeNode ; import javax . swing . tree . DefaultTreeModel ; import javax . swing . tree . TreePath ; import ch . ethz . inf . vs . californium . coap . * ; public class GUIClient extends JPanel { private static final long serialVersionUID = - <NUM_LIT> ; private static final String DEFAULT_URI = "<STR_LIT>" ; private static final String TESTSERVER_URI = "<STR_LIT>" ; private static final String COAP_PROTOCOL = "<STR_LIT>" ; private JComboBox cboTarget ; private JTextArea txaPayload ; private JTextArea txaResponse ; private JPanel pnlResponse ; private TitledBorder responseBorder ; private DefaultMutableTreeNode dmtRes ; private DefaultTreeModel dtmRes ; private JTree treRes ; public GUIClient ( ) { JButton btnGet = new JButton ( "<STR_LIT:GET>" ) ; JButton btnPos = new JButton ( "<STR_LIT:POST>" ) ; JButton btnPut = new JButton ( "<STR_LIT>" ) ; JButton btnDel = new JButton ( "<STR_LIT>" ) ; JButton btnDisc = new JButton ( "<STR_LIT>" ) ; btnGet . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { performRequest ( new GETRequest ( ) ) ; } } ) ; btnPos . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { performRequest ( new POSTRequest ( ) ) ; } } ) ; btnPut . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { performRequest ( new PUTRequest ( ) ) ; } } ) ; btnDel . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { performRequest ( new DELETERequest ( ) ) ; } } ) ; btnDisc . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { discover ( ) ; } } ) ; cboTarget = new JComboBox ( ) ; cboTarget . setEditable ( true ) ; cboTarget . setMinimumSize ( cboTarget . getPreferredSize ( ) ) ; cboTarget . addItem ( DEFAULT_URI ) ; cboTarget . addItem ( TESTSERVER_URI ) ; cboTarget . setSelectedIndex ( <NUM_LIT:0> ) ; txaPayload = new JTextArea ( "<STR_LIT>" , <NUM_LIT:8> , <NUM_LIT> ) ; txaResponse = new JTextArea ( "<STR_LIT>" , <NUM_LIT:8> , <NUM_LIT> ) ; txaResponse . setEditable ( false ) ; JPanel pnlDisc = new JPanel ( new BorderLayout ( ) ) ; pnlDisc . add ( cboTarget , BorderLayout . CENTER ) ; pnlDisc . add ( btnDisc , BorderLayout . EAST ) ; JPanel pnlTarget = new JPanel ( new BorderLayout ( ) ) ; pnlTarget . setBorder ( new TitledBorder ( "<STR_LIT>" ) ) ; pnlTarget . add ( pnlDisc , BorderLayout . NORTH ) ; pnlTarget . setMaximumSize ( new Dimension ( Integer . MAX_VALUE , pnlTarget . getPreferredSize ( ) . height ) ) ; JPanel pnlButtons = new JPanel ( new GridLayout ( <NUM_LIT:1> , <NUM_LIT:4> , <NUM_LIT:10> , <NUM_LIT:10> ) ) ; pnlButtons . setBorder ( new EmptyBorder ( <NUM_LIT:10> , <NUM_LIT:10> , <NUM_LIT:10> , <NUM_LIT:10> ) ) ; pnlButtons . add ( btnGet ) ; pnlButtons . add ( btnPos ) ; pnlButtons . add ( btnPut ) ; pnlButtons . add ( btnDel ) ; JPanel pnlRequest = new JPanel ( new BorderLayout ( ) ) ; pnlRequest . setBorder ( new TitledBorder ( "<STR_LIT>" ) ) ; pnlRequest . add ( new JScrollPane ( txaPayload ) , BorderLayout . CENTER ) ; pnlRequest . add ( pnlButtons , BorderLayout . SOUTH ) ; pnlResponse = new JPanel ( new BorderLayout ( ) ) ; responseBorder = new TitledBorder ( "<STR_LIT>" ) ; pnlResponse . setBorder ( responseBorder ) ; pnlResponse . add ( new JScrollPane ( txaResponse ) ) ; JPanel panelC = new JPanel ( ) ; panelC . setLayout ( new BoxLayout ( panelC , BoxLayout . Y_AXIS ) ) ; panelC . add ( pnlTarget ) ; panelC . add ( pnlRequest ) ; JSplitPane splReqRes = new JSplitPane ( JSplitPane . VERTICAL_SPLIT ) ; splReqRes . setContinuousLayout ( true ) ; splReqRes . setResizeWeight ( <NUM_LIT> ) ; splReqRes . setTopComponent ( panelC ) ; splReqRes . setBottomComponent ( pnlResponse ) ; dmtRes = new DefaultMutableTreeNode ( "<STR_LIT>" ) ; dtmRes = new DefaultTreeModel ( dmtRes ) ; treRes = new JTree ( dtmRes ) ; JScrollPane scrRes = new JScrollPane ( treRes ) ; scrRes . setPreferredSize ( new Dimension ( <NUM_LIT> , scrRes . getPreferredSize ( ) . height ) ) ; JPanel panelE = new JPanel ( new BorderLayout ( ) ) ; panelE . setBorder ( new TitledBorder ( "<STR_LIT>" ) ) ; panelE . add ( scrRes , BorderLayout . CENTER ) ; setLayout ( new BorderLayout ( ) ) ; JSplitPane splCE = new JSplitPane ( JSplitPane . HORIZONTAL_SPLIT ) ; splCE . setContinuousLayout ( true ) ; splCE . setResizeWeight ( <NUM_LIT> ) ; splCE . setLeftComponent ( panelE ) ; splCE . setRightComponent ( splReqRes ) ; add ( splCE ) ; treRes . addTreeSelectionListener ( new TreeSelectionListener ( ) { public void valueChanged ( TreeSelectionEvent e ) { TreePath tp = e . getNewLeadSelectionPath ( ) ; if ( tp != null ) { Object [ ] nodes = tp . getPath ( ) ; StringBuffer sb = new StringBuffer ( COAP_PROTOCOL + getHost ( ) ) ; for ( int i = <NUM_LIT:1> ; i < nodes . length ; i ++ ) sb . append ( "<STR_LIT:/>" + nodes [ i ] . toString ( ) ) ; cboTarget . setSelectedItem ( sb . toString ( ) ) ; } } } ) ; discover ( ) ; } private void discover ( ) { dmtRes . removeAllChildren ( ) ; dtmRes . reload ( ) ; Request request = new GETRequest ( ) ; request . setURI ( COAP_PROTOCOL + getHost ( ) + "<STR_LIT>" ) ; request . registerResponseHandler ( new ResponseHandler ( ) { public void handleResponse ( Response response ) { String text = response . getPayloadString ( ) ; Scanner scanner = new Scanner ( text ) ; Pattern pattern = Pattern . compile ( "<STR_LIT:<>" ) ; scanner . useDelimiter ( pattern ) ; ArrayList < String > ress1 = new ArrayList < String > ( ) ; ArrayList < String > ress2 = new ArrayList < String > ( ) ; while ( scanner . hasNext ( ) ) { String part = scanner . next ( ) ; String res = part . split ( "<STR_LIT:>>" ) [ <NUM_LIT:0> ] ; ress1 . add ( COAP_PROTOCOL + getHost ( ) + res ) ; ress2 . add ( res ) ; } cboTarget . setModel ( new DefaultComboBoxModel ( ress1 . toArray ( new String [ ress1 . size ( ) ] ) ) ) ; populateTree ( ress2 ) ; } } ) ; execute ( request ) ; } private void populateTree ( List < String > ress ) { Node root = new Node ( "<STR_LIT>" ) ; for ( String res : ress ) { String [ ] parts = res . split ( "<STR_LIT:/>" ) ; Node cur = root ; for ( int i = <NUM_LIT:1> ; i < parts . length ; i ++ ) { Node n = cur . get ( parts [ i ] ) ; if ( n == null ) cur . children . add ( n = new Node ( parts [ i ] ) ) ; cur = n ; } } dmtRes . removeAllChildren ( ) ; addNodes ( dmtRes , root ) ; dtmRes . reload ( ) ; for ( int i = <NUM_LIT:0> ; i < treRes . getRowCount ( ) ; i ++ ) { treRes . expandRow ( i ) ; } } private void addNodes ( DefaultMutableTreeNode parent , Node node ) { for ( Node n : node . children ) { DefaultMutableTreeNode dmt = new DefaultMutableTreeNode ( n . name ) ; parent . add ( dmt ) ; addNodes ( dmt , n ) ; } } private class Node { private String name ; private ArrayList < Node > children = new ArrayList < Node > ( ) ; private Node ( String name ) { this . name = name ; } private Node get ( String name ) { for ( Node c : children ) if ( name . equals ( c . name ) ) return c ; return null ; } } public static class MyPostRequest extends POSTRequest { } private void performRequest ( Request request ) { txaResponse . setText ( "<STR_LIT>" ) ; responseBorder . setTitle ( "<STR_LIT>" ) ; pnlResponse . repaint ( ) ; request . registerResponseHandler ( new ResponsePrinter ( ) ) ; request . setPayload ( txaPayload . getText ( ) ) ; request . setURI ( cboTarget . getSelectedItem ( ) . toString ( ) . replace ( "<STR_LIT:U+0020>" , "<STR_LIT>" ) ) ; execute ( request ) ; } private void execute ( Request request ) { try { request . execute ( ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } private class ResponsePrinter implements ResponseHandler { public void handleResponse ( Response response ) { txaResponse . setText ( response . getPayloadString ( ) ) ; responseBorder . setTitle ( "<STR_LIT>" + CodeRegistry . toString ( response . getCode ( ) ) ) ; pnlResponse . repaint ( ) ; } } public static void main ( String [ ] args ) { setLookAndFeel ( ) ; SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { JFrame frame = new JFrame ( "<STR_LIT>" ) ; frame . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; frame . add ( new GUIClient ( ) ) ; frame . pack ( ) ; frame . setLocationRelativeTo ( null ) ; frame . setVisible ( true ) ; } } ) ; } private static void setLookAndFeel ( ) { try { UIManager . setLookAndFeel ( UIManager . getCrossPlatformLookAndFeelClassName ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } private String getHost ( ) { String uri = ( String ) cboTarget . getSelectedItem ( ) ; StringTokenizer st = new StringTokenizer ( uri , "<STR_LIT:/>" ) ; st . nextToken ( ) ; String host = st . nextToken ( ) ; return host ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . logging . Level ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . util . Log ; public class RTTClient { static String uriString = "<STR_LIT>" ; static int n = <NUM_LIT:1000> ; static int sent = <NUM_LIT:0> ; static int received = <NUM_LIT:0> ; static double total = <NUM_LIT> ; static double min = Double . MAX_VALUE ; static double max = <NUM_LIT> ; public static void main ( String [ ] args ) { URI uri = null ; Log . setLevel ( Level . WARNING ) ; Log . init ( ) ; if ( args . length > <NUM_LIT:0> ) { try { uri = new URI ( args [ <NUM_LIT:0> ] ) ; uriString = args [ <NUM_LIT:0> ] ; } catch ( URISyntaxException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( - <NUM_LIT:1> ) ; } if ( args . length > <NUM_LIT:1> ) { try { n = Integer . parseInt ( args [ <NUM_LIT:1> ] ) ; } catch ( NumberFormatException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( - <NUM_LIT:1> ) ; } } Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { public void run ( ) { System . out . printf ( "<STR_LIT>" , uriString , sent , received , sent - received , ( sent - received ) / sent , min , max , total / received ) ; } } ) ; for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { Request request = new GETRequest ( ) ; request . enableResponseQueue ( true ) ; request . setURI ( uri ) ; try { request . execute ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; System . exit ( - <NUM_LIT:1> ) ; } try { Response response = request . receiveResponse ( ) ; ++ sent ; if ( response != null ) { ++ received ; if ( response . getRTT ( ) > max ) { max = response . getRTT ( ) ; } if ( response . getRTT ( ) < min ) { min = response . getRTT ( ) ; } if ( response . getRTT ( ) < <NUM_LIT:0> ) { System . out . println ( "<STR_LIT>" + response . getRTT ( ) ) ; } else if ( request . getRetransmissioned ( ) > <NUM_LIT:0> ) { System . out . println ( "<STR_LIT>" + response . getRTT ( ) ) ; } else { System . out . println ( "<STR_LIT>" + response . getRTT ( ) + "<STR_LIT>" ) ; } total += response . getRTT ( ) ; } else { System . out . println ( "<STR_LIT>" ) ; } } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } } else { System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( ) ; System . out . println ( "<STR_LIT>" + RTTClient . class . getSimpleName ( ) + "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; public class GETClient { public static void main ( String args [ ] ) { URI uri = null ; if ( args . length > <NUM_LIT:0> ) { try { uri = new URI ( args [ <NUM_LIT:0> ] ) ; } catch ( URISyntaxException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( - <NUM_LIT:1> ) ; } Request request = new GETRequest ( ) ; request . setURI ( uri ) ; request . enableResponseQueue ( true ) ; try { request . execute ( ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( - <NUM_LIT:1> ) ; } try { Response response = request . receiveResponse ( ) ; if ( response != null ) { response . prettyPrint ( ) ; } else { System . out . println ( "<STR_LIT>" ) ; } } catch ( InterruptedException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( - <NUM_LIT:1> ) ; } } else { System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( ) ; System . out . println ( "<STR_LIT>" + GETClient . class . getSimpleName ( ) + "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . net . UnknownHostException ; import java . util . logging . Level ; import ch . ethz . inf . vs . californium . coap . * ; import ch . ethz . inf . vs . californium . endpoint . RemoteResource ; import ch . ethz . inf . vs . californium . endpoint . Resource ; import ch . ethz . inf . vs . californium . util . Log ; public class ExampleClient { private static final String DISCOVERY_RESOURCE = "<STR_LIT>" ; private static final int IDX_METHOD = <NUM_LIT:0> ; private static final int IDX_URI = <NUM_LIT:1> ; private static final int IDX_PAYLOAD = <NUM_LIT:2> ; private static final int ERR_MISSING_METHOD = <NUM_LIT:1> ; private static final int ERR_UNKNOWN_METHOD = <NUM_LIT:2> ; private static final int ERR_MISSING_URI = <NUM_LIT:3> ; private static final int ERR_BAD_URI = <NUM_LIT:4> ; private static final int ERR_REQUEST_FAILED = <NUM_LIT:5> ; private static final int ERR_RESPONSE_FAILED = <NUM_LIT:6> ; private static final int ERR_BAD_LINK_FORMAT = <NUM_LIT:7> ; public static void main ( String [ ] args ) { String method = null ; URI uri = null ; String payload = null ; boolean loop = false ; if ( args . length == <NUM_LIT:0> ) { printInfo ( ) ; return ; } Log . setLevel ( Level . ALL ) ; Log . init ( ) ; int idx = <NUM_LIT:0> ; for ( String arg : args ) { if ( arg . startsWith ( "<STR_LIT:->" ) ) { if ( arg . equals ( "<STR_LIT>" ) ) { loop = true ; } else { System . out . println ( "<STR_LIT>" + arg ) ; } } else { switch ( idx ) { case IDX_METHOD : method = arg . toUpperCase ( ) ; break ; case IDX_URI : try { uri = new URI ( arg ) ; } catch ( URISyntaxException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( ERR_BAD_URI ) ; } break ; case IDX_PAYLOAD : payload = arg ; break ; default : System . out . println ( "<STR_LIT>" + arg ) ; } ++ idx ; } } if ( method == null ) { System . err . println ( "<STR_LIT>" ) ; System . exit ( ERR_MISSING_METHOD ) ; } if ( uri == null ) { System . err . println ( "<STR_LIT>" ) ; System . exit ( ERR_MISSING_URI ) ; } Request request = newRequest ( method ) ; if ( request == null ) { System . err . println ( "<STR_LIT>" + method ) ; System . exit ( ERR_UNKNOWN_METHOD ) ; } if ( method . equals ( "<STR_LIT>" ) ) { request . setOption ( new Option ( <NUM_LIT:0> , OptionNumberRegistry . OBSERVE ) ) ; loop = true ; } if ( method . equals ( "<STR_LIT>" ) && ( uri . getPath ( ) == null || uri . getPath ( ) . isEmpty ( ) || uri . getPath ( ) . equals ( "<STR_LIT:/>" ) ) ) { try { uri = new URI ( uri . getScheme ( ) , uri . getAuthority ( ) , DISCOVERY_RESOURCE , uri . getQuery ( ) ) ; } catch ( URISyntaxException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( ERR_BAD_URI ) ; } } request . setURI ( uri ) ; request . setPayload ( payload ) ; request . setToken ( TokenManager . getInstance ( ) . acquireToken ( ) ) ; request . enableResponseQueue ( true ) ; request . prettyPrint ( ) ; try { request . execute ( ) ; do { System . out . println ( "<STR_LIT>" ) ; Response response = null ; try { response = request . receiveResponse ( ) ; } catch ( InterruptedException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( ERR_RESPONSE_FAILED ) ; } if ( response != null ) { response . prettyPrint ( ) ; System . out . println ( "<STR_LIT>" + response . getRTT ( ) ) ; if ( response . getContentType ( ) == MediaTypeRegistry . APPLICATION_LINK_FORMAT ) { String linkFormat = response . getPayloadString ( ) ; Resource root = RemoteResource . newRoot ( linkFormat ) ; if ( root != null ) { System . out . println ( "<STR_LIT>" ) ; root . prettyPrint ( ) ; } else { System . err . println ( "<STR_LIT>" ) ; System . exit ( ERR_BAD_LINK_FORMAT ) ; } } else { if ( method . equals ( "<STR_LIT>" ) ) { System . out . println ( "<STR_LIT>" ) ; } } } else { System . err . println ( "<STR_LIT>" ) ; break ; } } while ( loop ) ; } catch ( UnknownHostException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( ERR_REQUEST_FAILED ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( ERR_REQUEST_FAILED ) ; } System . out . println ( ) ; } public static void printInfo ( ) { System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( ) ; System . out . println ( "<STR_LIT>" + ExampleClient . class . getSimpleName ( ) + "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; } private static Request newRequest ( String method ) { if ( method . equals ( "<STR_LIT:GET>" ) ) { return new GETRequest ( ) ; } else if ( method . equals ( "<STR_LIT:POST>" ) ) { return new POSTRequest ( ) ; } else if ( method . equals ( "<STR_LIT>" ) ) { return new PUTRequest ( ) ; } else if ( method . equals ( "<STR_LIT>" ) ) { return new DELETERequest ( ) ; } else if ( method . equals ( "<STR_LIT>" ) ) { return new GETRequest ( ) ; } else if ( method . equals ( "<STR_LIT>" ) ) { return new GETRequest ( ) ; } else { return null ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . plugtest ; import java . text . DateFormat ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . Timer ; import java . util . TimerTask ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class Observe extends LocalResource { private String time ; public Observe ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; isObservable ( true ) ; Timer timer = new Timer ( ) ; timer . schedule ( new TimeTask ( ) , <NUM_LIT:0> , <NUM_LIT> ) ; } private class TimeTask extends TimerTask { @ Override public void run ( ) { time = getTime ( ) ; changed ( ) ; } } private String getTime ( ) { DateFormat dateFormat = new SimpleDateFormat ( "<STR_LIT>" ) ; Date time = new Date ( ) ; return dateFormat . format ( time ) ; } @ Override public void performGET ( GETRequest request ) { Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; response . setPayload ( time ) ; response . setContentType ( MediaTypeRegistry . TEXT_PLAIN ) ; response . setMaxAge ( <NUM_LIT:5> ) ; request . respond ( response ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . plugtest ; import java . util . ArrayList ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . LinkFormat ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . PUTRequest ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class LargeUpdate extends LocalResource { private byte [ ] data = null ; private int dataCt = MediaTypeRegistry . TEXT_PLAIN ; public LargeUpdate ( ) { this ( "<STR_LIT>" ) ; } public LargeUpdate ( String resourceIdentifier ) { super ( resourceIdentifier ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { ArrayList < Integer > supported = new ArrayList < Integer > ( ) ; supported . add ( dataCt ) ; int ct = MediaTypeRegistry . IMAGE_PNG ; if ( ( ct = MediaTypeRegistry . contentNegotiation ( dataCt , supported , request . getOptions ( OptionNumberRegistry . ACCEPT ) ) ) == MediaTypeRegistry . UNDEFINED ) { request . respond ( CodeRegistry . RESP_NOT_ACCEPTABLE , "<STR_LIT>" + MediaTypeRegistry . toString ( dataCt ) ) ; return ; } Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; if ( data == null ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; request . respond ( CodeRegistry . RESP_CONTENT , builder . toString ( ) , ct ) ; } else { response . setPayload ( data ) ; response . setContentType ( ct ) ; request . respond ( response ) ; } } @ Override public void performPUT ( PUTRequest request ) { if ( request . getContentType ( ) == MediaTypeRegistry . UNDEFINED ) { request . respond ( CodeRegistry . RESP_BAD_REQUEST , "<STR_LIT>" ) ; return ; } storeData ( request ) ; request . respond ( CodeRegistry . RESP_CHANGED ) ; } private synchronized void storeData ( Request request ) { data = request . getPayload ( ) ; dataCt = request . getContentType ( ) ; clearAttribute ( LinkFormat . CONTENT_TYPE ) ; setContentTypeCode ( dataCt ) ; changed ( ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . plugtest ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . Option ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class Query extends LocalResource { public Query ( ) { super ( "<STR_LIT:query>" ) ; setTitle ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; StringBuilder payload = new StringBuilder ( ) ; payload . append ( String . format ( "<STR_LIT>" , request . getType ( ) . ordinal ( ) , request . typeString ( ) , request . getCode ( ) , CodeRegistry . toString ( request . getCode ( ) ) , request . getMID ( ) ) ) ; for ( Option query : request . getOptions ( OptionNumberRegistry . URI_QUERY ) ) { String keyValue [ ] = query . getStringValue ( ) . split ( "<STR_LIT:=>" ) ; payload . append ( "<STR_LIT>" ) ; payload . append ( keyValue [ <NUM_LIT:0> ] ) ; if ( keyValue . length == <NUM_LIT:2> ) { payload . append ( "<STR_LIT::U+0020>" ) ; payload . append ( keyValue [ <NUM_LIT:1> ] ) ; } } if ( payload . length ( ) > <NUM_LIT> ) { payload . delete ( <NUM_LIT> , payload . length ( ) ) ; payload . append ( '<STR_LIT>' ) ; } response . setPayload ( payload . toString ( ) ) ; response . setContentType ( MediaTypeRegistry . TEXT_PLAIN ) ; request . respond ( response ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . plugtest ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class LongPath extends LocalResource { public LongPath ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; String payload = String . format ( "<STR_LIT>" , request . getType ( ) . ordinal ( ) , request . typeString ( ) , request . getCode ( ) , CodeRegistry . toString ( request . getCode ( ) ) , request . getMID ( ) ) ; response . setPayload ( payload ) ; response . setContentType ( MediaTypeRegistry . TEXT_PLAIN ) ; request . respond ( response ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . plugtest ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class Separate extends LocalResource { public Separate ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { request . accept ( ) ; try { Thread . sleep ( <NUM_LIT:1000> ) ; } catch ( InterruptedException e ) { } Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; response . setPayload ( String . format ( "<STR_LIT>" , request . getType ( ) . ordinal ( ) , request . typeString ( ) , request . getCode ( ) , CodeRegistry . toString ( request . getCode ( ) ) , request . getMID ( ) ) ) ; response . setContentType ( MediaTypeRegistry . TEXT_PLAIN ) ; request . respond ( response ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . plugtest ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . DELETERequest ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . POSTRequest ; import ch . ethz . inf . vs . californium . coap . PUTRequest ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class DefaultTest extends LocalResource { public DefaultTest ( ) { super ( "<STR_LIT:test>" ) ; setTitle ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { Response response = new Response ( CodeRegistry . RESP_CONTENT ) ; StringBuilder payload = new StringBuilder ( ) ; payload . append ( String . format ( "<STR_LIT>" , request . getType ( ) . ordinal ( ) , request . typeString ( ) , request . getCode ( ) , CodeRegistry . toString ( request . getCode ( ) ) , request . getMID ( ) ) ) ; if ( request . getToken ( ) . length > <NUM_LIT:0> ) { payload . append ( "<STR_LIT>" ) ; payload . append ( request . getTokenString ( ) ) ; } if ( payload . length ( ) > <NUM_LIT> ) { payload . delete ( <NUM_LIT> , payload . length ( ) ) ; payload . append ( '<STR_LIT>' ) ; } response . setPayload ( payload . toString ( ) ) ; response . setContentType ( MediaTypeRegistry . TEXT_PLAIN ) ; request . respond ( response ) ; } @ Override public void performPOST ( POSTRequest request ) { Response response = new Response ( CodeRegistry . RESP_CREATED ) ; response . setLocationPath ( "<STR_LIT>" ) ; request . respond ( response ) ; } @ Override public void performPUT ( PUTRequest request ) { Response response = new Response ( CodeRegistry . RESP_CHANGED ) ; request . respond ( response ) ; } @ Override public void performDELETE ( DELETERequest request ) { Response response = new Response ( CodeRegistry . RESP_DELETED ) ; request . respond ( response ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . plugtest ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class Large extends LocalResource { public Large ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; request . respond ( CodeRegistry . RESP_CONTENT , builder . toString ( ) , MediaTypeRegistry . TEXT_PLAIN ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . plugtest ; import java . util . ArrayList ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . LinkFormat ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . OptionNumberRegistry ; import ch . ethz . inf . vs . californium . coap . POSTRequest ; import ch . ethz . inf . vs . californium . coap . DELETERequest ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class LargeCreate extends LocalResource { private byte [ ] data = null ; private int dataCt = - <NUM_LIT:1> ; public LargeCreate ( ) { this ( "<STR_LIT>" ) ; } public LargeCreate ( String resourceIdentifier ) { super ( resourceIdentifier , false ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { Response response = null ; if ( data == null ) { response = new Response ( CodeRegistry . RESP_CONTENT ) ; response . setPayload ( "<STR_LIT>" , MediaTypeRegistry . TEXT_PLAIN ) ; } else { ArrayList < Integer > supported = new ArrayList < Integer > ( ) ; supported . add ( dataCt ) ; int ct = dataCt ; if ( ( ct = MediaTypeRegistry . contentNegotiation ( dataCt , supported , request . getOptions ( OptionNumberRegistry . ACCEPT ) ) ) == MediaTypeRegistry . UNDEFINED ) { request . respond ( CodeRegistry . RESP_NOT_ACCEPTABLE , "<STR_LIT>" + MediaTypeRegistry . toString ( dataCt ) ) ; return ; } response = new Response ( CodeRegistry . RESP_CONTENT ) ; response . setPayload ( data ) ; response . setContentType ( ct ) ; } request . respond ( response ) ; } @ Override public void performPOST ( POSTRequest request ) { if ( request . getContentType ( ) == MediaTypeRegistry . UNDEFINED ) { request . respond ( CodeRegistry . RESP_BAD_REQUEST , "<STR_LIT>" ) ; return ; } storeData ( request ) ; Response response = new Response ( CodeRegistry . RESP_CREATED ) ; response . setLocationPath ( "<STR_LIT>" ) ; request . respond ( response ) ; } @ Override public void performDELETE ( DELETERequest request ) { data = null ; request . respond ( new Response ( CodeRegistry . RESP_DELETED ) ) ; } private synchronized void storeData ( Request request ) { data = request . getPayload ( ) ; dataCt = request . getContentType ( ) ; clearAttribute ( LinkFormat . CONTENT_TYPE ) ; setContentTypeCode ( dataCt ) ; changed ( ) ; } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples ; import java . net . SocketException ; import java . util . logging . Level ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . endpoint . Endpoint ; import ch . ethz . inf . vs . californium . endpoint . LocalEndpoint ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; import ch . ethz . inf . vs . californium . examples . plugtest . * ; import ch . ethz . inf . vs . californium . util . Log ; public class PlugtestServer extends LocalEndpoint { public static final int ERR_INIT_FAILED = <NUM_LIT:1> ; public PlugtestServer ( ) throws SocketException { addResource ( new DefaultTest ( ) ) ; addResource ( new LongPath ( ) ) ; addResource ( new Query ( ) ) ; addResource ( new Separate ( ) ) ; addResource ( new Large ( ) ) ; addResource ( new LargeUpdate ( ) ) ; addResource ( new LargeCreate ( ) ) ; addResource ( new Observe ( ) ) ; } @ Override public void handleRequest ( Request request ) { request . prettyPrint ( ) ; super . handleRequest ( request ) ; } public static void main ( String [ ] args ) { Log . setLevel ( Level . INFO ) ; Log . init ( ) ; try { Endpoint server = new PlugtestServer ( ) ; System . out . printf ( PlugtestServer . class . getSimpleName ( ) + "<STR_LIT>" , server . port ( ) ) ; } catch ( SocketException e ) { System . err . printf ( "<STR_LIT>" + PlugtestServer . class . getSimpleName ( ) + "<STR_LIT>" , e . getMessage ( ) ) ; System . exit ( ERR_INIT_FAILED ) ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples ; import java . net . SocketException ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . endpoint . LocalEndpoint ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class HelloWorldServer extends LocalEndpoint { class HelloWorldResource extends LocalResource { public HelloWorldResource ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; } @ Override public void performGET ( GETRequest request ) { request . respond ( CodeRegistry . RESP_CONTENT , "<STR_LIT>" ) ; } } public HelloWorldServer ( ) throws SocketException { addResource ( new HelloWorldResource ( ) ) ; } public static void main ( String [ ] args ) { try { HelloWorldServer server = new HelloWorldServer ( ) ; System . out . println ( "<STR_LIT>" + server . port ( ) ) ; } catch ( SocketException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples ; import java . net . InetAddress ; import java . net . SocketException ; import java . net . UnknownHostException ; import java . util . logging . Level ; import ch . ethz . inf . vs . californium . coap . LinkFormat ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . POSTRequest ; import ch . ethz . inf . vs . californium . coap . Request ; import ch . ethz . inf . vs . californium . coap . Response ; import ch . ethz . inf . vs . californium . endpoint . LocalEndpoint ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; import ch . ethz . inf . vs . californium . examples . ipso . * ; import ch . ethz . inf . vs . californium . util . Log ; public class IpsoServer extends LocalEndpoint { public static final int ERR_INIT_FAILED = <NUM_LIT:1> ; public IpsoServer ( ) throws SocketException { addResource ( new DeviceName ( ) ) ; addResource ( new DeviceManufacturer ( ) ) ; addResource ( new DeviceModel ( ) ) ; addResource ( new DeviceSerial ( ) ) ; addResource ( new DeviceBattery ( ) ) ; addResource ( new PowerInstantaneous ( ) ) ; addResource ( new PowerCumulative ( ) ) ; addResource ( new PowerRelay ( ) ) ; addResource ( new PowerDimmer ( ) ) ; } @ Override public void handleRequest ( Request request ) { request . prettyPrint ( ) ; super . handleRequest ( request ) ; } public static void main ( String [ ] args ) { Log . setLevel ( Level . INFO ) ; Log . init ( ) ; try { LocalEndpoint server = new IpsoServer ( ) ; System . out . printf ( IpsoServer . class . getSimpleName ( ) + "<STR_LIT>" , server . port ( ) ) ; Request register = new POSTRequest ( ) { @ Override protected void handleResponse ( Response response ) { System . out . println ( "<STR_LIT>" ) ; response . prettyPrint ( ) ; } } ; String rd = "<STR_LIT>" ; if ( args . length > <NUM_LIT:0> && args [ <NUM_LIT:0> ] . startsWith ( "<STR_LIT>" ) ) { rd = args [ <NUM_LIT:0> ] ; } else { System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; } String hostname = Double . toString ( Math . round ( Math . random ( ) * <NUM_LIT:1000> ) ) ; if ( args . length > <NUM_LIT:1> && args [ <NUM_LIT:1> ] . matches ( "<STR_LIT>" ) ) { hostname = args [ <NUM_LIT:1> ] ; } else { System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; try { hostname = InetAddress . getLocalHost ( ) . getHostName ( ) ; } catch ( UnknownHostException e1 ) { System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; } } register . setURI ( rd + "<STR_LIT>" + hostname ) ; register . setPayload ( LinkFormat . serialize ( server . getRootResource ( ) , null , true ) , MediaTypeRegistry . APPLICATION_LINK_FORMAT ) ; try { System . out . println ( "<STR_LIT>" + rd + "<STR_LIT>" + hostname ) ; register . execute ( ) ; } catch ( Exception e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; System . exit ( ERR_INIT_FAILED ) ; } } catch ( SocketException e ) { System . err . printf ( "<STR_LIT>" + IpsoServer . class . getSimpleName ( ) + "<STR_LIT>" , e . getMessage ( ) ) ; System . exit ( ERR_INIT_FAILED ) ; } } } </s>
|
<s> package ch . ethz . inf . vs . californium . examples . ipso ; import ch . ethz . inf . vs . californium . coap . CodeRegistry ; import ch . ethz . inf . vs . californium . coap . GETRequest ; import ch . ethz . inf . vs . californium . coap . MediaTypeRegistry ; import ch . ethz . inf . vs . californium . coap . PUTRequest ; import ch . ethz . inf . vs . californium . endpoint . LocalResource ; public class PowerDimmer extends LocalResource { private static int percent = <NUM_LIT:100> ; public static int getDimmer ( ) { return percent ; } public PowerDimmer ( ) { super ( "<STR_LIT>" ) ; setTitle ( "<STR_LIT>" ) ; setResourceType ( "<STR_LIT>" ) ; setInterfaceDescription ( "<STR_LIT>" ) ; isObservable ( true ) ; } @ Override public void performGET ( GETRequest request ) { request . respond ( CodeRegistry . RESP_CONTENT , Integer . toString ( percent ) , MediaTypeRegistry . TEXT_PLAIN ) ; } @ Override public void performPUT ( PUTRequest request ) { if ( request . getContentType ( ) != MediaTypeRegistry . TEXT_PLAIN ) { request . respond ( CodeRegistry . RESP_BAD_REQUEST , "<STR_LIT>" ) ; return ; } int pl = Integer . parseInt ( request . getPayloadString ( ) ) ; if ( pl >= <NUM_LIT:0> && pl <= <NUM_LIT:100> ) { if ( percent == pl ) return ; percent = pl ; request . respond ( CodeRegistry . RESP_CHANGED ) ; changed ( ) ; } else { request . respond ( CodeRegistry . RESP_BAD_REQUEST , "<STR_LIT>" ) ; } } } </s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.