answer
stringlengths
17
10.2M
package com.sandwell.JavaSimulation3D; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Rectangle2D; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JWindow; import javax.swing.SpinnerNumberModel; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import com.jaamsim.basicsim.ErrorException; import com.jaamsim.controllers.RateLimiter; import com.jaamsim.controllers.RenderManager; import com.jaamsim.events.EventErrorListener; import com.jaamsim.events.EventManager; import com.jaamsim.events.EventTimeListener; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.math.Vec3d; import com.jaamsim.ui.AboutBox; import com.jaamsim.ui.DisplayEntityFactory; import com.jaamsim.ui.EntityPallet; import com.jaamsim.ui.FrameBox; import com.jaamsim.ui.LogBox; import com.jaamsim.ui.View; import com.sandwell.JavaSimulation.Entity; import com.sandwell.JavaSimulation.Simulation; /** * The main window for a Graphical Simulation. It provides the controls for managing then * EventManager (run, pause, ...) and the graphics (zoom, pan, ...) */ public class GUIFrame extends JFrame implements EventTimeListener, EventErrorListener { private static GUIFrame instance; // global shutdown flag static private AtomicBoolean shuttingDown; private JMenu fileMenu; private JMenu viewMenu; private JMenu windowMenu; private JMenu windowList; private JMenu optionMenu; private JMenu helpMenu; private JCheckBoxMenuItem showPosition; private JCheckBoxMenuItem alwaysTop; //private JCheckBoxMenuItem tooltip; private JCheckBoxMenuItem graphicsDebug; private JMenuItem printInputItem; private JMenuItem saveConfigurationMenuItem; // "Save" private JLabel clockDisplay; private JLabel speedUpDisplay; private JLabel remainingDisplay; private JToggleButton controlRealTime; private JSpinner spinner; private JToggleButton controlStartResume; private JToggleButton controlStop; private JTextField pauseTime; private JLabel locatorPos; private JLabel locatorLabel; JButton toolButtonIsometric; JButton toolButtonXYPlane; JButton toolButtonUndo; JButton toolButtonRedo; private int lastValue = -1; private JProgressBar progressBar; private static Image iconImage; private static final RateLimiter rateLimiter; private static boolean SAFE_GRAPHICS; // Collection of default window parameters public static int COL1_WIDTH; public static int COL2_WIDTH; public static int COL3_WIDTH; public static int COL1_START; public static int COL2_START; public static int COL3_START; public static int HALF_TOP; public static int HALF_BOTTOM; public static int TOP_START; public static int BOTTOM_START; public static int LOWER_HEIGHT; public static int LOWER_START; public static int VIEW_HEIGHT; public static int VIEW_WIDTH; static final String infinitySign = "\u221e"; static { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { LogBox.logLine("Unable to change look and feel."); } try { URL file = GUIFrame.class.getResource("/resources/images/icon.png"); iconImage = Toolkit.getDefaultToolkit().getImage(file); } catch (Exception e) { LogBox.logLine("Unable to load icon file."); iconImage = null; } shuttingDown = new AtomicBoolean(false); rateLimiter = RateLimiter.create(60); } private GUIFrame() { super(); getContentPane().setLayout( new BorderLayout() ); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); this.addWindowListener(new CloseListener()); // Initialize the working environment initializeMenus(); initializeMainToolBars(); initializeStatusBar(); this.setIconImage(GUIFrame.getWindowIcon()); //Set window size and make visible pack(); setResizable( false ); controlStartResume.setSelected( false ); controlStartResume.setEnabled( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); setProgress( 0 ); ToolTipManager.sharedInstance().setLightWeightPopupEnabled( false ); JPopupMenu.setDefaultLightWeightPopupEnabled( false ); } public static synchronized GUIFrame instance() { if (instance == null) instance = new GUIFrame(); return instance; } public static final RateLimiter getRateLimiter() { return rateLimiter; } /** * Listens for window events for the GUI. * */ private class CloseListener extends WindowAdapter implements ActionListener { @Override public void windowClosing(WindowEvent e) { GUIFrame.this.close(); } @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.close(); } @Override public void windowDeiconified(WindowEvent e) { // Re-open the view windows for (View v : View.getAll()) { if (v.showWindow()) RenderManager.inst().createWindow(v); } // Re-open the tools Simulation.showActiveTools(); FrameBox.reSelectEntity(); } @Override public void windowIconified(WindowEvent e) { // Close all the tools Simulation.closeAllTools(); // Save whether each window is open or closed for (View v : View.getAll()) { v.setKeepWindowOpen(v.showWindow()); } // Close all the view windows RenderManager.clear(); } } /** * Perform exit window duties */ void close() { // close warning/error trace file InputAgent.closeLogFile(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "Do you want to save the changes?", "Confirm Exit Without Saving", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ); if (userOption == JOptionPane.YES_OPTION) { InputAgent.save(this); GUIFrame.shutdown(0); } else if (userOption == JOptionPane.NO_OPTION) { GUIFrame.shutdown(0); } } else { GUIFrame.shutdown(0); } } /** * Clears the simulation and user interface for a new run */ public void clear() { currentEvt.clear(); currentEvt.setTraceListener(null); // Clear the simulation Simulation.clear(); FrameBox.clear(); EntityPallet.clear(); RenderManager.clear(); this.updateForSimulationState(GUIFrame.SIM_STATE_LOADED); // Clear the title bar setTitle(Simulation.getModelName()); // Clear the status bar setProgress( 0 ); speedUpDisplay.setText(" remainingDisplay.setText(" locatorPos.setText( "(-, -, -)" ); // Read the autoload configuration file InputAgent.clear(); InputAgent.setRecordEdits(false); InputAgent.readResource("inputs/autoload.cfg"); } /** * Sets up the Control Panel's menu bar. */ public void initializeMenus() { // Set up the individual menus this.initializeFileMenu(); this.initializeViewMenu(); this.initializeWindowMenu(); this.initializeOptionsMenu(); this.initializeHelpMenu(); // Add the individual menu to the main menu JMenuBar mainMenuBar = new JMenuBar(); mainMenuBar.add( fileMenu ); mainMenuBar.add( viewMenu ); mainMenuBar.add( windowMenu ); mainMenuBar.add( optionMenu ); mainMenuBar.add( helpMenu ); // Add main menu to the window setJMenuBar( mainMenuBar ); } /** * Sets up the File menu in the Control Panel's menu bar. */ private void initializeFileMenu() { // File menu creation fileMenu = new JMenu( "File" ); fileMenu.setMnemonic( 'F' ); fileMenu.setEnabled( false ); // 1) "New" menu item JMenuItem newMenuItem = new JMenuItem( "New" ); newMenuItem.setMnemonic( 'N' ); newMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { currentEvt.pause(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "A new simulation will overwrite the existing simulation without saving changes.\n" + "Do you wish to continue with a new simulation?", "Confirm New Simulation", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); if(userOption == JOptionPane.NO_OPTION) { return; } } clear(); InputAgent.setRecordEdits(true); InputAgent.loadDefault(); displayWindows(); } } ); fileMenu.add( newMenuItem ); // 2) "Open" menu item JMenuItem configMenuItem = new JMenuItem( "Open..." ); configMenuItem.setMnemonic( 'O' ); configMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { currentEvt.pause(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "Opening a simulation will overwrite the existing simulation without saving changes.\n" + "Do you wish to continue opening a simulation?", "Confirm Open", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); if (userOption == JOptionPane.NO_OPTION) { return; } } InputAgent.load(GUIFrame.this); } } ); fileMenu.add( configMenuItem ); // 3) "Save" menu item saveConfigurationMenuItem = new JMenuItem( "Save" ); saveConfigurationMenuItem.setMnemonic( 'S' ); saveConfigurationMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.save(GUIFrame.this); } } ); fileMenu.add( saveConfigurationMenuItem ); // 4) "Save As..." menu item JMenuItem saveConfigurationAsMenuItem = new JMenuItem( "Save As..." ); saveConfigurationAsMenuItem.setMnemonic( 'V' ); saveConfigurationAsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.saveAs(GUIFrame.this); } } ); fileMenu.add( saveConfigurationAsMenuItem ); // 5) "Import..." menu item JMenuItem importGraphicsMenuItem = new JMenuItem( "Import..." ); importGraphicsMenuItem.setMnemonic( 'I' ); importGraphicsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntityFactory.importGraphics(GUIFrame.this); } } ); fileMenu.add( importGraphicsMenuItem ); // 6) "Print Input Report" menu item printInputItem = new JMenuItem( "Print Input Report" ); printInputItem.setMnemonic( 'I' ); printInputItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.printInputFileKeywords(); } } ); fileMenu.add( printInputItem ); // 7) "Exit" menu item JMenuItem exitMenuItem = new JMenuItem( "Exit" ); exitMenuItem.setMnemonic( 'x' ); exitMenuItem.addActionListener(new CloseListener()); fileMenu.add( exitMenuItem ); } /** * Sets up the View menu in the Control Panel's menu bar. */ private void initializeViewMenu() { // View menu creation viewMenu = new JMenu( "Tools" ); viewMenu.setMnemonic( 'T' ); // 1) "Show Basic Tools" menu item JMenuItem showBasicToolsMenuItem = new JMenuItem( "Show Basic Tools" ); showBasicToolsMenuItem.setMnemonic( 'B' ); showBasicToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { Simulation sim = Simulation.getInstance(); ArrayList<String> arg = new ArrayList<String>(1); arg.add("TRUE"); InputAgent.apply(sim, new KeywordIndex("ShowModelBuilder", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowObjectSelector", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowInputEditor", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowOutputViewer", arg, null)); } } ); viewMenu.add( showBasicToolsMenuItem ); // 2) "Close All Tools" menu item JMenuItem closeAllToolsMenuItem = new JMenuItem( "Close All Tools" ); closeAllToolsMenuItem.setMnemonic( 'C' ); closeAllToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { Simulation sim = Simulation.getInstance(); ArrayList<String> arg = new ArrayList<String>(1); arg.add("FALSE"); InputAgent.apply(sim, new KeywordIndex("ShowModelBuilder", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowObjectSelector", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowInputEditor", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowOutputViewer", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowPropertyViewer", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowLogViewer", arg, null)); } } ); viewMenu.add( closeAllToolsMenuItem ); // 3) "Model Builder" menu item JMenuItem objectPalletMenuItem = new JMenuItem( "Model Builder" ); objectPalletMenuItem.setMnemonic( 'O' ); objectPalletMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<String>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowModelBuilder", arg, null)); } } ); viewMenu.add( objectPalletMenuItem ); // 4) "Object Selector" menu item JMenuItem objectSelectorMenuItem = new JMenuItem( "Object Selector" ); objectSelectorMenuItem.setMnemonic( 'S' ); objectSelectorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<String>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowObjectSelector", arg, null)); } } ); viewMenu.add( objectSelectorMenuItem ); // 5) "Input Editor" menu item JMenuItem inputEditorMenuItem = new JMenuItem( "Input Editor" ); inputEditorMenuItem.setMnemonic( 'I' ); inputEditorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<String>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowInputEditor", arg, null)); } } ); viewMenu.add( inputEditorMenuItem ); // 6) "Output Viewer" menu item JMenuItem outputMenuItem = new JMenuItem( "Output Viewer" ); outputMenuItem.setMnemonic( 'U' ); outputMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<String>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowOutputViewer", arg, null)); } } ); viewMenu.add( outputMenuItem ); // 7) "Property Viewer" menu item JMenuItem propertiesMenuItem = new JMenuItem( "Property Viewer" ); propertiesMenuItem.setMnemonic( 'P' ); propertiesMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<String>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowPropertyViewer", arg, null)); } } ); viewMenu.add( propertiesMenuItem ); // 8) "Log Viewer" menu item JMenuItem logMenuItem = new JMenuItem( "Log Viewer" ); logMenuItem.setMnemonic( 'L' ); logMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<String>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowLogViewer", arg, null)); } } ); viewMenu.add( logMenuItem ); } /** * Sets up the Window menu in the Control Panel's menu bar. */ private void initializeWindowMenu() { // Window menu creation windowMenu = new NewRenderWindowMenu("Views"); windowMenu.setMnemonic( 'V' ); // Initialize list of windows windowList = new WindowMenu("Select Window"); windowList.setMnemonic( 'S' ); //windowMenu.add( windowList ); } /** * Sets up the Options menu in the Control Panel's menu bar. */ private void initializeOptionsMenu() { optionMenu = new JMenu( "Options" ); optionMenu.setMnemonic( 'O' ); // 1) "Show Position" check box showPosition = new JCheckBoxMenuItem( "Show Position", true ); showPosition.setMnemonic( 'P' ); optionMenu.add( showPosition ); showPosition.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { setShowPositionXY(); } } ); // 2) "Always on top" check box alwaysTop = new JCheckBoxMenuItem( "Always on top", false ); alwaysTop.setMnemonic( 'A' ); optionMenu.add( alwaysTop ); alwaysTop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { if( GUIFrame.this.isAlwaysOnTop() ) { GUIFrame.this.setAlwaysOnTop( false ); } else { GUIFrame.this.setAlwaysOnTop( true ); } } } ); /*tooltip = new JCheckBoxMenuItem( "Tooltip", true ); tooltip.setMnemonic( 'L' ); optionMenu.add( tooltip ); tooltip.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { // TODO Needs to be implemented for the new Renderer } } );*/ // 3) "Graphics Debug Info" check box graphicsDebug = new JCheckBoxMenuItem( "Graphics Debug Info", false ); graphicsDebug.setMnemonic( 'G' ); optionMenu.add( graphicsDebug ); graphicsDebug.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { RenderManager.setDebugInfo(graphicsDebug.getState()); } } ); } /** * Sets up the Help menu in the Control Panel's menu bar. */ private void initializeHelpMenu() { // Help menu creation helpMenu = new JMenu( "Help" ); helpMenu.setMnemonic( 'H' ); // 1) "About" menu item JMenuItem aboutMenu = new JMenuItem( "About" ); aboutMenu.setMnemonic( 'A' ); aboutMenu.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { AboutBox.instance().setVisible(true); } } ); helpMenu.add( aboutMenu ); } /** * Returns the pixel length of the string with specified font */ private static int getPixelWidthOfString_ForFont(String str, Font font) { FontMetrics metrics = new FontMetrics(font) {}; Rectangle2D bounds = metrics.getStringBounds(str, null); return (int)bounds.getWidth(); } /** * Sets up the Control Panel's main tool bar. */ public void initializeMainToolBars() { // Insets used in setting the toolbar components Insets noMargin = new Insets( 0, 0, 0, 0 ); Insets smallMargin = new Insets( 1, 1, 1, 1 ); // Initilize the main toolbar JToolBar mainToolBar = new JToolBar(); mainToolBar.setMargin( smallMargin ); mainToolBar.setFloatable(false); // 1) Run/Pause button controlStartResume = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/run.png"))); controlStartResume.setSelectedIcon( new ImageIcon(GUIFrame.class.getResource("/resources/images/pause.png"))); controlStartResume.setToolTipText( "Run" ); controlStartResume.setMargin( noMargin ); controlStartResume.setEnabled( false ); controlStartResume.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { JToggleButton startResume = (JToggleButton)event.getSource(); startResume.setEnabled(false); if(startResume.isSelected()) { GUIFrame.this.startSimulation(); } else { GUIFrame.this.pauseSimulation(); } } } ); // 2) Stop button controlStop = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/stop.png"))); controlStop.setToolTipText( "Stop" ); controlStop.setMargin( noMargin ); controlStop.setEnabled( false ); controlStop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if( getSimState() == SIM_STATE_RUNNING ) { GUIFrame.this.pauseSimulation(); } int userOption = JOptionPane.showConfirmDialog( null, "WARNING: If you stop the run, it can only be re-started from time 0.\n" + "Do you really want to stop?", "Confirm Stop", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); // stop only if yes if (userOption == JOptionPane.YES_OPTION) { GUIFrame.this.stopSimulation(); lastSimTimeHours = 0.0d; lastSystemTime = System.currentTimeMillis(); setSpeedUp(0.0d); } } } ); // Separators have 5 pixels before and after and the preferred height of controlStartResume button Dimension separatorDim = new Dimension(11, controlStartResume.getPreferredSize().height); // dimension for 5 pixels gaps Dimension gapDim = new Dimension(5, separatorDim.height); mainToolBar.add( controlStartResume ); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add( controlStop ); // 3) Pause Time box mainToolBar.add(Box.createRigidArea(gapDim)); JLabel pauseAt = new JLabel( "Pause at:" ); mainToolBar.add(pauseAt); mainToolBar.add(Box.createRigidArea(gapDim)); pauseTime = new JTextField("2000-00-00") { @Override protected void processFocusEvent(FocusEvent fe) { // Focus gained if (fe.getID() == FocusEvent.FOCUS_GAINED) { // Convert an infinity sign to blank for editing if (getText().equals(infinitySign)) { this.setHorizontalAlignment(JTextField.RIGHT); this.setText(""); } } // Focus lost else if (fe.getID() == FocusEvent.FOCUS_LOST) { GUIFrame.instance.setPauseTime(this.getText()); } super.processFocusEvent( fe ); } }; // avoid height increase for pauseTime pauseTime.setMaximumSize(pauseTime.getPreferredSize()); // avoid stretching for puaseTime when focusing in and out pauseTime.setPreferredSize(pauseTime.getPreferredSize()); mainToolBar.add(pauseTime); pauseTime.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GUIFrame.instance.setPauseTime(pauseTime.getText()); } }); pauseTime.setText(infinitySign); pauseTime.setHorizontalAlignment(JTextField.CENTER); pauseTime.setToolTipText( "Time at which to pause the run, e.g. 3 h, 10 s, etc." ); // 4) Real Time button mainToolBar.addSeparator(separatorDim); controlRealTime = new JToggleButton( "Real Time" ); controlRealTime.setToolTipText( "Toggle Real Time mode. When selected, the simulation runs at a fixed multiple of wall clock time." ); controlRealTime.setMargin( smallMargin ); controlRealTime.addActionListener(new RealTimeActionListener()); mainToolBar.add( controlRealTime ); mainToolBar.add(Box.createRigidArea(gapDim)); // 5) Speed Up spinner SpinnerNumberModel numberModel = new SpinnerModel(Simulation.DEFAULT_REAL_TIME_FACTOR, Simulation.MIN_REAL_TIME_FACTOR, Simulation.MAX_REAL_TIME_FACTOR, 1); spinner = new JSpinner(numberModel); // make sure spinner TextField is no wider than 9 digits int diff = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().getPreferredSize().width - getPixelWidthOfString_ForFont("9", spinner.getFont()) * 9; Dimension dim = spinner.getPreferredSize(); dim.width -= diff; spinner.setMaximumSize(dim); spinner.addChangeListener(new SpeedFactorListener()); spinner.setToolTipText( "Target ratio of simulation time to wall clock time when Real Time mode is selected." ); mainToolBar.add( spinner ); // 6) View Control buttons mainToolBar.addSeparator(separatorDim); JLabel viewLabel = new JLabel( " View Control: " ); mainToolBar.add( viewLabel ); // 6a) Perspective button toolButtonIsometric = new JButton( "Perspective" ); toolButtonIsometric.setToolTipText( "Set Perspective View" ); toolButtonIsometric.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (RenderManager.isGood()) RenderManager.inst().setIsometricView(); } } ); mainToolBar.add( toolButtonIsometric ); // 6b) XY-Plane button toolButtonXYPlane = new JButton( "XY-Plane" ); toolButtonXYPlane.setToolTipText( "Set XY-Plane View" ); toolButtonXYPlane.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (RenderManager.isGood()) RenderManager.inst().setXYPlaneView(); } } ); mainToolBar.add( toolButtonXYPlane ); // 7) Undo/Redo buttons (not used at present) mainToolBar.addSeparator(separatorDim); toolButtonUndo = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/previous.png"))); toolButtonUndo.setToolTipText( "Previous view" ); toolButtonUndo.setEnabled( false ); toolButtonUndo.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { // Not implemented } } ); //mainToolBar.add( toolButtonUndo ); // add a button to redo the last step ( viewer and window ) toolButtonRedo = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/next.png"))); toolButtonRedo.setToolTipText( "Next view" ); toolButtonRedo.setEnabled( false ); toolButtonRedo.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { // Not implemented } } ); //mainToolBar.add( toolButtonRedo ); //mainToolBar.addSeparator(separatorDim); // End creation of view control label and buttons // Add toolbar to the window getContentPane().add( mainToolBar, BorderLayout.NORTH ); } private static class WindowMenu extends JMenu implements MenuListener { WindowMenu(String text) { super(text); this.addMenuListener(this); } @Override public void menuCanceled(MenuEvent arg0) {} @Override public void menuDeselected(MenuEvent arg0) { this.removeAll(); } @Override public void menuSelected(MenuEvent arg0) { if (!RenderManager.isGood()) { return; } ArrayList<Integer> windowIDs = RenderManager.inst().getOpenWindowIDs(); for (int id : windowIDs) { String windowName = RenderManager.inst().getWindowName(id); this.add(new WindowSelector(id, windowName)); } } } private static class WindowSelector extends JMenuItem implements ActionListener { private final int windowID; WindowSelector(int windowID, String windowName) { this.windowID = windowID; this.setText(windowName); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { return; } RenderManager.inst().focusWindow(windowID); } } private static class NewRenderWindowMenu extends JMenu implements MenuListener { NewRenderWindowMenu(String text) { super(text); this.addMenuListener(this); } @Override public void menuSelected(MenuEvent e) { for (View view : View.getAll()) { this.add(new NewRenderWindowLauncher(view)); } this.addSeparator(); this.add(new ViewDefiner()); } @Override public void menuCanceled(MenuEvent arg0) { } @Override public void menuDeselected(MenuEvent arg0) { this.removeAll(); } } private static class NewRenderWindowLauncher extends JMenuItem implements ActionListener { private final View view; NewRenderWindowLauncher(View v) { view = v; this.setText(view.getName()); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } ArrayList<String> arg = new ArrayList<String>(1); arg.add("TRUE"); InputAgent.apply(view, new KeywordIndex("ShowWindow", arg, null)); RenderManager.inst().createWindow(view); FrameBox.setSelectedEntity(view); } } private static class ViewDefiner extends JMenuItem implements ActionListener { ViewDefiner() {} { this.setText("Define new View"); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } View tmp = InputAgent.defineEntityWithUniqueName(View.class, "View", "", true); RenderManager.inst().createWindow(tmp); FrameBox.setSelectedEntity(tmp); ArrayList<String> arg = new ArrayList<String>(1); arg.add("TRUE"); InputAgent.apply(tmp, new KeywordIndex("ShowWindow", arg, null)); } } /** * Sets up the Control Panel's status bar. */ public void initializeStatusBar() { // Create the status bar JPanel statusBar = new JPanel(); statusBar.setBorder( BorderFactory.createLineBorder( Color.darkGray ) ); statusBar.setLayout( new FlowLayout( FlowLayout.LEFT, 10, 5 ) ); // Create the display clock and label JLabel clockLabel = new JLabel( "Simulation Time (hrs):" ); clockDisplay = new JLabel( " clockDisplay.setPreferredSize( new Dimension( 55, 16 ) ); clockDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( clockLabel ); statusBar.add( clockDisplay ); //statusBar.addSeparator(); // Create the progress bar progressBar = new JProgressBar( 0, 100 ); progressBar.setValue( 0 ); progressBar.setStringPainted( true ); // Add the progress bar to the status bar statusBar.add( progressBar ); // Create a speed-up factor display JLabel speedUpLabel = new JLabel( "Speed Up:" ); speedUpDisplay = new JLabel( " speedUpDisplay.setPreferredSize( new Dimension( 60, 16 ) ); speedUpDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( speedUpLabel ); statusBar.add( speedUpDisplay ); // Create a remaining run time display JLabel remainingLabel = new JLabel( "Time Remaining (mins):" ); remainingDisplay = new JLabel( " remainingDisplay.setPreferredSize( new Dimension( 40, 16 ) ); remainingDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( remainingLabel ); statusBar.add( remainingDisplay ); locatorPos = new JLabel( "(-, -, -)" ); locatorPos.setPreferredSize( new Dimension( 140, 16 ) ); locatorPos.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); locatorLabel = new JLabel( "Pos: " ); statusBar.add( locatorLabel ); statusBar.add( locatorPos ); // Add the status bar to the window getContentPane().add( statusBar, BorderLayout.SOUTH ); } private long lastSystemTime = System.currentTimeMillis(); private double lastSimTimeHours = 0.0d; /** * Sets the values for the simulation time, run progress, speedup factor, * and remaining run time in the Control Panel's status bar. * * @param simTime - the present simulation time in seconds. */ public void setClock(double simTime) { double clockContents = simTime / 3600.0d; clockDisplay.setText(String.format("%.2f", clockContents)); long cTime = System.currentTimeMillis(); double duration = Simulation.getRunDurationHours() + Simulation.getInitializationHours(); double timeElapsed = clockContents - Simulation.getStartHours(); int progress = (int)(timeElapsed * 100.0d / duration); this.setProgress(progress); if (cTime - lastSystemTime > 5000) { long elapsedMillis = cTime - lastSystemTime; double elapsedSimHours = timeElapsed - lastSimTimeHours; // Determine the speed-up factor double speedUp = (elapsedSimHours * 3600000.0d) / elapsedMillis; setSpeedUp(speedUp); double remainingSimTime = duration - timeElapsed; double remainingMinutes = (remainingSimTime * 60.0d) / speedUp; setRemaining(remainingMinutes); lastSystemTime = cTime; lastSimTimeHours = timeElapsed; } } /** * Displays the given value on the Control Panel's progress bar. * * @param val - the percent of the run that has completed. */ public void setProgress( int val ) { if (lastValue == val) return; progressBar.setValue( val ); progressBar.repaint(25); lastValue = val; if (getSimState() >= SIM_STATE_CONFIGURED) { String title = String.format("%d%% %s - %s", val, Simulation.getModelName(), InputAgent.getRunName()); setTitle(title); } } /** * Write the given text on the Control Panel's progress bar. * * @param txt - the text to write. */ public void setProgressText( String txt ) { progressBar.setString( txt ); } /** * Write the given value on the Control Panel's speed up factor box. * * @param val - the speed up factor to write. */ public void setSpeedUp( double val ) { speedUpDisplay.setText(String.format("%,.0f", val)); } /** * Write the given value on the Control Panel's remaining run time box. * * @param val - the remaining run time in minutes. */ public void setRemaining( double val ) { remainingDisplay.setText(String.format("%.1f", val)); } /** * Starts or resumes the simulation run. */ public void startSimulation() { // pause at a time double runToSecs = Simulation.getPauseTime(); if( getSimState() <= SIM_STATE_CONFIGURED ) { if (InputAgent.isSessionEdited()) { InputAgent.saveAs(this); } Simulation.start(currentEvt); currentEvt.resume(currentEvt.secondsToNearestTick(runToSecs)); } else if( getSimState() == SIM_STATE_PAUSED ) { currentEvt.resume(currentEvt.secondsToNearestTick(runToSecs)); } else if( getSimState() == SIM_STATE_STOPPED ) { updateForSimulationState(SIM_STATE_CONFIGURED); Simulation.start(currentEvt); currentEvt.resume(currentEvt.secondsToNearestTick(runToSecs)); } else throw new ErrorException( "Invalid Simulation State for Start/Resume" ); } /** * Pauses the simulation run. */ private void pauseSimulation() { if( getSimState() == SIM_STATE_RUNNING ) currentEvt.pause(); else throw new ErrorException( "Invalid Simulation State for pause" ); } /** * Stops the simulation run. */ public void stopSimulation() { if( getSimState() == SIM_STATE_RUNNING || getSimState() == SIM_STATE_PAUSED ) { currentEvt.pause(); currentEvt.clear(); this.updateForSimulationState(GUIFrame.SIM_STATE_STOPPED); // kill all generated objects for (int i = 0; i < Entity.getAll().size();) { Entity ent = Entity.getAll().get(i); if (ent.testFlag(Entity.FLAG_GENERATED)) ent.kill(); else i++; } } else throw new ErrorException( "Invalid Simulation State for stop" ); } /** model was executed, but no configuration performed */ public static final int SIM_STATE_LOADED = 0; /** essential model elements created, no configuration performed */ public static final int SIM_STATE_UNCONFIGURED = 1; /** model has been configured, not started */ public static final int SIM_STATE_CONFIGURED = 2; /** model is presently executing events */ public static final int SIM_STATE_RUNNING = 3; /** model has run, but presently is paused */ public static final int SIM_STATE_PAUSED = 4; /** model has run, but presently is stopped */ public static final int SIM_STATE_STOPPED = 5; private int simState; public int getSimState() { return simState; } EventManager currentEvt; public void setEventManager(EventManager e) { currentEvt = e; } /** * Sets the state of the simulation run to the given state value. * * @param state - an index that designates the state of the simulation run. */ public void updateForSimulationState(int state) { simState = state; switch( getSimState() ) { case SIM_STATE_LOADED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( false ); controlStop.setSelected( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( false ); break; case SIM_STATE_UNCONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); controlStartResume.setEnabled( false ); controlStartResume.setSelected( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( false ); showPosition.setState( true ); setShowPositionXY(); break; case SIM_STATE_CONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( true ); remainingDisplay.setEnabled( true ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setSelected( false ); controlStop.setEnabled( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( true ); break; case SIM_STATE_RUNNING: controlStartResume.setEnabled( true ); controlStartResume.setSelected( true ); controlStartResume.setToolTipText( "Pause" ); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case SIM_STATE_PAUSED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case SIM_STATE_STOPPED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( false ); controlStop.setSelected( false ); break; default: throw new ErrorException( "Unrecognized Graphics State" ); } fileMenu.setEnabled( true ); } /** * updates RealTime button and Spinner */ public void updateForRealTime(boolean executeRT, int factorRT) { currentEvt.setExecuteRealTime(executeRT, factorRT); controlRealTime.setSelected(executeRT); spinner.setValue(factorRT); } /** * updates PauseTime entry */ public void updateForPauseTime(Double t, String valueString) { if (t == Double.POSITIVE_INFINITY) { pauseTime.setText(infinitySign); pauseTime.setHorizontalAlignment(JTextField.CENTER); } else { pauseTime.setText(valueString); pauseTime.setHorizontalAlignment(JTextField.RIGHT); } } /** * Sets the PauseTime keyword for Simulation. * @param str - value to assign. */ private void setPauseTime(String str) { if (!str.equals(infinitySign)) { try { InputAgent.processEntity_Keyword_Value(Simulation.getInstance(), "PauseTime", str); } catch (InputErrorException e) { pauseTime.setText(Simulation.getInstance().getInput("PauseTime").getValueString()); JOptionPane.showMessageDialog(null, e.getMessage(), "Input Error", JOptionPane.ERROR_MESSAGE); } } // If the entry is infinity, show the infinity sign if (Simulation.getPauseTime() == Double.POSITIVE_INFINITY) { pauseTime.setText(infinitySign); pauseTime.setHorizontalAlignment(JTextField.CENTER); } else { pauseTime.setHorizontalAlignment(JTextField.RIGHT); } } public static Image getWindowIcon() { return iconImage; } public void copyLocationToClipBoard(Vec3d pos) { String data = String.format("(%.3f, %.3f, %.3f)", pos.x, pos.y, pos.z); StringSelection stringSelection = new StringSelection(data); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents( stringSelection, null ); } public void showLocatorPosition(Vec3d pos) { // null indicates nothing to display if( pos == null ) { locatorPos.setText( "(-, -, -)" ); } else { if( showPosition.getState() ) { locatorPos.setText(String.format((Locale)null, "(%.3f, %.3f, %.3f)", pos.x, pos.y, pos.z)); } } } public void setShowPositionXY() { boolean show = showPosition.getState(); showPosition.setState( show ); locatorLabel.setVisible( show ); locatorPos.setVisible( show ); locatorLabel.setText( "Pos: " ); locatorPos.setText( "(-, -, -)" ); } public void enableSave(boolean bool) { saveConfigurationMenuItem.setEnabled(bool); } /** * Sets variables used to determine the position and size of various * windows based on the size of the computer display being used. */ private static void calcWindowDefaults() { Dimension guiSize = GUIFrame.instance().getSize(); Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); COL1_WIDTH = 220; COL2_WIDTH = Math.min(520, (winSize.width - COL1_WIDTH) / 2); COL3_WIDTH = Math.min(420, winSize.width - COL1_WIDTH - COL2_WIDTH); COL1_START = 0; COL2_START = COL1_START + COL1_WIDTH; COL3_START = COL2_START + COL2_WIDTH; HALF_TOP = (winSize.height - guiSize.height) / 2; HALF_BOTTOM = (winSize.height - guiSize.height - HALF_TOP); TOP_START = guiSize.height; BOTTOM_START = TOP_START + HALF_TOP; LOWER_HEIGHT = (winSize.height - guiSize.height) / 3; LOWER_START = winSize.height - LOWER_HEIGHT; VIEW_WIDTH = COL2_WIDTH + COL3_WIDTH; VIEW_HEIGHT = winSize.height - TOP_START - LOWER_HEIGHT; } /** * Displays the view windows and tools on startup. * * @param viewOnly - boolean that determines whether the tools are to be displayed. * TRUE - show just the view windows. * FALSE - show the view windows and the tools. */ public static void displayWindows() { // Show the view windows specified in the configuration file for (View v : View.getAll()) { if (v.showWindow()) RenderManager.inst().createWindow(v); } // Set the selected entity to the first view window if (View.getAll().size() > 0) FrameBox.setSelectedEntity(View.getAll().get(0)); } // MAIN public static void main( String args[] ) { // Process the input arguments and filter out directives ArrayList<String> configFiles = new ArrayList<String>(args.length); boolean batch = false; boolean minimize = false; boolean quiet = false; for (String each : args) { // Batch mode if (each.equalsIgnoreCase("-b") || each.equalsIgnoreCase("-batch")) { batch = true; continue; } // z-buffer offset if (each.equalsIgnoreCase("-z") || each.equalsIgnoreCase("-zbuffer")) { // Parse the option, but do nothing continue; } // Minimize model window if (each.equalsIgnoreCase("-m") || each.equalsIgnoreCase("-minimize")) { minimize = true; continue; } // Do not open default windows if (each.equalsIgnoreCase("-q") || each.equalsIgnoreCase("-quiet")) { quiet = true; continue; } if (each.equalsIgnoreCase("-sg") || each.equalsIgnoreCase("-safe_graphics")) { SAFE_GRAPHICS = true; continue; } // Not a program directive, add to list of config files configFiles.add(each); } // If not running in batch mode, create the splash screen JWindow splashScreen = null; if (!batch) { URL splashImage = GUIFrame.class.getResource("/resources/images/splashscreen.png"); ImageIcon imageIcon = new ImageIcon(splashImage); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int splashX = (screen.width - imageIcon.getIconWidth()) / 2; int splashY = (screen.height - imageIcon.getIconHeight()) / 2; // Set the window's bounds, centering the window splashScreen = new JWindow(); splashScreen.setAlwaysOnTop(true); splashScreen.setBounds(splashX, splashY, imageIcon.getIconWidth(), imageIcon.getIconHeight()); // Build the splash screen splashScreen.getContentPane().add(new JLabel(imageIcon)); // Display it splashScreen.setVisible(true); // Begin initializing the rendering system RenderManager.initialize(SAFE_GRAPHICS); } // create a graphic simulation LogBox.logLine("Loading Simulation Environment ... "); EventManager evt = new EventManager("DefaultEventManager"); GUIFrame gui = GUIFrame.instance(); gui.setEventManager(evt); gui.updateForSimulationState(SIM_STATE_LOADED); evt.setTimeListener(gui); evt.setErrorListener(gui); LogBox.logLine("Simulation Environment Loaded"); if (batch) InputAgent.setBatch(true); if (minimize) gui.setExtendedState(JFrame.ICONIFIED); // Show the Control Panel gui.setVisible(true); GUIFrame.calcWindowDefaults(); // Load the autoload file InputAgent.setRecordEdits(false); InputAgent.readResource("inputs/autoload.cfg"); gui.setTitle(Simulation.getModelName()); // Resolve all input arguments against the current working directory File user = new File(System.getProperty("user.dir")); // Process any configuration files passed on command line // (Multiple configuration files are not supported at present) for (int i = 0; i < configFiles.size(); i++) { //InputAgent.configure(gui, new File(configFiles.get(i))); File abs = new File((File)null, configFiles.get(i)); if (abs.exists()) InputAgent.configure(gui, abs.getAbsoluteFile()); else InputAgent.configure(gui, new File(user, configFiles.get(i))); } // If no configuration files were specified on the command line, then load the default configuration file if( configFiles.size() == 0 ) { InputAgent.setRecordEdits(true); InputAgent.loadDefault(); gui.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED); } // Show the view windows if(!quiet && !batch) { displayWindows(); } // If in batch or quiet mode, close the any tools that were opened if (quiet || batch) Simulation.closeAllTools(); // Set RecordEdits mode (if it has not already been set in the configuration file) InputAgent.setRecordEdits(true); // Start the model if in batch mode if (batch) { if (InputAgent.numErrors() > 0) GUIFrame.shutdown(0); Simulation.start(evt); evt.resume(Long.MAX_VALUE); GUIFrame.instance.updateForSimulationState(GUIFrame.SIM_STATE_RUNNING); return; } // Wait to allow the renderer time to finish initialisation try { Thread.sleep(1000); } catch (InterruptedException e) {} // Hide the splash screen if (splashScreen != null) { splashScreen.dispose(); splashScreen = null; } // Bring the Control Panel to the front (along with any open Tools) gui.toFront(); // Trigger an extra redraw to ensure that the view windows are ready if (View.getAll().size() > 0) RenderManager.redraw(); } public static class SpeedFactorListener implements ChangeListener { @Override public void stateChanged( ChangeEvent e ) { ArrayList<String> arg = new ArrayList<String>(1); arg.add(String.format("%d", ((JSpinner)e.getSource()).getValue())); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("RealTimeFactor", arg, null)); } } /* * this class is created so the next value will be value * 2 and the * previous value will be value / 2 */ public static class SpinnerModel extends SpinnerNumberModel { private int value; public SpinnerModel( int val, int min, int max, int stepSize) { super(val, min, max, stepSize); } @Override @SuppressWarnings("unchecked") public Object getPreviousValue() { value = this.getNumber().intValue() / 2; // Avoid going beyond limit if(this.getMinimum().compareTo(value) > 0 ) { return this.getMinimum(); } return value; } @Override @SuppressWarnings("unchecked") public Object getNextValue() { value = this.getNumber().intValue() * 2; // Avoid going beyond limit if(this.getMaximum().compareTo(value) < 0 ) { return this.getMaximum(); } return value; } } public static class RealTimeActionListener implements ActionListener { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<String>(1); if (((JToggleButton)event.getSource()).isSelected()) arg.add("TRUE"); else arg.add("FALSE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("RealTime", arg, null)); } } public static boolean getShuttingDownFlag() { return shuttingDown.get(); } public static void shutdown(int errorCode) { shuttingDown.set(true); if (RenderManager.isGood()) { RenderManager.inst().shutdown(); } System.exit(errorCode); } @Override public void tickUpdate(long tick) { FrameBox.timeUpdate(tick); } @Override public void timeRunning(boolean running) { if (running) { updateForSimulationState(SIM_STATE_RUNNING); } else { updateForSimulationState(SIM_STATE_PAUSED); } } @Override public void handleError(EventManager evt, Throwable t, long currentTick) { if (t instanceof OutOfMemoryError) { OutOfMemoryError e = (OutOfMemoryError)t; LogBox.logLine("Out of Memory use the -Xmx flag during execution for more memory"); LogBox.logLine("Further debug information:"); LogBox.logLine("Error: " + e.getMessage()); for (StackTraceElement each : e.getStackTrace()) LogBox.logLine(each.toString()); LogBox.makeVisible(); GUIFrame.shutdown(1); return; } else { double curSec = evt.ticksToSeconds(currentTick); LogBox.format("EXCEPTION AT TIME: %f s%n", curSec); LogBox.logLine("Error: " + t.getMessage()); for (StackTraceElement each : t.getStackTrace()) LogBox.logLine(each.toString()); LogBox.makeVisible(); } if (InputAgent.getBatch()) GUIFrame.shutdown(1); } }
package com.seleniumtests.webelements; import com.seleniumtests.core.CustomAssertion; import com.seleniumtests.core.TestLogging; import com.seleniumtests.customexception.NotCurrentPageException; import com.seleniumtests.driver.BrowserType; import com.seleniumtests.driver.WebUIDriver; import com.seleniumtests.helper.WaitHelper; import com.thoughtworks.selenium.SeleniumException; import com.thoughtworks.selenium.Wait; import com.thoughtworks.selenium.webdriven.commands.Windows; import org.openqa.selenium.*; import org.openqa.selenium.internal.seleniumemulation.JavascriptLibrary; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; /** * Base html page abstraction. Used by PageObject and WebPageSection * */ public abstract class BasePage { protected WebDriver driver = WebUIDriver.getWebDriver(); protected final WebUIDriver webUXDriver = WebUIDriver.getWebUXDriver(); private int explictWaitTimeout = WebUIDriver.getWebUXDriver() .getExplicitWait(); private int sessionTimeout = WebUIDriver.getWebUXDriver() .getWebSessionTimeout(); public BasePage() { } public void acceptAlert() throws NotCurrentPageException { Alert alert = driver.switchTo().alert(); alert.accept(); driver.switchTo().defaultContent(); } public void assertAlertPresent() { TestLogging.logWebStep(null, "assert alert present.", false); try { driver.switchTo().alert(); } catch (Exception ex) { assertAlertHTML(false, "assert alert present."); } } public void assertAlertText(String text) { TestLogging.logWebStep(null, "assert alert text.", false); Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); assertAlertHTML(alertText.contains(text), "assert alert text."); } /** * * @param element * @param attributeName * @param value */ public void assertAttribute(HtmlElement element, String attributeName, String value) { TestLogging.logWebStep(null, "assert " + element.toHTML() + " attribute = " + attributeName + ", expectedValue ={" + value + "}.", false); String attributeValue = element.getAttribute(attributeName); assertHTML(value != null && value.equals(attributeValue), element.toString() + " attribute = " + attributeName + ", expectedValue = {" + value + "}" + ", attributeValue = {" + attributeValue + "}"); } public void assertAttributeContains(HtmlElement element, String attributeName, String keyword) { TestLogging.logWebStep(null, "assert " + element.toHTML() + " attribute=" + attributeName + ", contains keyword = {" + keyword + "}.", false); String attributeValue = element.getAttribute(attributeName); assertHTML( attributeValue != null && keyword != null && attributeValue.contains(keyword), element.toString() + " attribute=" + attributeName + ", expected to contains keyword {" + keyword + "}" + ", attributeValue = {" + attributeValue + "}"); } public void assertAttributeMatches(HtmlElement element, String attributeName, String regex) { TestLogging.logWebStep(null, "assert " + element.toHTML() + " attribute=" + attributeName + ", matches regex = {" + regex + "}.", false); String attributeValue = element.getAttribute(attributeName); assertHTML( attributeValue != null && regex != null && attributeValue.matches(regex), element.toString() + " attribute=" + attributeName + " expected to match regex {" + regex + "}" + ", attributeValue = {" + attributeValue + "}"); } public void assertConfirmationText(String text) { TestLogging.logWebStep(null, "assert confirmation text.", false); Alert alert = driver.switchTo().alert(); String seenText = alert.getText(); assertAlertHTML(seenText.contains(text), "assert confirmation text."); } protected void assertCurrentPage(boolean log) throws NotCurrentPageException { } public void assertElementNotPresent(HtmlElement element) { TestLogging.logWebStep(null, "assert " + element.toHTML() + " is not present.", false); assertHTML(!element.isElementPresent(), element.toString() + " found."); } public void assertElementPresent(HtmlElement element) { TestLogging.logWebStep(null, "assert " + element.toHTML() + " is present.", false); assertHTML(element.isElementPresent(), element.toString() + " not found."); } public void assertElementEnabled(HtmlElement element) { TestLogging.logWebStep(null, "assert " + element.toHTML() + " is enabled.", false); assertHTML(element.isEnabled(), element.toString() + " not found."); } public void assertElementNotEnabled(HtmlElement element) { TestLogging.logWebStep(null, "assert " + element.toHTML() + " is not enabled.", false); assertHTML(!element.isEnabled(), element.toString() + " not found."); } public void assertElementDisplayed(HtmlElement element) { TestLogging.logWebStep(null, "assert " + element.toHTML() + " is displayed.", false); assertHTML(element.isDisplayed(), element.toString() + " not found."); } public void assertElementSelected(HtmlElement element) { TestLogging.logWebStep(null, "assert " + element.toHTML() + " is selected.", false); assertHTML(element.isSelected(), element.toString() + " not found."); } public void assertElementNotSelected(HtmlElement element) { TestLogging.logWebStep(null, "assert " + element.toHTML() + " is NOT selected.", false); assertHTML(!element.isSelected(), element.toString() + " not found."); } public void assertCondition(boolean condition, String message) { TestLogging.logWebStep(null, "assert that " + message, false); assert condition; } void assertHTML(boolean condition, String message) { if (!condition) { capturePageSnapshot(); CustomAssertion.assertTrue(condition, message); } } void assertAlertHTML(boolean condition, String message) { if (!condition) { CustomAssertion.assertTrue(condition, message); } } public void assertPromptText(String text) { TestLogging.logWebStep(null, "assert prompt text.", false); Alert alert = driver.switchTo().alert(); String seenText = alert.getText(); assertAlertHTML(seenText.contains(text), "assert prompt text."); } public void assertTable(Table table, int row, int col, String text) { TestLogging.logWebStep(null, "assert text \"" + text + "\" equals " + table.toHTML() + " at (row, col) = (" + row + ", " + col + ").", false); String content = table.getContent(row, col); assertHTML(content != null && content.equals(text), "Text= {" + text + "} not found on " + table.toString() + " at cell(row, col) = {" + row + "," + col + "}"); } public void assertTableContains(Table table, int row, int col, String text) { TestLogging.logWebStep(null, "assert text \"" + text + "\" contains " + table.toHTML() + " at (row, col) = (" + row + ", " + col + ").", false); String content = table.getContent(row, col); assertHTML(content != null && content.contains(text), "Text= {" + text + "} not found on " + table.toString() + " at cell(row, col) = {" + row + "," + col + "}"); } public void assertTableMatches(Table table, int row, int col, String text) { TestLogging.logWebStep(null, "assert text \"" + text + "\" matches " + table.toHTML() + " at (row, col) = (" + row + ", " + col + ").", false); String content = table.getContent(row, col); assertHTML(content != null && content.matches(text), "Text= {" + text + "} not found on " + table.toString() + " at cell(row, col) = {" + row + "," + col + "}"); } public void assertTextNotPresent(String text) { TestLogging.logWebStep(null, "assert text \"" + text + "\" is not present.", false); assertHTML(!isTextPresent(text), "Text= {" + text + "} found."); } public void assertTextNotPresentIgnoreCase(String text) { TestLogging.logWebStep(null, "assert text \"" + text + "\" is not present.(ignore case)", false); assertHTML(!getBodyText().toLowerCase().contains(text.toLowerCase()), "Text= {" + text + "} found."); } public void assertTextPresent(String text) { TestLogging.logWebStep(null, "assert text \"" + text + "\" is present.", false); assertHTML(isTextPresent(text), "Text= {" + text + "} not found."); } public void assertTextPresentIgnoreCase(String text) { TestLogging.logWebStep(null, "assert text \"" + text + "\" is present.(ignore case)", false); assertHTML(getBodyText().toLowerCase().contains(text.toLowerCase()), "Text= {" + text + "} not found."); } public String cancelConfirmation() throws NotCurrentPageException { Alert alert = driver.switchTo().alert(); String seenText = alert.getText(); alert.dismiss(); driver.switchTo().defaultContent(); return seenText; } protected abstract void capturePageSnapshot(); public Alert getAlert() { Alert alert = driver.switchTo().alert(); return alert; } public String getAlertText() { Alert alert = driver.switchTo().alert(); String seenText = alert.getText(); return seenText; } private String getBodyText() { WebElement body = driver.findElement(By.tagName("body")); return body.getText(); } public String getConfirmation() { Alert alert = driver.switchTo().alert(); String seenText = alert.getText(); return seenText; } public WebDriver getDriver() { driver = WebUIDriver.getWebDriver(); return driver; } public String getPrompt() { Alert alert = driver.switchTo().alert(); String seenText = alert.getText(); return seenText; } public boolean isElementPresent(By by) { int count = 0; try { count = WebUIDriver.getWebDriver().findElements(by).size(); } catch (RuntimeException e) { if ((e instanceof InvalidSelectorException) || (e.getMessage() != null && e .getMessage() .contains( "TransformedEntriesMap cannot be cast to java.util.List"))) { TestLogging.log("InvalidSelectorException or CastException got, retry"); WaitHelper.waitForSeconds(2); count = WebUIDriver.getWebDriver().findElements(by).size(); } else throw e; } if (count == 0) return false; return true; } public boolean isFrame() { return false; } public boolean isTextPresent(String text) { CustomAssertion .assertNotNull(text, "isTextPresent: text should not be null!"); driver = WebUIDriver.getWebDriver(); WebElement body = driver.findElement(By.tagName("body")); if (WebUIDriver.getWebUXDriver().getBrowser() .equalsIgnoreCase(BrowserType.HtmlUnit.getBrowserType())) { return body.getText().contains(text); } Boolean result = false; if (body.getText().contains(text)) return true; JavascriptLibrary js = new JavascriptLibrary(); String script = js.getSeleniumScript("isTextPresent.js"); result = (Boolean) ((JavascriptExecutor) driver).executeScript( "return (" + script + ")(arguments[0]);", text); // Handle the null case return Boolean.TRUE == result; } public void selectFrame(By by) { TestLogging.logWebStep(null, "select frame, locator={\"" + by.toString() + "\"}", false); driver.switchTo().frame(driver.findElement(by)); } /** * If current window is closed then use driver.switchTo.window(handle) * * @param windowName * @throws com.seleniumtests.customexception.NotCurrentPageException */ public final void selectWindow(String windowName) throws NotCurrentPageException { if (windowName == null) { Windows windows = new Windows(driver); try { windows.selectBlankWindow(driver); } catch (SeleniumException e) { driver.switchTo().defaultContent(); } } else { Windows windows = new Windows(driver); windows.selectWindow(driver, "name=" + windowName); } } public void waitForElementChecked(HtmlElement element) { Assert.assertNotNull(element, "Element can't be null"); TestLogging.logWebStep(null, "wait for " + element.toString() + " to be checked.", false); WebDriverWait wait = new WebDriverWait(driver, explictWaitTimeout); wait.until(ExpectedConditions.elementToBeSelected(element.getBy())); } public void waitForElementEditable(HtmlElement element) { Assert.assertNotNull(element, "Element can't be null"); TestLogging.logWebStep(null, "wait for " + element.toString() + " to be editable.", false); WebDriverWait wait = new WebDriverWait(driver, explictWaitTimeout); wait.until(ExpectedConditions.elementToBeClickable(element.getBy())); } public void waitForElementPresent(By by) { TestLogging.logWebStep(null, "wait for " + by.toString() + " to be present.", false); WebDriverWait wait = new WebDriverWait(driver, explictWaitTimeout); wait.until(ExpectedConditions.presenceOfElementLocated(by)); } public void waitForElementPresent(By by, int timeout) { TestLogging.logWebStep(null, "wait for " + by.toString() + " to be present.", false); WebDriverWait wait = new WebDriverWait(driver, timeout); wait.until(ExpectedConditions.presenceOfElementLocated(by)); } public void waitForElementPresent(HtmlElement element) { Assert.assertNotNull(element, "Element can't be null"); TestLogging.logWebStep(null, "wait for " + element.toString() + " to be present.", false); WebDriverWait wait = new WebDriverWait(driver, explictWaitTimeout); wait.until(ExpectedConditions.presenceOfElementLocated(element.getBy())); } public void waitForElementToBeVisible(HtmlElement element) { Assert.assertNotNull(element, "Element can't be null"); TestLogging.logWebStep(null, "wait for " + element.toString() + " to be visible.", false); WebDriverWait wait = new WebDriverWait(driver, explictWaitTimeout); wait.until(ExpectedConditions.visibilityOfElementLocated(element .getBy())); } public void waitForElementToDisappear(HtmlElement element) { Assert.assertNotNull(element, "Element can't be null"); TestLogging.logWebStep(null, "wait for " + element.toString() + " to disappear.", false); WebDriverWait wait = new WebDriverWait(driver, explictWaitTimeout); wait.until(ExpectedConditions.invisibilityOfElementLocated(element .getBy())); } public void waitForPopup(String locator) throws Exception { waitForPopUp(locator, sessionTimeout + ""); } public void waitForPopUp(final String windowID, String timeout) { final long millis = Long.parseLong(timeout); final String current = driver.getWindowHandle(); final Windows windows = new Windows(driver); if (webUXDriver.getConfig().getBrowser() == BrowserType.InternetExplore) waitForSeconds(3); new Wait() { @Override public boolean until() { try { if ("_blank".equals(windowID)) { windows.selectBlankWindow(driver); } else { driver.switchTo().window(windowID); } return !"about:blank".equals(driver.getCurrentUrl()); } catch (SeleniumException e) { } catch (NoSuchWindowException e) { } return false; } }.wait(String.format("Timed out waiting for %s. Waited %s", windowID, timeout), millis); driver.switchTo().window(current); } /** * Wait For seconds. Provide a value less than WebSessionTimeout i.e. 180 * Seconds * * @param seconds */ protected void waitForSeconds(int seconds) { WaitHelper.waitForSeconds(seconds); } public void waitForTextPresent(HtmlElement element, String text) { Assert.assertNotNull(text, "Text can't be null"); TestLogging.logWebStep(null, "wait for text \"" + text + "\" to be present.", false); WebDriverWait wait = new WebDriverWait(driver, explictWaitTimeout); wait.until(ExpectedConditions.textToBePresentInElement(element.getBy(), text)); } public void waitForTextPresent(String text) { Assert.assertNotNull(text, "Text can't be null"); TestLogging.logWebStep(null, "wait for text \"" + text + "\" to be present.", false); boolean b = false; for (int millisec = 0; millisec < explictWaitTimeout * 1000; millisec += 1000) { try { if ((isTextPresent(text))) { b = true; break; } } catch (Exception ignore) { } try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage()); } } assertHTML(b, "Timed out waiting for text \"" + text + "\" to be there."); } public void waitForTextToDisappear(String text) { Assert.assertNotNull(text, "Text can't be null"); TestLogging.logWebStep(null, "wait for text \"" + text + "\" to disappear.", false); boolean textPresent = true; for (int millisec = 0; millisec < explictWaitTimeout * 1000; millisec += 1000) { try { if (!(isTextPresent(text))) { textPresent = false; break; } } catch (Exception ignore) { } try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage()); } } assertHTML(!textPresent, "Timed out waiting for text \"" + text + "\" to be gone."); } }
package com.shc.silenceengine.input; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*; /** * A class for handling polled Controller input. * * @author Sri Harsha Chilakapati * @author Josh "ShadowLordAlpha" */ public class Controller { // Generic Button Constants public static final int GENERIC_BUTTON_1 = 1; public static final int GENERIC_BUTTON_2 = 2; public static final int GENERIC_BUTTON_3 = 3; public static final int GENERIC_BUTTON_4 = 4; public static final int GENERIC_BUTTON_5 = 5; public static final int GENERIC_BUTTON_6 = 6; public static final int GENERIC_BUTTON_7 = 7; public static final int GENERIC_BUTTON_8 = 8; public static final int GENERIC_BUTTON_9 = 9; public static final int GENERIC_BUTTON_10 = 10; public static final int GENERIC_BUTTON_11 = 11; public static final int GENERIC_BUTTON_12 = 12; public static final int GENERIC_BUTTON_13 = 13; public static final int GENERIC_BUTTON_14 = 14; public static final int GENERIC_BUTTON_15 = 15; public static final int GENERIC_BUTTON_16 = 16; public static final int GENERIC_BUTTON_17 = 17; public static final int GENERIC_BUTTON_18 = 18; public static final int GENERIC_BUTTON_19 = 19; public static final int GENERIC_BUTTON_20 = 20; public static final int GENERIC_BUTTON_21 = 21; public static final int GENERIC_BUTTON_22 = 22; public static final int GENERIC_BUTTON_23 = 23; public static final int GENERIC_BUTTON_24 = 24; public static final int GENERIC_BUTTON_25 = 25; public static final int GENERIC_BUTTON_26 = 26; public static final int GENERIC_BUTTON_27 = 27; public static final int GENERIC_BUTTON_28 = 28; public static final int GENERIC_BUTTON_29 = 29; public static final int GENERIC_BUTTON_30 = 30; public static final int GENERIC_BUTTON_31 = 31; // Named generic buttons public static final int GENERIC_BUTTON_L1 = 5; public static final int GENERIC_BUTTON_L2 = 7; public static final int GENERIC_BUTTON_R1 = 6; public static final int GENERIC_BUTTON_R2 = 8; public static final int GENERIC_BUTTON_SELECT = 9; public static final int GENERIC_BUTTON_START = 10; // Generic D-PAD constants, You need to optimize for other controllers public static final int GENERIC_DPAD_UP = 13; public static final int GENERIC_DPAD_RIGHT = 14; public static final int GENERIC_DPAD_DOWN = 15; public static final int GENERIC_DPAD_LEFT = 16; // Generic AXE constants public static final int GENERIC_AXE_LEFT_X = 1; public static final int GENERIC_AXE_LEFT_Y = 2; public static final int GENERIC_AXE_RIGHT_X = 3; public static final int GENERIC_AXE_RIGHT_Y = 4; // XBOX Button constants public static final int XBOX_BUTTON_A = 1; public static final int XBOX_BUTTON_B = 2; public static final int XBOX_BUTTON_X = 3; public static final int XBOX_BUTTON_Y = 4; public static final int XBOX_BUTTON_LB = 5; public static final int XBOX_BUTTON_RB = 6; public static final int XBOX_BUTTON_BACK = 7; public static final int XBOX_BUTTON_START = 8; public static final int XBOX_BUTTON_LS = 9; public static final int XBOX_BUTTON_RS = 10; public static final int XBOX_DPAD_UP = 11; public static final int XBOX_DPAD_RIGHT = 12; public static final int XBOX_DPAD_DOWN = 13; public static final int XBOX_DPAD_LEFT = 14; // XBOX AXE constants public static final int XBOX_LEFT_STICKER_X = 1; public static final int XBOX_LEFT_STICKER_Y = 2; public static final int XBOX_SHOULDER_TRIGGER = 3; public static final int XBOX_RIGHT_STICKER_Y = 4; public static final int XBOX_RIGHT_STICKER_X = 5; // PS3 Button constants public static final int PS3_BUTTON_SELECT = 0; public static final int PS3_BUTTON_LEFT_JS = 1; public static final int PS3_BUTTON_RIGHT_JS = 2; public static final int PS3_BUTTON_START = 3; public static final int PS3_DPAD_UP = 4; public static final int PS3_DPAD_RIGHT = 5; public static final int PS3_DPAD_DOWN = 6; public static final int PS3_DPAD_LEFT = 7; public static final int PS3_BUTTON_L2 = 8; public static final int PS3_BUTTON_R2 = 9; public static final int PS3_BUTTON_L1 = 10; public static final int PS3_BUTTON_R1 = 11; public static final int PS3_BUTTON_TRIANGLE = 12; public static final int PS3_BUTTON_CIRCLE = 13; public static final int PS3_BUTTON_CROSS = 14; public static final int PS3_BUTTON_SQUARE = 15; public static final int PS3_BUTTON_PS = 16; // PS3 AXE constants public static final int PS3_AXE_LS_X = 0; public static final int PS3_AXE_LS_Y = 1; public static final int PS3_AXE_RS_X = 2; public static final int PS3_AXE_RS_Y = 3; // TODO: Add PS4 controller mappings too private static Controller[] controllers; private int id; private String name; private int numButtons; private int numAxes; private Type type; private Map<Integer, Boolean> buttons; private Map<Integer, Float> axes; private Map<Integer, Float> axesThisFrame; private Map<Integer, Float> axesLastFrame; private Map<Integer, Boolean> buttonsThisFrame; private Map<Integer, Boolean> buttonsLastFrame; /** * Constructs a controller object that represents a single joystick that is connected to the system. A controller * has a unique ID (GLFWjoystick*) and a name. There is no guarantee GLFW makes that this name is unique, because it * is the name of the driver that the OS uses to interface with the controller. * * @param id The unique ID of the joystick. It is the number of the joystick, starting from 0. * @param name The name of the driver that is used to interface with the controller hardware. */ private Controller(int id, String name) { this.id = id; this.name = name; buttons = new HashMap<>(); axes = new HashMap<>(); buttonsThisFrame = new HashMap<>(); buttonsLastFrame = new HashMap<>(); axesThisFrame = new HashMap<>(); axesLastFrame = new HashMap<>(); // Calculate the number of buttons of this controller ByteBuffer buttons = glfwGetJoystickButtons(id); while (buttons.hasRemaining()) { numButtons++; buttons.get(); } // Calculate the number of axes of this controller FloatBuffer axes = glfwGetJoystickAxes(id); while (axes.hasRemaining()) { numAxes++; axes.get(); } // Decide the controller type if (name.equalsIgnoreCase("Wireless Controller") && numButtons == 18) type = Type.PS4; else if (name.equalsIgnoreCase("PLAYSTATION(R)3 Controller") && numButtons == 19) type = Type.PS3; else if (name.equalsIgnoreCase("Controller") && numButtons == 15) type = Type.XBOX; else type = Type.GENERIC; } /** * poll all controllers for input */ public static void poll() { for (Controller controller : controllers) controller.pollValues(); } /** * Call <code>startFrame();</code> on all known connected controllers */ public static void startEventFrame() { for (Controller controller : controllers) controller.startFrame(); } /** * Call <code>clearFrame();</code> on all known connected controllers */ public static void clearEventFrame() { for (Controller controller : controllers) controller.clearFrame(); } /** * Gets a list of all known connected controllers * * @return A list of all known connected controllers */ public static Controller[] getConnectedControllers() { return controllers; } /** * Gets if the button has been pressed this event frame on the controller * * @param button The button * @param controller The controller * * @return True if the button has been pressed this event frame on the controller */ public static boolean isPressed(int button, int controller) { if (controllers == null) create(); return controller < controllers.length && controllers[controller].isPressed(button); } /** * Generate a list of controllers that are able to be used */ public static void create() { // Create a list to store the controllers List<Controller> controllerList = new ArrayList<>(); // Iterate over all the controllers GLFW supports for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++) { // If the controller is present, add it to the list if (glfwJoystickPresent(i) == GL_TRUE) { String name = glfwGetJoystickName(i); controllerList.add(new Controller(i, name)); } } // Turn the list into an array controllers = new Controller[controllerList.size()]; controllers = controllerList.toArray(controllers); } /** * Gets if the button has been pressed in this event frame and not the frame before on the controller * * @param button The button * @param controller The controller * * @return true if the button has been pressed in this event frame and not the frame before on the controller */ public static boolean isClicked(int button, int controller) { if (controllers == null) create(); return controller < controllers.length && controllers[controller].isClicked(button); } /** * Gets the current value on the axis for the controller * * @param axe The axis * @param controller The ID of the controller, starting from 0. * * @return The current value on the axis for the controller */ public static float getAxe(int axe, int controller) { if (controllers == null) create(); return controller < controllers.length ? controllers[controller].getAxe(axe) : 0; } /** * Whether the axis is on or not for the controller * * @param axe The axis * @param controller The ID of the controller, starting from 0. * * @return Whether the axis is on or not for the controller */ public static float getClickAxe(int axe, int controller) { if (controllers == null) create(); return controller < controllers.length ? controllers[controller].getClickAxe(axe) : 0; } /** * Polls the controller for input as well as checks to see if the controller is still active */ private void pollValues() { // Check if controller is still plugged in if (!isPresent()) { buttons.keySet().forEach(i -> buttons.put(i, false)); axes.keySet().forEach(i -> axes.put(i, 0f)); return; } // Poll the buttons ByteBuffer buttons = glfwGetJoystickButtons(id); int buttonID = 0; while (buttons.hasRemaining()) { buttonID++; this.buttons.put(buttonID, buttons.get() == 1); } // Poll the axes FloatBuffer axes = glfwGetJoystickAxes(id); int axeID = 0; while (axes.hasRemaining()) { axeID++; float value = axes.get(); if (value > -0.15 && value < 0.15) value = 0; this.axes.put(axeID, value); } } /** * Gets if the controller is still connected * * @return true if the controller is still connected */ public boolean isPresent() { return glfwJoystickPresent(id) == GL_TRUE; } /** * Remove all events from the current event frame and add all events from the event buffer into the current event * frame */ private void startFrame() { buttonsThisFrame.clear(); buttonsThisFrame.putAll(buttons); axesThisFrame.clear(); axesThisFrame.putAll(axes); } /** * Remove all events from the last frame and move all events from the current event frame into the last frame list. */ private void clearFrame() { buttonsLastFrame.clear(); buttonsLastFrame.putAll(buttonsThisFrame); axesLastFrame.clear(); axesLastFrame.putAll(axesThisFrame); } /** * Gets if the button has been pressed this event frame * * @param button The button * * @return true if the button has been pressed this event frame */ public boolean isPressed(int button) { if (!buttonsLastFrame.containsKey(button)) buttonsLastFrame.put(button, false); if (!buttonsThisFrame.containsKey(button)) buttonsThisFrame.put(button, false); return buttonsLastFrame.get(button) || buttonsThisFrame.get(button); } /** * Gets if the button has been pressed in this event frame and not the frame before * * @param button The button * * @return true if the button has been pressed in this event frame and not the frame before */ public boolean isClicked(int button) { if (!buttonsLastFrame.containsKey(button)) buttonsLastFrame.put(button, false); if (!buttonsThisFrame.containsKey(button)) buttonsThisFrame.put(button, false); return buttonsThisFrame.get(button) && !buttonsLastFrame.get(button); } /** * Gets the current value on the axis * * @param axe The axis * * @return The current value on the axis */ public float getAxe(int axe) { return axes.get(axe); } /** * Whether the axis is on or not * * @param axe The axis * * @return Whether the axis is on or not */ public float getClickAxe(int axe) { if (axesLastFrame.get(axe) != 0) return 0; return axesThisFrame.get(axe); } /** * Debug method to see button and axis presses on a controller this is the same as calling * <code>printValues(false);</code> */ public void printValues() { printValues(false); } /** * Debug method to see button and axis presses on a controller * * @param repeat If true, the values are printed even if the button or axis is pressed and held down. */ public void printValues(boolean repeat) { buttons.keySet().forEach(i -> { boolean condition = repeat ? isPressed(i) : isClicked(i); if (condition) System.out.println("Button " + i + " down"); }); axes.keySet().forEach(i -> { float value = repeat ? getAxe(i) : getClickAxe(i); if (value != 0) System.out.println("Axe " + i + ": " + value); }); } /** * Gets the ID of the controller * * @return The ID of the controller */ public int getId() { return id; } /** * Gets the name of the controller * * @return The name of the controller */ public String getName() { return name; } /** * Gets the number of buttons on the controller * * @return The number of button on the controller */ public int getNumButtons() { return numButtons; } /** * Gets the number of axes the controller has * * @return The number of axes the controller has */ public int getNumAxes() { return numAxes; } /** * Gets the type of controller * * @return The type of controller */ public Type getType() { return type; } /** * Enum denoting the different types of controllers */ public enum Type { PS3, PS4, XBOX, GENERIC } }
package com.sibilantsolutions.grison; import java.net.InetSocketAddress; import org.reactivestreams.Subscription; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sibilantsolutions.grison.driver.foscam.dto.CommandDto; import com.sibilantsolutions.grison.driver.foscam.dto.SearchReqTextDto; import com.sibilantsolutions.grison.net.netty.SearchChannelInitializer; import com.sibilantsolutions.grison.net.netty.codec.FoscamTextByteBufDTOEncoder; import com.sibilantsolutions.grison.net.netty.codec.SearchReqTextDtoEncoder; import com.sibilantsolutions.grison.net.netty.codec.dto.FoscamTextByteBufDTO; import com.sibilantsolutions.grison.net.retrofit.CgiRetrofitService; import com.sibilantsolutions.grison.net.retrofit.FoscamInsecureAuthInterceptor; import com.sibilantsolutions.grison.net.retrofit.HttpResult; import com.sibilantsolutions.grison.net.retrofit.RetrofitResultToHttpResult; import com.sibilantsolutions.grison.rx.State; import com.sibilantsolutions.grison.rx.event.action.AbstractAction; import com.sibilantsolutions.grison.rx.event.result.AbstractResult; import com.sibilantsolutions.grison.rx.event.result.AudioVideoReceiveResult; import com.sibilantsolutions.grison.rx.event.result.OperationReceiveResult; import com.sibilantsolutions.grison.rx.event.ui.ConnectUiEvent; import com.sibilantsolutions.grison.rx.event.ui.UiEvent; import com.sibilantsolutions.grison.rx.event.xform.AbstractActionToAbstractResult; import com.sibilantsolutions.grison.rx.event.xform.CommandToAudioVideoReceiveResult; import com.sibilantsolutions.grison.rx.event.xform.CommandToOperationReceiveResult; import com.sibilantsolutions.grison.rx.event.xform.StateAndResultToStateBiFunction; import com.sibilantsolutions.grison.rx.event.xform.StateToState; import com.sibilantsolutions.grison.rx.event.xform.UiEventToAbstractAction; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.DatagramPacket; import io.netty.channel.socket.nio.NioDatagramChannel; import io.reactivex.Flowable; import io.reactivex.FlowableSubscriber; import io.reactivex.Observer; import io.reactivex.Single; import io.reactivex.SingleObserver; import io.reactivex.disposables.Disposable; import io.reactivex.processors.FlowableProcessor; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.Result; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; public class NettyDemo { private static final Logger LOG = LoggerFactory.getLogger(NettyDemo.class); private static final String BROADCAST_ADDRESS = "255.255.255.255"; private static final int BROADCAST_PORT = 10_000; void go(String host, int port, String username, String password) { go11(host, port, username, password) .subscribe(new LogSubscriber<>()); // search(); // cgi(cgiRetrofitService(retrofit(host, port, username, password))); } public static Flowable<State> go11(String host, int port, String username, String password) { Flowable<UiEvent> events = Flowable.just(new ConnectUiEvent(host, port)); //TODO: Handle upstream socket disconnect. Flowable<AbstractAction> uiEventsToActions = events .compose(new UiEventToAbstractAction()); final FlowableProcessor<AbstractAction> dynamicActions = PublishProcessor.<AbstractAction>create().toSerialized(); Flowable<AbstractAction> actions = Flowable .merge( uiEventsToActions, dynamicActions); final FlowableProcessor<CommandDto> operationDatastream = PublishProcessor.<CommandDto>create().toSerialized(); final FlowableProcessor<CommandDto> audioVideoDatastream = PublishProcessor.<CommandDto>create().toSerialized(); final Flowable<OperationReceiveResult> operationReceiveResults = operationDatastream .observeOn(Schedulers.io()) .compose(new CommandToOperationReceiveResult()); final Flowable<AudioVideoReceiveResult> audioVideoReceiveResults = audioVideoDatastream .observeOn(Schedulers.io()) .compose(new CommandToAudioVideoReceiveResult()); final Flowable<AbstractResult> actionResults = actions .compose(new AbstractActionToAbstractResult(operationDatastream, audioVideoDatastream)); Flowable<AbstractResult> results = Flowable.merge( actionResults, operationReceiveResults, audioVideoReceiveResults); Flowable<State> states = results .scanWith( () -> State.INITIAL, new StateAndResultToStateBiFunction()); states = states .compose(new StateToState(dynamicActions, username, password)); // states // //TODO: Pretend UI disabled video, but only if it was validly connected, after some period of time. //// .observeOn(Schedulers.io()) // .subscribe(new LogSubscriber<>()); return states; } private void search() { EventLoopGroup group = new NioEventLoopGroup(); final Bootstrap bootstrap = new Bootstrap(); bootstrap .group(group) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new SearchChannelInitializer(group)); try { final Channel channel = bootstrap .bind(50_080) //TODO Use 0 for a random port; but firewall needs to be open to receive response. .sync() .channel(); LOG.info("{} got channel.", channel); final SearchReqTextDto searchReqTextDto = SearchReqTextDto.builder().build(); final FoscamTextByteBufDTO foscamTextByteBufDTO = FoscamTextByteBufDTO.create(searchReqTextDto.opCode(), SearchReqTextDtoEncoder.encode(searchReqTextDto, channel.alloc().buffer(searchReqTextDto.encodedLength(), searchReqTextDto.encodedLength()))); int len = CommandDto.COMMAND_PREFIX_LENGTH + searchReqTextDto.encodedLength(); final ByteBuf buffer = channel.alloc().buffer(len, len); new FoscamTextByteBufDTOEncoder().encode(null, foscamTextByteBufDTO, buffer); channel .writeAndFlush( new DatagramPacket( buffer, new InetSocketAddress(BROADCAST_ADDRESS, BROADCAST_PORT))) .addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { LOG.info("{} Wrote the msg.", future.channel()); } else { LOG.error("Trouble: ", future.cause()); } }); } catch (InterruptedException e) { throw new UnsupportedOperationException("TODO (CSB)", e); } // } finally { // LOG.info("{} Shutting down.", group); // group.shutdownGracefully(); } private void cgi(CgiRetrofitService cgiRetrofitService) { // final Flowable<Response<String>> resultSingle = cgiRetrofitService.checkUser(username, password); // final Single<Result<String>> resultSingle = cgiRetrofitService.irOff(); // final Single<Result<String>> resultSingle = cgiRetrofitService.irAuto(); // final Single<Result<String>> resultSingle = cgiRetrofitService.up(); // final Single<Result<String>> resultSingle = cgiRetrofitService.up(80); // final Single<Result<String>> resultSingle = cgiRetrofitService.upOneStep(); // final Single<Result<String>> resultSingle = cgiRetrofitService.down(); // final Single<Result<String>> resultSingle = cgiRetrofitService.down(150); // final Single<Result<String>> resultSingle = cgiRetrofitService.left(80); // final Single<Result<String>> resultSingle = cgiRetrofitService.right(); final Single<Result<String>> resultSingle = cgiRetrofitService.center(); // final Single<Result<String>> resultSingle = cgiRetrofitService.goToPreset1(); // final Single<Result<String>> resultSingle = cgiRetrofitService.goToPreset2(); // final Completable ans = cgiRetrofitService.irOff(username, password); // .toFlowable(); // final Flowable<Response<String>> resultSingle = cgiRetrofitService.checkUserOmitAuth(); final Single<HttpResult<String>> result = resultSingle .compose(new RetrofitResultToHttpResult<>()); final Flowable<HttpResult<String>> httpResultFlowable = result .toFlowable() .startWith(HttpResult.inFlight()); httpResultFlowable .subscribe(new LogSubscriber<>()); } public static CgiRetrofitService cgiRetrofitService(Retrofit retrofit) { return retrofit.create(CgiRetrofitService.class); } public static Retrofit retrofit(String host, int port, String username, String password) { //TODO: Dedicated HTTP logger; use Markers; use Trace level. HttpLoggingInterceptor logging = new HttpLoggingInterceptor(LOG::debug); // set your desired log level logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new FoscamInsecureAuthInterceptor(username, password)); // add logging as last interceptor httpClient.addInterceptor(logging); return new Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync()) .addConverterFactory(ScalarsConverterFactory.create()) .baseUrl(String.format("http://%s:%d", host, port)) .client(httpClient.build()) .build(); } private static class LogSingleObserver<T> implements SingleObserver<T> { @Override public void onSubscribe(Disposable d) { LOG.info("onSubscribe disposable={}.", d); } @Override public void onSuccess(T t) { LOG.info("onSuccess item={}.", t); } @Override public void onError(Throwable e) { LOG.error("onError: ", new RuntimeException(e)); } } private static class LogObserver<T> implements Observer<T> { @Override public void onSubscribe(Disposable d) { LOG.info("onSubscribe disposable={}.", d); } @Override public void onNext(T t) { LOG.info("onNext item={}.", t); } @Override public void onError(Throwable e) { LOG.error("onError: ", new RuntimeException(e)); } @Override public void onComplete() { LOG.info("onComplete."); } } private static class LogSubscriber<T> implements FlowableSubscriber<T> { private Subscription s; @Override public void onSubscribe(Subscription s) { LOG.info("onSubscribe subscription={}.", s); this.s = s; this.s.request(60); } @Override public void onNext(T t) { LOG.info("onNext item={}.", t); s.request(60); } @Override public void onError(Throwable t) { LOG.error("onError:", new RuntimeException(t)); } @Override public void onComplete() { LOG.info("onComplete."); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.wizzardo.http.framework; import com.wizzardo.http.Session; import com.wizzardo.http.framework.di.DependencyScope; import com.wizzardo.http.framework.di.Injectable; import com.wizzardo.http.framework.template.Model; import com.wizzardo.http.framework.template.Renderer; import com.wizzardo.http.framework.template.TextRenderer; import com.wizzardo.http.framework.template.ViewRenderer; import com.wizzardo.http.request.Parameters; import com.wizzardo.http.request.Request; import com.wizzardo.http.response.Response; import com.wizzardo.http.response.Status; /** * @author Moxa */ @Injectable(scope = DependencyScope.PROTOTYPE) public abstract class Controller { protected Request request; protected Response response; protected String name; protected Model model; public Model model() { if (model == null) model = new Model(); return model; } public Parameters params() { return request.params(); } public Parameters getParams() { return request.params(); } public Session session() { return request.session(); } public Session getSession() { return request.session(); } public Renderer renderView(String view) { return new ViewRenderer(model(), name(), view); } public Renderer renderTemplate(String template) { return new ViewRenderer(model(), template); } public Renderer renderString(String s) { return new TextRenderer(s); } public Renderer redirect(String url) { return redirect(url, Status._302); } public Renderer redirect(String url, Status status) { response.setStatus(status); response.setHeader("Location", url); return null; } public String name() { if (name != null) return name; name = getControllerName(getClass()); return name; } static String getControllerName(Class<? extends Controller> clazz) { String controllerName = clazz.getSimpleName(); if (controllerName.endsWith("Controller")) controllerName = controllerName.substring(0, controllerName.length() - "Controller".length()); controllerName = controllerName.substring(0, 1).toLowerCase() + controllerName.substring(1); return controllerName; } public String getName() { return name(); } }
package coyote.dataframe.marshal; import java.io.BufferedWriter; import java.io.IOException; import java.io.StringWriter; import java.util.List; import coyote.dataframe.DataField; import coyote.dataframe.DataFrame; import coyote.dataframe.marshal.json.JsonFrameParser; import coyote.dataframe.marshal.json.JsonWriter; import coyote.dataframe.marshal.json.WriterConfig; public class JSONMarshaler { /** * Marshal the given JSON into a dataframe. * * @param json * * @return Data frame containing the JSON represented data */ public static List<DataFrame> marshal( final String json ) throws MarshalException { List<DataFrame> retval = null; try { retval = new JsonFrameParser( json ).parse(); } catch ( final Exception e ) { System.out.println( "oops: " + e.getMessage() ); throw new MarshalException( "Could not marshal JSON to DataFrame", e ); } return retval; } /** * Generate a JSON string from the given data frame. * * @param frame The frame to marshal * * @return A JSON formatted string which can be marshaled back into a frame */ public static String marshal( final DataFrame frame ) { return write( frame, WriterConfig.MINIMAL ); } /** * Generate a nicely formatted (and indented) JSON string from the given data frame. * * @param frame The frame to marshal * * @return A JSON formatted string which can be marshaled back into a frame */ public static String toFormattedString( final DataFrame frame ) { return write( frame, WriterConfig.PRETTY_PRINT ); } /** * @param frame * @param config * @return */ private static String write( final DataFrame frame, final WriterConfig config ) { // create string writer final StringWriter sw = new StringWriter(); final BufferedWriter bw = new BufferedWriter( sw ); final JsonWriter writer = config.createWriter( bw ); try { writeFrame( frame, writer ); bw.flush(); } catch ( IOException e ) { return "[\"" + e.getMessage() + "\"]"; } return sw.getBuffer().toString(); } /** * * @param frame * @param config * * @return * @throws IOException */ private static void writeFrame( final DataFrame frame, final JsonWriter writer ) throws IOException { if( frame == null || writer == null){ return; } if ( frame.size() > 0 ) { boolean isArray = frame.isArray(); if ( isArray ) writer.writeArrayOpen(); else writer.writeObjectOpen(); DataField field = null; for ( int i = 0; i < frame.size(); i++ ) { field = frame.getField( i ); if ( !isArray ) { if ( field.getName() != null ) { writer.writeString( field.getName() ); } else { writer.writeString( "" ); } writer.writeMemberSeparator(); } if ( field.getType() == DataField.NULLTYPE ) { writer.writeLiteral( "null" ); } else if ( field.getType() == DataField.BOOLEANTYPE ) { if ( "true".equalsIgnoreCase( field.getStringValue() ) ) { writer.writeLiteral( "true" ); } else { writer.writeLiteral( "false" ); } } else if ( field.isNumeric() ) { writer.writeNumber( field.getStringValue() ); } else if ( field.getType() == DataField.FRAMETYPE ) { writeFrame( (DataFrame)field.getObjectValue(), writer ); } else { writer.writeString( field.getObjectValue().toString() ); } if ( i + 1 < frame.size() ) { writer.writeObjectSeparator(); } } if ( isArray ) writer.writeArrayClose(); else writer.writeObjectClose(); } else { writer.writeObjectOpen(); writer.writeObjectClose(); } return; } }
package de.oetting.kata.diamond; public class DiamondPrinter { public String print(char character) { String upperHalf = createUpperHalf(character); String middleLine = createMiddleLine(character); String lowerHalf = createLowerHalf(character); return upperHalf + middleLine + lowerHalf; } private String createUpperHalf(char character) { String result = ""; for (int i = 0; i < getNumberOfDifferentCharacters(character) - 1; i++) { result += createOutputLine(i, character) + '\n'; } return result; } private String createMiddleLine(char character) { String line = createOutputLine(getNumberOfDifferentCharacters(character) - 1, character); if (getNumberOfDifferentCharacters(character) == 1) return line; return line + '\n'; } private String createLowerHalf(char character) { String result = ""; for (int i = getNumberOfDifferentCharacters(character) - 2; i >= 0; i result += createOutputLine(i, character); if (createNthCharacter(i) != 'A') result += '\n'; } return result; } private char createNthCharacter(int i) { return (char) ('A' + i); } private String createOutputLine(int characterIndex, char inputCharacter) { if (characterIndex == 0) return createTextForA(getNumberOfDifferentCharacters(inputCharacter)); return createOutputLineForNonA(createNthCharacter(characterIndex), getNumberOfDifferentCharacters(inputCharacter)); } private String createOutputLineForNonA(char c, int numberOfCharacters) { String spacesBefore = createNumberOfSpacesSpaces(numberOfCharacters - (c - 'A') - 1); String characterPlusSpacesBetween = c + createNumberOfSpacesSpaces((c - 'A') * 2 - 1) + c; return spacesBefore + characterPlusSpacesBetween; } // This is a special method for A because this will be the only line which // only contains one character private String createTextForA(int numberOfCharacters) { String spaces = createNumberOfSpacesSpaces(numberOfCharacters - 1); return spaces + "A"; } private String createNumberOfSpacesSpaces(int times) { String result = ""; for (int i = 0; i < times; i++) result += ' '; return result; } private int getNumberOfDifferentCharacters(char character) { return character - 'A' + 1; } }
package fi.csc.microarray.analyser; import java.util.Date; import org.apache.log4j.Logger; import fi.csc.microarray.messaging.JobState; import fi.csc.microarray.messaging.message.JobMessage; import fi.csc.microarray.messaging.message.ResultMessage; import fi.csc.microarray.util.Exceptions; public abstract class AnalysisJob implements Runnable { public static String SCRIPT_SUCCESSFUL_STRING = "script-finished-succesfully"; public static String SCRIPT_FAILED_STRING = "script-finished-unsuccesfully"; public final String ERROR_MESSAGE_TOKEN = "Error"; public final String CHIPSTER_NOTE_TOKEN = "CHIPSTER-NOTE:"; private static final Logger logger = Logger.getLogger(AnalysisJob.class); protected JobMessage inputMessage; protected ResultCallback resultHandler; protected ToolDescription analysis; private Date receiveTime; private Date scheduleTime; private Date executionStartTime; private Date executionEndTime; private boolean constructed = false; private JobState state; private String stateDetail; private boolean toBeCanceled = false; protected ResultMessage outputMessage; public AnalysisJob() { this.state = JobState.NEW; this.stateDetail = "new job created."; } public void construct(JobMessage inputMessage, ToolDescription analysis, ResultCallback resultHandler) { this.constructed = true; this.analysis = analysis; this.inputMessage = inputMessage; this.resultHandler = resultHandler; // initialize result message outputMessage = new ResultMessage(); outputMessage.setJobId(this.getId()); outputMessage.setReplyTo(inputMessage.getReplyTo()); outputMessage.setState(this.state); outputMessage.setStateDetail(this.stateDetail); } /** * Run the job. After execution, job should report results * through the ResultCallback interface. */ public void run() { try { if (!constructed) { throw new IllegalStateException("you must call construct(...) first"); } // before execute preExecute(); // execute if (this.getState() == JobState.RUNNING) { this.setExecutionStartTime(new Date()); execute(); this.setExecutionEndTime(new Date()); } // after execute if (this.getState() == JobState.RUNNING) { postExecute(); } // successful job if (this.getState() == JobState.RUNNING) { // update state and send results this.state = JobState.COMPLETED; this.stateDetail = ""; } // send the result message // for the unsuccessful jobs, the state has been set by the subclass outputMessage.setState(this.state); outputMessage.setStateDetail(this.stateDetail); resultHandler.sendResultMessage(inputMessage, outputMessage); } // job cancelled, do nothing catch (JobCancelledException jce) { this.setExecutionEndTime(new Date()); logger.debug("job cancelled: " + this.getId()); } // something unexpected happened catch (Throwable e) { this.setExecutionEndTime(new Date()); updateState(JobState.ERROR, "running tool failed"); outputMessage.setErrorMessage("Running tool failed."); outputMessage.setOutputText(Exceptions.getStackTrace(e)); outputMessage.setState(this.state); outputMessage.setStateDetail(this.stateDetail); resultHandler.sendResultMessage(inputMessage, outputMessage); } // clean up finally { try { cleanUp(); } catch (Throwable t) { logger.error("Error when cleaning up.", t); } resultHandler.removeRunningJob(this); } } public String getId() { return this.inputMessage.getJobId(); } public synchronized void updateState(JobState newState, String stateDetail) { // don't allow new state changes, if this is cancelled already if (getState() == JobState.CANCELLED) { return; } // update state this.state = newState; this.stateDetail = stateDetail; } /** * Updates the state detail and also sends the state and the detail * to the client. * * @param newStateDetail */ public synchronized void updateStateDetailToClient(String newStateDetail) { // job may continue for some time before it checks if it's cancelled if (getState() == JobState.CANCELLED) { return; } // update state this.stateDetail = newStateDetail; // send notification message outputMessage.setState(this.state); outputMessage.setStateDetail(this.stateDetail); resultHandler.sendResultMessage(inputMessage, outputMessage); } public synchronized void updateStateToClient() { this.updateStateToClient(this.state, this.stateDetail, true); } public synchronized void updateStateToClient(JobState newState, String stateDetail) { this.updateStateToClient(newState, stateDetail, false); } public synchronized void updateStateToClient(JobState newState, String stateDetail, boolean isHeartbeat) { // job may continue for some time before it checks if it's cancelled if (getState() == JobState.CANCELLED) { return; } // update state this.state = newState; this.stateDetail = stateDetail; // send notification message outputMessage.setState(this.state); outputMessage.setStateDetail(this.stateDetail); outputMessage.setHeartbeat(isHeartbeat); resultHandler.sendResultMessage(inputMessage, outputMessage); } public JobState getState() { return this.state; } /** * Request the job to be canceled. The job is not canceled immediately. Instead it is * flagged to be canceled and will cancel as soon as possible. * */ public void cancel() { logger.debug("Canceling job " + getId()); this.toBeCanceled = true; updateState(JobState.CANCELLED, ""); cancelRequested(); } /** * Check if the job should be canceled (cancel() has been called), and if needed * updates the state and cancels the job by throwing the cancellation exception. * * Should be called by subclasses in situations where it is safe to cancel the job. * * * @throws JobCancelledException */ protected void cancelCheck() throws JobCancelledException { if (toBeCanceled) { throw new JobCancelledException(); } } /** * Will be called when the job is canceled using the cancel() method. * * Subclasses should override this method with actions that should be taken * immediately when cancel is requested. * */ protected abstract void cancelRequested(); protected abstract void execute() throws JobCancelledException; protected void preExecute() throws JobCancelledException { if (!constructed) { throw new IllegalStateException("you must call construct(...) first"); } updateStateToClient(JobState.RUNNING, "initialising"); } protected void postExecute() throws JobCancelledException { } protected void cleanUp() { } public JobMessage getInputMessage() { return inputMessage; } public ResultMessage getResultMessage() { return outputMessage; } public Date getReceiveTime() { return receiveTime; } public void setReceiveTime(Date receiveTime) { this.receiveTime = receiveTime; } public Date getScheduleTime() { return scheduleTime; } public void setScheduleTime(Date scheduleTime) { this.scheduleTime = scheduleTime; } public Date getExecutionStartTime() { return executionStartTime; } public void setExecutionStartTime(Date executionStartTime) { this.executionStartTime = executionStartTime; } public Date getExecutionEndTime() { return executionEndTime; } public void setExecutionEndTime(Date executionEndTime) { this.executionEndTime = executionEndTime; } public String getStateDetail() { return this.stateDetail; } }
package foodtruck.server; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.Singleton; import org.codehaus.jettison.json.JSONException; import org.joda.time.LocalDate; import foodtruck.dao.ConfigurationDAO; import foodtruck.dao.LocationDAO; import foodtruck.model.DailySchedule; import foodtruck.model.Location; import foodtruck.model.TruckStop; import foodtruck.server.resources.json.DailyScheduleWriter; import foodtruck.server.resources.json.JSONSerializer; import foodtruck.truckstops.FoodTruckStopService; import foodtruck.util.Clock; /** * @author aviolette * @since 8/27/14 */ @Singleton public class BoozeAndTrucksServlet extends FrontPageServlet { private static final String JSP = "/WEB-INF/jsp/booze.jsp"; private final Clock clock; private final FoodTruckStopService stopService; private final DailyScheduleWriter dailyScheduleWriter; private final LocationDAO locationDAO; @Inject public BoozeAndTrucksServlet(ConfigurationDAO configDAO, FoodTruckStopService stopService, Clock clock, DailyScheduleWriter scheduleWriter, LocationDAO locationDAO) { super(configDAO); this.stopService = stopService; this.clock = clock; this.dailyScheduleWriter = scheduleWriter; this.locationDAO = locationDAO; } @Override protected void doGetProtected(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ImmutableList.Builder<ScheduleForDay> schedules = ImmutableList.builder(); LocalDate currentDay = null; Map<String, TruckStopGroup> tsgs = Maps.newHashMap(); for (TruckStop stop : stopService.findBoozeStopsForWeek(clock.firstDayOfWeek())) { if (currentDay != null && !stop.getStartTime().toLocalDate().equals(currentDay) && !tsgs.isEmpty()) { schedules.add(new ScheduleForDay(currentDay, ImmutableList.copyOf(tsgs.values()))); tsgs = Maps.newHashMap(); } TruckStopGroup tsg = tsgs.get(stop.getLocation().getName()); if (tsg == null) { tsg = new TruckStopGroup(stop.getLocation()); tsgs.put(stop.getLocation().getName(), tsg); } tsg.addStop(stop); currentDay = stop.getStartTime().toLocalDate(); } if (!tsgs.isEmpty()) { schedules.add(new ScheduleForDay(currentDay, ImmutableList.copyOf(tsgs.values()))); } req.setAttribute("daySchedules", schedules.build()); req.getRequestDispatcher(JSP).forward(req, resp); } public static class TruckStopGroup { private Location location; private List<TruckStop> stops = Lists.newLinkedList(); public TruckStopGroup(Location location) { this.location = location; } public Location getLocation() { return location; } public List<TruckStop> getStops() { return stops; } public void addStop(TruckStop stop) { this.stops.add(stop); } } public static class ScheduleForDay { private final LocalDate day; private final List<TruckStopGroup> groups; public ScheduleForDay(LocalDate day, List<TruckStopGroup> groups) { this.day = day; this.groups = groups; } public List<TruckStopGroup> getGroups() { return groups; } public LocalDate getDay() { return day; } } }
package football.core; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import static com.google.common.base.Preconditions.checkPositionIndex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import football.players.*; // for creating DEFAULT_RULES import football.players.modes.Mode; import football.stats.Rule; // for creating DEFAULT_RULES import football.stats.RuleMap; import football.stats.StatType; import football.stats.categories.*; import football.util.logging.ResultsLogger; import football.util.metrics.Metric; import football.util.metrics.SortOrderMetric; public final class CustomScoringHelperModel { private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); // rule map containing default rules, according to NFL.com private static final RuleMap DEFAULT_RULES = initDefaultRuleMap(); private static final Mode DEFAULT_MODE = Mode.QB; //TODO: make these maps map to List<E extends Player> if we drop Mode.ALL //TODO: make these lists static? // map of player modes to corresponding lists of players private Map<Mode,List<Player>> modesToPlayersMap; // copy of the above map containing copy player lists private Map<Mode,List<Player>> modesToPlayersMap2; private RuleMap currentRules; private Mode currentMode; public CustomScoringHelperModel() { logger.info("Constructing model with default mode {}", DEFAULT_MODE.toString()); currentMode = DEFAULT_MODE; // init to default rules (don't simply assign to prevent DEFAULT_RULES from being // modified whenever currentRules is modified) currentRules = initDefaultRuleMap(); modesToPlayersMap = new EnumMap<Mode,List<Player>>(Mode.class); modesToPlayersMap2 = new EnumMap<Mode,List<Player>>(Mode.class); populateModesToPlayersMap(); logger.debug("Using default rule map of:\n{}", DEFAULT_RULES.toString()); } // command line version public void run(String[] args) { logger.info("Running model with args: {}", Arrays.toString(args)); checkPositionIndex(0, args.length, "mode not specified\n" + getUsage()); Mode mode = Mode.fromString(args[0]); // parse scoring rules relevant to this mode RuleMap rules = mode.parseScoringRules(args); ScoringResults results = run(mode, rules); // log results logResults(results); } // GUI version private ScoringResults run(Mode mode, RuleMap rules) { logger.info("Running model with mode and custom rules: {}\n{}", mode.toString(), rules.toString()); // get corresponding lists of players for this mode List<Player> players1 = modesToPlayersMap.get(mode); List<Player> players2 = modesToPlayersMap2.get(mode); // evaluate all players in each list with the corresponding set of rules //TODO: pass in rules for players1 instead of always using DEFAULT_RULES scorePlayers(players1,DEFAULT_RULES); scorePlayers(players2,rules); // sort players according to their scores //TODO: delay sorting until logging in ResultsLogger, as sorting done by View anyway Collections.sort(players1); logger.info("Players sorted by default rules:\n{}", players1.toString()); Collections.sort(players2); logger.info("Players sorted by custom rules:\n{}", players2.toString()); // calculate (dis)similarity between players1 and players2 Metric metric = new SortOrderMetric(); double distance = metric.distance(players1,players2); logger.info("Distance between players using {}: {}", metric.getClass().getName(), distance); // return results so that view can be updated return new ScoringResults(mode, rules, players1, players2, distance); } // run using currentMode and currentRules public ScoringResults run() { return run(currentMode, currentRules); } // write results to file filename in directory resultsDirectory public void logResults(ScoringResults results, String resultsDirectory, String filename) { String fileSeparator = System.getProperty("file.separator"); logger.info("Writing results to {}{}{}", resultsDirectory, fileSeparator, filename); try { ResultsLogger logger = new ResultsLogger(resultsDirectory,filename); logger.logResults(results); logger.close(); } catch(IOException e) { logger.error("Unable to write results: {}", e.toString()); } } // write results to default file in default directory public void logResults(ScoringResults results) { String fileSeparator = System.getProperty("file.separator"); String resultsDirectory = System.getProperty("user.dir") + fileSeparator + "results"; String filename = (results.getMode().toString() + "results.txt"); logResults(results, resultsDirectory, filename); } /* * Getters */ public RuleMap getDefaultRules() { return DEFAULT_RULES; } public Mode getDefaultMode() { return DEFAULT_MODE; } public Map<Mode,List<Player>> getModesToPlayersMap() { return modesToPlayersMap; } /* * Setters */ public void setMode(Mode mode) { currentMode = mode; } public <T extends Enum<T> & StatType> void setRule(T category, Rule<T> rule) { currentRules.put(category, rule); } public void setRules(RuleMap rules) { currentRules = rules; } // assign each player in players a score using the scoring rules in rules private void scorePlayers(List<Player> players, RuleMap rules) { for(Player player : players) { // if we're using default rules, "look up" correct score by using // the saved defaultScore of each player instead of computing the // score from scratch //TODO: NOT CORRECT -- need to implement equals() for RuleMap //TODO: consider not checking for / tracking default score if(rules.equals(DEFAULT_RULES)) { player.useDefaultScore(); } else { player.evaluate(rules); } } } // adds mappings into modes map, and then accumulates the players lists // from these mappings in order to add a mapping for mode Mode.ALL // When this method returns, both instance maps will have a mapping for every // mode in Mode private void populateModesToPlayersMap() { logger.debug("Populating map of modes to players"); // add a mapping into the modes map for every mode. // Mode.ALL is skipped as it is built up using the lists of all of // the other mappings for(Mode mode : Mode.values()) { if(mode != Mode.ALL) { addMapping(mode); } } // at this point, modes map contains a mapping for every mode // except Mode.ALL. Therefore, we build up the mapping for Mode.ALL // using the players lists from all of the other mappings List<Player> allPlayersList = new ArrayList<Player>(); List<Player> allPlayersListCopy = new ArrayList<Player>(); for(Mode mode : modesToPlayersMap.keySet()) { allPlayersList.addAll(modesToPlayersMap.get(mode)); allPlayersListCopy.addAll(modesToPlayersMap2.get(mode)); } modesToPlayersMap.put(Mode.ALL, allPlayersList); modesToPlayersMap2.put(Mode.ALL, allPlayersListCopy); } // add mapping for mode to modes map, and corresponding copy mapping to copy of modes map // Allows for dynamically populating the modes map so that we don't spend unnecessary // computation creating lists of players for modes that aren't used private void addMapping(Mode mode) { modesToPlayersMap.put(mode, createPlayersList(mode)); modesToPlayersMap2.put(mode, createPlayersList(mode)); } // creates list of players for the given mode // Note, this should only be used in conjunction with addMapping() to create a // modes to players map in the class' constructor private static List<Player> createPlayersList(Mode mode) { // quickly initialize group of players based on mode Player[] players = null; //TODO: could add a getPlayersList() method to each Mode to avoid this switch stmt switch(mode) { case QB: players = new Player[]{Players.SANCHEZ.deepCopy(),Players.WEEDEN.deepCopy(), Players.LEINART.deepCopy(),Players.QUINN.deepCopy(),Players.KOLB.deepCopy(), Players.PALMER.deepCopy(),Players.BRADY.deepCopy(),Players.PEYTON.deepCopy(), Players.RODGERS.deepCopy()}; break; case RB: players = new Player[]{Players.REDMAN.deepCopy(),Players.HILLMAN.deepCopy(), Players.MATHEWS.deepCopy(),Players.JONESDREW.deepCopy(),Players.RBUSH.deepCopy(), Players.RICE.deepCopy(),Players.LYNCH.deepCopy(),Players.FOSTER.deepCopy()}; break; case WR: players = new Player[]{Players.BEDWARDS.deepCopy(),Players.SHOLMES.deepCopy(), Players.HDOUGLAS.deepCopy(),Players.MANNINGHAM.deepCopy(),Players.AMENDOLA.deepCopy(), Players.JJONES.deepCopy(),Players.DBRYANT.deepCopy(),Players.CJOHNSON.deepCopy()}; break; case K: players = new Player[]{Players.CUNDIFF.deepCopy(),Players.FOLK.deepCopy(), Players.CROSBY.deepCopy(),Players.FORBATH.deepCopy(),Players.SCOBEE.deepCopy(), Players.SUISHAM.deepCopy(),Players.GOSTKOWSKI.deepCopy(),Players.MBRYANT.deepCopy(), Players.TUCKER.deepCopy()}; break; case DEF: players = new Player[]{Players.OAKLAND.deepCopy(),Players.NEWORLEANS.deepCopy(), Players.JACKSONVILLE.deepCopy(),Players.CLEVELAND.deepCopy(),Players.SEATTLE.deepCopy(), Players.SANFRAN.deepCopy(),Players.CHICAGO.deepCopy()}; break; case ALL: // this list is built up from all other lists in addMapping() return null; default: throw new IllegalArgumentException("Error: Invalid mode\n" + getUsage()); } // put players into list List<Player> playersList = new ArrayList<Player>(Arrays.asList(players)); return playersList; } // create and initialize a RuleMap containing the default scoring rules // for NFL.com leagues private static RuleMap initDefaultRuleMap() { RuleMap rules = new RuleMap(); rules.put(Pass.YDS, new Rule<Pass>(Pass.YDS, 1.0, 25)); rules.put(Pass.TD, new Rule<Pass>(Pass.TD, 4.0)); rules.put(Pass.INT, new Rule<Pass>(Pass.INT, -2.0)); rules.put(Rush.YDS, new Rule<Rush>(Rush.YDS, 1.0, 10)); rules.put(Rush.TD, new Rule<Rush>(Rush.TD, 6.0)); rules.put(Rec.YDS, new Rule<Rec>(Rec.YDS, 1.0, 10)); rules.put(Rec.TD, new Rule<Rec>(Rec.TD, 6.0)); rules.put(Misc.FUMB_TD, new Rule<Misc>(Misc.FUMB_TD, 6.0)); rules.put(Misc.FUMB_LOST, new Rule<Misc>(Misc.FUMB_LOST, -2.0)); rules.put(Misc.TWO_PT_CONV, new Rule<Misc>(Misc.TWO_PT_CONV, 2.0)); rules.put(Kick.PAT_MD, new Rule<Kick>(Kick.PAT_MD, 1.0)); rules.put(Kick.FG_MD_0, new Rule<Kick>(Kick.FG_MD_0, 3.0)); rules.put(Kick.FG_MD_20, new Rule<Kick>(Kick.FG_MD_20, 3.0)); rules.put(Kick.FG_MD_30, new Rule<Kick>(Kick.FG_MD_30, 3.0)); rules.put(Kick.FG_MD_40, new Rule<Kick>(Kick.FG_MD_40, 3.0)); rules.put(Kick.FG_MD_50, new Rule<Kick>(Kick.FG_MD_50, 5.0)); rules.put(Def.SCK, new Rule<Def>(Def.SCK, 1.0)); rules.put(Def.INT, new Rule<Def>(Def.INT, 2.0)); rules.put(Def.FUMB, new Rule<Def>(Def.FUMB, 2.0)); rules.put(Def.SAF, new Rule<Def>(Def.SAF, 2.0)); rules.put(Def.TD, new Rule<Def>(Def.TD, 6.0)); rules.put(Def.RET, new Rule<Def>(Def.RET, 6.0)); rules.put(Def.PTS, new Rule<Def>(Def.PTS, -3.0, 7)); return rules; } // get string detailing command line usage private static String getUsage() { String result = ""; String indent = "\t\t"; result += "Usage: java FantasyFootballCustomScoringHelper <mode> <sc1> ... <scN>,\twhere\n"; result += (indent + "mode := player position to simulate. Possible values are def, k, qb, rb, and wr.\n"); result += (indent + "sc1 - scN := scoring coefficients representing all rules needed to score players" + " at position given by mode. Necessary scoring coefficients per position are given below.\n"); /*result += (indent + "def: " + DEF.categoriesToString() + "\n"); result += (indent + "k: " + K.categoriesToString() + "\n"); result += (indent + "qb: " + QB.categoriesToString() + "\n"); result += (indent + "rb: " + RB.categoriesToString() + "\n"); result += (indent + "wr: " + WR.categoriesToString() + "\n");*/ return result; } }
package hudson.plugins.pmd.parser; import hudson.FilePath; import hudson.FilePath.FileCallable; import hudson.plugins.pmd.Messages; import hudson.plugins.pmd.util.MavenModuleDetector; import hudson.plugins.pmd.util.model.JavaProject; import hudson.plugins.pmd.util.model.MavenModule; import hudson.remoting.VirtualChannel; import java.io.File; import java.io.IOException; import java.io.PrintStream; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.tools.ant.types.FileSet; import org.xml.sax.SAXException; /** * Parses the PMD files that match the specified pattern and creates a * corresponding Java project with a collection of annotations. * * @author Ulli Hafner */ public class PmdCollector implements FileCallable<JavaProject> { /** Slash separator on UNIX. */ private static final String SLASH = "/"; /** Generated ID. */ private static final long serialVersionUID = -6415863872891783891L; /** Determines whether to skip old files. */ private static final boolean SKIP_OLD_FILES = false; /** Logger. */ private transient PrintStream logger; /** Build time stamp, only newer files are considered. */ private final long buildTime; /** Ant file-set pattern to scan for PMD files. */ private final String filePattern; /** * Creates a new instance of <code>PmdCollector</code>. * * @param listener * the Logger * @param buildTime * build time stamp, only newer files are considered * @param filePattern * ant file-set pattern to scan for PMD files */ public PmdCollector(final PrintStream listener, final long buildTime, final String filePattern) { logger = listener; this.buildTime = buildTime; this.filePattern = filePattern; } /** {@inheritDoc} */ public JavaProject invoke(final File workspace, final VirtualChannel channel) throws IOException { String[] pmdFiles = findPmdFiles(workspace); JavaProject project = new JavaProject(); if (pmdFiles.length == 0) { project.setError("No pmd report files were found. Configuration error?"); return project; } try { MavenModuleDetector detector = new MavenModuleDetector(); int duplicateModuleCounter = 1; for (String file : pmdFiles) { File pmdFile = new File(workspace, file); String moduleName = detector.guessModuleName(pmdFile.getAbsolutePath()); if (project.containsModule(moduleName)) { moduleName += "-" + duplicateModuleCounter++; } MavenModule module = new MavenModule(moduleName); if (SKIP_OLD_FILES && pmdFile.lastModified() < buildTime) { String message = Messages.PMD_PMDCollector_Error_FileNotUpToDate(pmdFile); getLogger().println(message); module.setError(message); continue; } if (!pmdFile.canRead()) { String message = Messages.PMD_PMDCollector_Error_NoPermission(pmdFile); getLogger().println(message); module.setError(message); continue; } if (new FilePath(pmdFile).length() <= 0) { String message = Messages.PMD_PMDCollector_Error_EmptyFile(pmdFile); getLogger().println(message); module.setError(message); continue; } module = parseFile(workspace, pmdFile, module); project.addModule(module); } } catch (InterruptedException exception) { getLogger().println("Parsing has been canceled."); } return project; } /** * Parses the specified PMD file and maps all warnings to a * corresponding annotation. If the file could not be parsed then an empty * module with an error message is returned. * * @param workspace * the root of the workspace * @param pmdFile * the file to parse * @param emptyModule * an empty module with the guessed module name * @return the created module * @throws InterruptedException */ private MavenModule parseFile(final File workspace, final File pmdFile, final MavenModule emptyModule) throws InterruptedException { Exception exception = null; MavenModule module = emptyModule; try { FilePath filePath = new FilePath(pmdFile); PmdParser pmdParser = new PmdParser(); module = pmdParser.parse(filePath.read(), emptyModule.getName()); getLogger().println("Successfully parsed PMD file " + pmdFile + " of module " + module.getName() + " with " + module.getNumberOfAnnotations() + " warnings."); } catch (IOException e) { exception = e; } catch (SAXException e) { exception = e; } if (exception != null) { String errorMessage = Messages.PMD_PMDCollector_Error_Exception(pmdFile) + "\n\n" + ExceptionUtils.getStackTrace(exception); getLogger().println(errorMessage); module.setError(errorMessage); } return module; } /** * Returns an array with the filenames of the PMD files that have been * found in the workspace. * * @param workspaceRoot * root directory of the workspace * @return the filenames of the PMD files */ private String[] findPmdFiles(final File workspaceRoot) { FileSet fileSet = new FileSet(); org.apache.tools.ant.Project project = new org.apache.tools.ant.Project(); fileSet.setProject(project); fileSet.setDir(workspaceRoot); fileSet.setIncludes(filePattern); return fileSet.getDirectoryScanner(project).getIncludedFiles(); } /** * Returns the logger. * * @return the logger */ private PrintStream getLogger() { if (logger == null) { logger = System.out; } return logger; } }
package in.twizmwaz.cardinal.rotation; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import in.twizmwaz.cardinal.Cardinal; import in.twizmwaz.cardinal.rotation.exception.RotationLoadException; import in.twizmwaz.cardinal.util.Contributor; import in.twizmwaz.cardinal.util.DomUtils; import in.twizmwaz.cardinal.util.MojangUtils; import in.twizmwaz.cardinal.util.NumUtils; import org.apache.commons.io.Charsets; import org.bukkit.Bukkit; import org.jdom2.Document; import org.jdom2.Element; import java.io.*; import java.nio.file.Files; import java.util.*; import java.util.logging.Level; public class Rotation { private File rotationFile; private List<LoadedMap> rotation; private List<LoadedMap> loaded; private int position; private File repo; public Rotation() throws RotationLoadException { this.rotationFile = new File(Cardinal.getInstance().getConfig().getString("rotation")); refreshRepo(); refreshRotation(); } /** * Refreshes the maps in the repository and the data associated with them * * @throws RotationLoadException */ public void refreshRepo() throws RotationLoadException { loaded = new ArrayList<>(); this.repo = new File(Cardinal.getInstance().getConfig().getString("repo")); List<String> requirements = Arrays.asList("map.xml", "region", "level.dat"); for (File map : repo.listFiles()) { if (map.isFile()) continue; if (Arrays.asList(map.list()).containsAll(requirements)) { try { Document xml = DomUtils.parse(new File(map.getPath() + "/map.xml")); String name = xml.getRootElement().getChild("name").getText(); String version = xml.getRootElement().getChild("version").getText(); String objective = xml.getRootElement().getChild("objective").getText(); List<Contributor> authors = new ArrayList<>(); for (Element authorsElement : xml.getRootElement().getChildren("authors")) { for (Element author : authorsElement.getChildren()) { authors.add(parseContributor(author)); } } List<Contributor> contributors = new ArrayList<>(); for (Element contributorsElement : xml.getRootElement().getChildren("contributors")) { for (Element contributor : contributorsElement.getChildren()) { contributors.add(parseContributor(contributor)); } } List<String> rules = new ArrayList<>(); for (Element rulesElement : xml.getRootElement().getChildren("rules")) { for (Element rule : rulesElement.getChildren()) { rules.add(rule.getText().trim()); } } int maxPlayers = 0; for (Element teams : xml.getRootElement().getChildren("teams")) { for (Element team : teams.getChildren()) { maxPlayers = maxPlayers + NumUtils.parseInt(team.getAttributeValue("max")); } } loaded.add(new LoadedMap(name, version, objective, authors, contributors, rules, maxPlayers, map)); } catch (Exception e) { Bukkit.getLogger().log(Level.WARNING, "Failed to load map at " + map.getAbsolutePath()); if (Cardinal.getInstance().getConfig().getBoolean("displayMapLoadErrors")) { Bukkit.getLogger().log(Level.INFO, "Showing error, this can be disabled in the config: "); e.printStackTrace(); } } } } try { updatePlayers(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /** * Refreshes the plugin's default rotation */ public void refreshRotation() { rotation = new ArrayList<>(); try { if (!rotationFile.exists()) { List<String> maps = Lists.newArrayList(); for (LoadedMap map : loaded) maps.add(map.getName()); FileWriter writer = new FileWriter(rotationFile); for (String map : maps) writer.write(map + System.lineSeparator()); writer.close(); } List<String> lines = Files.readAllLines(rotationFile.toPath(), Charsets.UTF_8); for (String line : lines) { for (LoadedMap map : loaded) { if (map.getName().replaceAll(" ", "").equalsIgnoreCase(line.replaceAll(" ", ""))) { rotation.add(map); break; } } } } catch (IOException e) { List<String> lines = new ArrayList<>(); for (int x = 0; x < 8; x++) { try { rotation.add(loaded.get(x)); } catch (IndexOutOfBoundsException ex) { } } Bukkit.getLogger().log(Level.WARNING, "Failed to load rotation file, using a temporary rotation instead."); } position = 0; } /** * Move the position in the rotation by one. If the end of the rotation is reached, it will be automatically reset. */ public int move() { position++; if (position > rotation.size() - 1) { position = 0; } return position; } /** * @return Returns the next map in the rotation */ public LoadedMap getNext() { return rotation.get(position); } /** * @return Returns the rotation */ public List<LoadedMap> getRotation() { return rotation; } /** * @return Returns all loaded maps */ public List<LoadedMap> getLoaded() { return loaded; } /** * @return Gets the rotation index of the next map */ public int getNextIndex() { return position; } /** * @param string The name of map to be searched for * @return The map */ public LoadedMap getMap(String string) { for (LoadedMap map : loaded) { if (map.getName().toLowerCase().startsWith(string.toLowerCase())) return map; } return null; } public LoadedMap getCurrent() { try { return rotation.get(position - 1); } catch (IndexOutOfBoundsException e) { return rotation.get(0); } } private Contributor parseContributor(Element element) { if (element.getAttributeValue("uuid") != null) { return new Contributor(UUID.fromString(element.getAttributeValue("uuid")), element.getAttributeValue("contribution")); } else return new Contributor(element.getText(), element.getAttributeValue("contribution")); } @SuppressWarnings("unchecked") private void updatePlayers() throws IOException, ClassNotFoundException { HashMap<UUID, String> names; try { names = (HashMap<UUID, String>) new ObjectInputStream(new FileInputStream(new File(Cardinal.getInstance().getDataFolder().getPath() + ".names.ser"))).readObject(); } catch (FileNotFoundException e) { names = Maps.newHashMap(); } for (LoadedMap map : loaded) { for (Contributor contributor : map.getAuthors()) { if (contributor.getName() == null) { String localName = Bukkit.getOfflinePlayer(contributor.getUniqueId()).getName(); if (localName != null) { contributor.setName(localName); } else if (names.containsKey(contributor.getUniqueId())) { contributor.setName(names.get(contributor.getUniqueId())); } else { names.put(contributor.getUniqueId(), MojangUtils.getNameByUUID(contributor.getUniqueId())); contributor.setName(names.get(contributor.getUniqueId())); } } } for (Contributor contributor : map.getContributors()) { if (contributor.getName() == null) { String localName = Bukkit.getOfflinePlayer(contributor.getUniqueId()).getName(); if (localName != null) { contributor.setName(localName); } else if (names.containsKey(contributor.getUniqueId())) { contributor.setName(names.get(contributor.getUniqueId())); } else { names.put(contributor.getUniqueId(), MojangUtils.getNameByUUID(contributor.getUniqueId())); contributor.setName(names.get(contributor.getUniqueId())); } } } } ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(Cardinal.getInstance().getDataFolder().getPath() + "/.names.ser"))); out.writeObject(names); out.close(); } }
package jp.gecko655.bot.fujimiya; import java.text.DateFormat; import java.util.List; import java.util.TimeZone; import java.util.logging.Level; import java.util.regex.Pattern; import java.util.stream.Collectors; import jp.gecko655.bot.AbstractCron; import jp.gecko655.bot.DBConnection; import twitter4j.Paging; import twitter4j.Relationship; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterException; public class FujimiyaReply extends AbstractCron { static final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); private static final Pattern keishouPattern = Pattern.compile("(|||)$"); private static final Pattern whoPattern = Pattern.compile("( $| $|[^]|[^]|[^]?|[^]?| | )"); public FujimiyaReply() { format.setTimeZone(TimeZone.getDefault()); } @Override protected void twitterCron() { try { Status lastStatus = DBConnection.getLastStatus(); List<Status> replies = twitter.getMentionsTimeline((new Paging()).count(20)); if(replies.isEmpty()){ logger.log(Level.INFO, "Not yet replied. Stop."); return; } DBConnection.setLastStatus(replies.get(0)); if(lastStatus == null){ logger.log(Level.INFO,"memcache saved. Stop. "+replies.get(0).getUser().getName()+"'s tweet at "+format.format(replies.get(0).getCreatedAt())); return; } List<Status> validReplies = replies.stream() .filter(reply -> isValid(reply, lastStatus)).collect(Collectors.toList()); if(validReplies.isEmpty()){ logger.log(Level.FINE, "No valid replies. Stop."); return; } for(Status reply : validReplies){ Relationship relation = twitter.friendsFollowers().showFriendship(twitter.getId(), reply.getUser().getId()); if(!relation.isSourceFollowingTarget()){ followBack(reply); }else if(whoPattern.matcher(reply.getText()).find()){ // put latest image URL to black-list who(reply); }else{ //auto reply (when fujimiya-san follows the replier) StatusUpdate update= new StatusUpdate("@"+reply.getUser().getScreenName()+" "); update.setInReplyToStatusId(reply.getId()); if(((int) (Math.random()*10))==1){ updateStatusWithMedia(update, " ", 100); }else{ updateStatusWithMedia(update, " ",100); } } } } catch (TwitterException e) { logger.log(Level.WARNING,e.toString()); e.printStackTrace(); } } private boolean isValid(Status reply, Status lastStatus) { if(lastStatus==null) return false; return reply.getCreatedAt().after(lastStatus.getCreatedAt()); } private void followBack(Status reply) throws TwitterException { twitter.createFriendship(reply.getUser().getId()); String userName = reply.getUser().getName(); if(!keishouPattern.matcher(userName).find()){ userName = userName + ""; } StatusUpdate update= new StatusUpdate("@"+reply.getUser().getScreenName()+" "+userName+""); update.setInReplyToStatusId(reply.getId()); Status status = twitter.updateStatus(update); logger.log(Level.INFO, "Successfully tweeted and followed back. "+status.getText()); } private void who(Status reply) { //Store the url to the black list. DBConnection.storeImageUrlToBlackList(reply.getInReplyToStatusId(),reply.getUser().getScreenName()); try{ //Delete the reported tweet. twitter.destroyStatus(reply.getInReplyToStatusId()); //Apologize to the report user. StatusUpdate update= new StatusUpdate("@"+reply.getUser().getScreenName()+" "); update.setInReplyToStatusId(reply.getId()); twitter.updateStatus(update); }catch(TwitterException e){ e.printStackTrace(); } } }
package jp.pushmestudio.kcuc.controller; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import jp.pushmestudio.kcuc.dao.UserInfoDao; import jp.pushmestudio.kcuc.model.Product; import jp.pushmestudio.kcuc.model.ResultContent; import jp.pushmestudio.kcuc.model.ResultPageList; import jp.pushmestudio.kcuc.model.ResultProductList; import jp.pushmestudio.kcuc.model.ResultSearchList; import jp.pushmestudio.kcuc.model.ResultUserList; import jp.pushmestudio.kcuc.model.SubscribedPage; import jp.pushmestudio.kcuc.model.Topic; import jp.pushmestudio.kcuc.model.TopicMeta; import jp.pushmestudio.kcuc.model.UserDocument; import jp.pushmestudio.kcuc.model.UserInfo; import jp.pushmestudio.kcuc.util.KCMessageFactory; import jp.pushmestudio.kcuc.util.Result; /** * * Result(=API)try-catch */ public class KCData { /** * * * @param userId * ID * @param prodId * IDID * @return Message() */ public Result cancelSubscribedProduct(String userId, String prodId) { try { UserInfoDao userInfoDao = UserInfoDao.getInstance(); if (!userInfoDao.isUserExist(userId)) { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "User Not Found."); } com.cloudant.client.api.model.Response res = userInfoDao.cancelSubscribedProduct(userId, prodId); return KCMessageFactory.createMessage(res.getStatusCode(), res.getReason()); } catch (JSONException e) { e.printStackTrace(); return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Internal Server Error."); } catch (IndexOutOfBoundsException ee) { ee.printStackTrace(); return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Not Yet Subscribed This Product."); } } /** * (TOCtopics()href) * JSON * * @param pageKey * * @return * <code>{"userList":[{"isUpdated":true,"id":"capsmalt"}],"pageHref": * "SSAW57_liberty/com.ibm.websphere.wlp.nd.doc/ae/cwlp_about.html"}</code> */ public Result checkUpdateByPage(String pageKey) { String pageHref = this.normalizeHref(pageKey); try { TopicMeta topicMeta = getSpecificPageMeta(pageHref); if (!topicMeta.isExist()) { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Page Not Found."); } Date lastModifiedDate = new Date(topicMeta.getDateLastUpdated()); final long weekSeconds = (7 * 24 * 60 * 60); // 604,800 long preservedTime = new Date().getTime() - weekSeconds; UserInfoDao userInfoDao = UserInfoDao.getInstance(); List<UserDocument> userList = userInfoDao.getSubscribedUserList(pageHref); // return Result result = new ResultUserList(pageHref); for (UserDocument userDoc : userList) { UserInfo eachUser = new UserInfo(userDoc.getUserId(), preservedTime < lastModifiedDate.getTime()); ((ResultUserList) result).addSubscriber(eachUser); } return result; } catch (JSONException e) { e.printStackTrace(); return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Internal Server Error."); } } /** * ID * * @param userId * ID * @return * <code>{"pages":[{"isUpdated":true,"pageHref": * "SSAW57_liberty/com.ibm.websphere.wlp.nd.doc/ae/cwlp_about.html"}], * "id":"capsmalt"}</code> */ public Result checkUpdateByUser(String userId) { return this.checkUpdateByUser(userId, null); } /** * ID ID * * @param userId * ID * @param prodId * ID, Optional * @return * <code>{"pages":[{"isUpdated":true,"pageHref": * "SSAW57_liberty/com.ibm.websphere.wlp.nd.doc/ae/cwlp_about.html"}], * "id":"capsmalt"}</code> */ public Result checkUpdateByUser(String userId, String prodId) { try { UserInfoDao userInfoDao = UserInfoDao.getInstance(); if (!userInfoDao.isUserExist(userId)) { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "User Not Found."); } // IDList List<UserDocument> userList; if (Objects.isNull(prodId)) { userList = userInfoDao.getUserList(userId); } else { userList = userInfoDao.getUserList(userId, prodId); } // return Result result = new ResultPageList(userId); for (UserDocument userDoc : userList) { List<SubscribedPage> subscribedPages = userDoc.getSubscribedPages(); for (SubscribedPage entry : subscribedPages) { String pageKey = entry.getPageHref(); long preservedDate = entry.getUpdatedTime(); TopicMeta topicMeta = getSpecificPageMeta(pageKey); if (!topicMeta.isExist()) { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Page Not Found."); } Date lastModifiedDate = new Date(topicMeta.getDateLastUpdated()); entry.setIsUpdated(preservedDate < lastModifiedDate.getTime()); ((ResultPageList) result).addSubscribedPage(entry); } } return result; } catch (JSONException e) { e.printStackTrace(); return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Internal Server Error."); } } /** * ID * * @param userId * ID * @return Message() */ public Result createUser(String userId) { UserInfoDao userInfoDao = UserInfoDao.getInstance(); com.cloudant.client.api.model.Response res = userInfoDao.createUser(userId); Result result = KCMessageFactory.createMessage(res.getStatusCode(), res.getReason()); return result; } /** * * * @param userId * ID * @param href * * @return Message() * */ public Result deleteSubscribedPage(String userId, String href) { try { String pageHref = this.normalizeHref(href); UserInfoDao userInfoDao = UserInfoDao.getInstance(); if (!userInfoDao.isUserExist(userId)) { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "User Not Found."); // KnowledgeCenter } else if (!isTopicExist(pageHref)) { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Page Not Found."); } else if (!userInfoDao.isPageExist(userId, pageHref)) { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Not Yet Subscribed This Page."); } com.cloudant.client.api.model.Response res = userInfoDao.delSubscribedPage(userId, pageHref); return KCMessageFactory.createMessage(res.getStatusCode(), res.getReason()); } catch (JSONException e) { e.printStackTrace(); return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Internal Server Error."); } } /** * ID * * @param userId * ID * @return Message() */ public Result deleteUser(String userId) { UserInfoDao userInfoDao = UserInfoDao.getInstance(); com.cloudant.client.api.model.Response res = userInfoDao.deleteUser(userId); Result result = KCMessageFactory.createMessage(res.getStatusCode(), res.getReason()); return result; } /** * * HashSet * * @param userId * * @return ID * @see {@link ResultProductList} */ public Result getSubscribedProductList(String userId) { UserInfoDao userInfoDao = UserInfoDao.getInstance(); if (!userInfoDao.isUserExist(userId)) { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "User Not Found"); } // IDList List<UserDocument> userList = userInfoDao.getUserList(userId); // return Result result = new ResultProductList(userId); /* * TODO DB * () */ for (UserDocument userDoc : userList) { List<SubscribedPage> subscribedPages = userDoc.getSubscribedPages(); subscribedPages.forEach(entry -> { ((ResultProductList) result).addSubscribedProduct(entry.getProdId(), entry.getProdName()); }); } return result; } /** * ID * * @param userId * ID * @param href * * @return Message() */ public Result registerSubscribedPage(String userId, String href) { try { String pageHref = this.normalizeHref(href); UserInfoDao userInfoDao = UserInfoDao.getInstance(); TopicMeta topicMeta = getSpecificPageMeta(pageHref); if (!userInfoDao.isUserExist(userId)) { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "User Not Found."); } else if (!topicMeta.isExist()) { // KnowledgeCenter return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Page Not Found."); } else if (userInfoDao.isPageExist(userId, pageHref)) { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "You Already Subscribe This Page."); } String prodId = topicMeta.getProduct(); String prodName = this.searchProduct(prodId).getLabel(); String pageName = this.getPageName(prodId, pageHref); com.cloudant.client.api.model.Response res = userInfoDao.setSubscribedPages(userId, pageHref, pageName, prodId, prodName); return KCMessageFactory.createMessage(res.getStatusCode(), res.getReason()); } catch (JSONException e) { e.printStackTrace(); return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Communication Error"); } } public Result searchContent(String href, String lang) { Client client = ClientBuilder.newClient(); final String searchUrl = "https: String pagehref = this.normalizeHref(href); WebTarget target; // null if (Objects.isNull(lang)) { target = client.target(searchUrl).path(pagehref); } else { target = client.target(searchUrl).path(lang).path(pagehref); } Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON); Response res = invocationBuilder.get(); Result result = new ResultContent(res.readEntity(String.class)); return result; } public Result searchPages(String query, String products, String inurl, Integer offset, Integer limit, String lang, String sort) { Client client = ClientBuilder.newClient(); final String searchUrl = "https: WebTarget target = client.target(searchUrl).queryParam("query", query); /* * * 1.Map2.Map * , queryParamWebTargetMap */ Map<String, String> queryMap = new HashMap<>(); Optional.ofNullable(products).ifPresent(_products -> queryMap.put("products", _products)); Optional.ofNullable(inurl).ifPresent(_inurl -> queryMap.put("inurl", _inurl)); Optional.ofNullable(offset).ifPresent(_offset -> queryMap.put("offset", _offset.toString())); Optional.ofNullable(limit).ifPresent(_limit -> queryMap.put("limit", _limit.toString())); Optional.ofNullable(lang).ifPresent(_lang -> queryMap.put("lang", _lang)); // null if (!"date:a".equals(sort) && !"date:d".equals(sort)) { sort = null; } Optional.ofNullable(sort).ifPresent(_sort -> queryMap.put("sort", _sort)); for (Entry<String, String> each : queryMap.entrySet()) { target = target.queryParam(each.getKey(), each.getValue()); } Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON); Response res = invocationBuilder.get(); JSONObject resJson = new JSONObject(res.readEntity(String.class)); // topics if (resJson.has("topics")) { int resOffset = resJson.getInt("offset"); int resNext = resJson.getInt("next"); int resPrev = resJson.getInt("prev"); int resCount = resJson.getInt("count"); int resTotal = resJson.getInt("total"); List<Topic> resTopics = new ArrayList<>(); // JSONtopics1Topic resJson.getJSONArray("topics").forEach(topic -> resTopics.add(new Topic((JSONObject) topic))); Result result = new ResultSearchList(resOffset, resNext, resPrev, resCount, resTotal, resTopics); return ((ResultSearchList) result); } else { return KCMessageFactory.createMessage(Result.CODE_SERVER_ERROR, "Can't get search result"); } } /** * breadcrumb()hreflabel * * @param prodId * ID * @param pageHref * pageHref * @return breadcrumb */ private String getPageName(String prodId, String pageHref) throws JSONException { Client client = ClientBuilder.newClient(); final String topicMetaUrl = "https: WebTarget target = client.target(topicMetaUrl).path(prodId).queryParam("href", pageHref); Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON); Response res = invocationBuilder.get(); JSONObject resJson = new JSONObject(res.readEntity(String.class)); String pageName = ""; // breadcrumbhreflabelhref if (resJson.has("breadcrumb")) { JSONArray breadCrumb = resJson.getJSONArray("breadcrumb"); JSONObject targetPage = breadCrumb.getJSONObject((breadCrumb.length() - 1)); pageName = targetPage.getString("label"); } return pageName; } /** * KC * * @param specificHref * pageHref * @return topic_metadata{@link TopicMeta} */ private TopicMeta getSpecificPageMeta(String specificHref) throws JSONException { Client client = ClientBuilder.newClient(); final String topicMetaUrl = "https: WebTarget target = client.target(topicMetaUrl).queryParam("href", specificHref); Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON); Response res = invocationBuilder.get(); JSONObject resJson = new JSONObject(res.readEntity(String.class)); return new TopicMeta(resJson); } /** * KnowledgeCenter-1 * {@link TopicMeta#isExist()} * * @param pageHref * * @return True or False */ private boolean isTopicExist(String pageHref) { try { return getSpecificPageMeta(pageHref).isExist(); } catch (JSONException | NullPointerException e) { return false; } } /** * .htm.htmlisTopicExist()) * sc=_latest * xxx.htm,xxx.htm?sc=_latest,xxx.html?sc=_latestxxx.html * * @param originalHref * href * @return href */ private String normalizeHref(String originalHref) { String normalizedHref = originalHref .replaceFirst("\\.htm$" + "|\\.htm\\?sc=_latest$" + "|\\.html\\?sc=_latest$", "\\.html"); return normalizedHref; } /** * KC * * @param productKey * * @return JSON{@link Product} | null */ private Product searchProduct(String productKey) { Client client = ClientBuilder.newClient(); final String searchUrl = "https: WebTarget target = client.target(searchUrl + productKey); Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON); Response res = invocationBuilder.get(); JSONObject resJson = new JSONObject(res.readEntity(String.class)); // product if (resJson.has("product")) { return new Product(resJson.getJSONObject("product")); } else { return null; } } }
package kihira.tails.client.render; import kihira.tails.client.model.ModelPartBase; import kihira.tails.common.PartInfo; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; public class RenderWings extends RenderPart { public RenderWings(String name, int subTypes, String modelAuthor, ModelPartBase modelPart, String... textureNames) { super(name, subTypes, modelAuthor, modelPart, textureNames); } @Override protected void doRender(EntityLivingBase entity, PartInfo info, float partialTicks) { Minecraft.getMinecraft().renderEngine.bindTexture(info.getTexture()); WorldRenderer renderer = Tessellator.getInstance().getWorldRenderer(); boolean isFlying = entity instanceof EntityPlayer && ((EntityPlayer) entity).capabilities.isFlying && entity.isAirBorne || entity.fallDistance > 0F; float timestep = ModelPartBase.getAnimationTime(isFlying ? 500 : 6500, entity); float angle = (float) Math.sin(timestep) * (isFlying ? 24F : 4F); float scale = info.subid == 1 ? 1F : 2F; GlStateManager.translate(0, -(scale * 8F) * ModelPartBase.SCALE + (info.subid == 1 ? 0.1F : 0), 0.1F); GlStateManager.rotate(90, 0, 1, 0); GlStateManager.rotate(90, 0, 0, 1); GlStateManager.scale(scale, scale, scale); GlStateManager.translate(0.1F, -0.4F * ModelPartBase.SCALE, -0.025F); GlStateManager.pushMatrix(); GlStateManager.translate(0F, 0F, 1F * ModelPartBase.SCALE); GlStateManager.rotate(30F - angle, 1F, 0F, 0F); renderer.startDrawingQuads(); renderer.addVertexWithUV(0, 1, 0, 0, 0); renderer.addVertexWithUV(1, 1, 0, 1, 0); renderer.addVertexWithUV(1, 0, 0, 1, 1); renderer.addVertexWithUV(0, 0, 0, 0, 1); Tessellator.getInstance().draw(); GlStateManager.popMatrix(); GlStateManager.pushMatrix(); GlStateManager.translate(0F, 0.3F * ModelPartBase.SCALE, 0F); GlStateManager.rotate(-30F + angle, 1F, 0F, 0F); renderer.startDrawingQuads(); renderer.addVertexWithUV(0, 1, 0, 0, 0); renderer.addVertexWithUV(1, 1, 0, 1, 0); renderer.addVertexWithUV(1, 0, 0, 1, 1); renderer.addVertexWithUV(0, 0, 0, 0, 1); Tessellator.getInstance().draw(); GlStateManager.popMatrix(); } }
package net.md_5.mc.protocol; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class PacketDefinitions { private static final Instruction[][] opCodes = new Instruction[256][]; private static final Instruction BYTE = new JumpOpCode(1); private static final Instruction BOOLEAN = BYTE; private static final Instruction SHORT = new JumpOpCode(2); private static final Instruction INT = new JumpOpCode(4); private static final Instruction FLOAT = INT; private static final Instruction LONG = new JumpOpCode(8); private static final Instruction DOUBLE = LONG; private static final Instruction SHORT_BYTE = new ShortHeader(BYTE); private static final Instruction BYTE_INT = new ByteHeader(INT); private static final Instruction INT_BYTE = new IntHeader(BYTE); private static final Instruction INT_3 = new IntHeader(new JumpOpCode(3)); private static final Instruction INT_6 = new IntHeader(new JumpOpCode(6)); private static final Instruction STRING = new ShortHeader(SHORT); private static final Instruction ITEM = new Instruction() { @Override void read(DataInput in) throws IOException { short type = in.readShort(); if (type >= 0) { skip(in, 3); SHORT_BYTE.read(in); } } @Override public String toString() { return "Item"; } }; private static final Instruction SHORT_ITEM = new ShortHeader(ITEM); private static final Instruction METADATA = new Instruction() { @Override void read(DataInput in) throws IOException { int x = in.readUnsignedByte(); while (x != 127) { int type = x >> 5; switch (type) { case 0: BYTE.read(in); break; case 1: SHORT.read(in); break; case 2: INT.read(in); break; case 3: FLOAT.read(in); break; case 4: STRING.read(in); break; case 5: skip(in, 5); // short, byte, short break; case 6: skip(in, 6); // int, int, int break; default: throw new IllegalArgumentException("Unknown metadata type " + type); } x = in.readByte(); } } @Override public String toString() { return "Metadata"; } }; private static final Instruction BULK_CHUNK = new Instruction() { @Override void read(DataInput in) throws IOException { short count = in.readShort(); INT_BYTE.read(in); skip(in, count * 12); } @Override public String toString() { return "Bulk Chunk"; } }; private static final Instruction UBYTE_BYTE = new Instruction() { @Override void read(DataInput in) throws IOException { int size = in.readUnsignedByte(); skip(in, size); } @Override public String toString() { return "Unsigned Byte Byte"; } }; static { opCodes[0x00] = new Instruction[]{INT}; opCodes[0x01] = new Instruction[]{INT, STRING, BYTE, BYTE, BYTE, BYTE, BYTE}; opCodes[0x02] = new Instruction[]{BYTE, STRING, STRING, INT}; opCodes[0x03] = new Instruction[]{STRING}; opCodes[0x04] = new Instruction[]{LONG}; opCodes[0x05] = new Instruction[]{INT, SHORT, ITEM}; opCodes[0x06] = new Instruction[]{INT, INT, INT}; opCodes[0x07] = new Instruction[]{INT, INT, BOOLEAN}; opCodes[0x08] = new Instruction[]{SHORT, SHORT, FLOAT}; opCodes[0x09] = new Instruction[]{INT, BYTE, BYTE, SHORT, STRING}; opCodes[0x0A] = new Instruction[]{BOOLEAN}; opCodes[0x0B] = new Instruction[]{DOUBLE, DOUBLE, DOUBLE, DOUBLE, BOOLEAN}; opCodes[0x0C] = new Instruction[]{FLOAT, FLOAT, BOOLEAN}; opCodes[0x0D] = new Instruction[]{DOUBLE, DOUBLE, DOUBLE, DOUBLE, FLOAT, FLOAT, BOOLEAN}; opCodes[0x0E] = new Instruction[]{BYTE, INT, BYTE, INT, BYTE}; opCodes[0x0F] = new Instruction[]{INT, BYTE, INT, BYTE, ITEM, BYTE, BYTE, BYTE}; opCodes[0x10] = new Instruction[]{SHORT}; opCodes[0x11] = new Instruction[]{INT, BYTE, INT, BYTE, INT}; opCodes[0x12] = new Instruction[]{INT, BYTE}; opCodes[0x13] = new Instruction[]{INT, BYTE}; opCodes[0x14] = new Instruction[]{INT, STRING, INT, INT, INT, BYTE, BYTE, SHORT, METADATA}; opCodes[0x15] = new Instruction[]{INT, SHORT, BYTE, SHORT, INT, INT, INT, BYTE, BYTE, BYTE}; opCodes[0x16] = new Instruction[]{INT, INT}; opCodes[0x17] = new Instruction[]{INT, BYTE, INT, INT, INT, INT_6}; opCodes[0x18] = new Instruction[]{INT, BYTE, INT, INT, INT, BYTE, BYTE, BYTE, SHORT, SHORT, SHORT, METADATA}; opCodes[0x19] = new Instruction[]{INT, STRING, INT, INT, INT, INT}; opCodes[0x1A] = new Instruction[]{INT, INT, INT, INT, SHORT}; opCodes[0x1B] = null; // Does not exist opCodes[0x1C] = new Instruction[]{INT, SHORT, SHORT, SHORT}; opCodes[0x1D] = new Instruction[]{BYTE_INT}; opCodes[0x1E] = new Instruction[]{INT}; opCodes[0x1F] = new Instruction[]{INT, BYTE, BYTE, BYTE}; opCodes[0x20] = new Instruction[]{INT, BYTE, BYTE}; opCodes[0x21] = new Instruction[]{INT, BYTE, BYTE, BYTE, BYTE, BYTE}; opCodes[0x22] = new Instruction[]{INT, INT, INT, INT, BYTE, BYTE}; opCodes[0x23] = new Instruction[]{INT, BYTE}; opCodes[0x24] = null; // Does not exist opCodes[0x25] = null; // Does not exist opCodes[0x26] = new Instruction[]{INT, BYTE}; opCodes[0x27] = new Instruction[]{INT, INT}; opCodes[0x28] = new Instruction[]{INT, METADATA}; opCodes[0x29] = new Instruction[]{INT, BYTE, BYTE, SHORT}; opCodes[0x2A] = new Instruction[]{INT, BYTE}; opCodes[0x2B] = new Instruction[]{FLOAT, SHORT, SHORT}; // 0x2C -> 0x32 Do not exist opCodes[0x33] = new Instruction[]{INT, INT, BOOLEAN, SHORT, SHORT, INT_BYTE}; opCodes[0x34] = new Instruction[]{INT, INT, SHORT, INT_BYTE}; opCodes[0x35] = new Instruction[]{INT, BYTE, INT, SHORT, BYTE}; opCodes[0x36] = new Instruction[]{INT, SHORT, INT, BYTE, BYTE, SHORT}; opCodes[0x37] = new Instruction[]{INT, INT, INT, INT, BYTE}; opCodes[0x38] = new Instruction[]{BULK_CHUNK}; opCodes[0x39] = null; // Does not exist opCodes[0x3A] = null; // Does not exist opCodes[0x3B] = null; // Does not exist opCodes[0x3C] = new Instruction[]{DOUBLE, DOUBLE, DOUBLE, FLOAT, INT_3, FLOAT, FLOAT, FLOAT}; opCodes[0x3D] = new Instruction[]{INT, INT, BYTE, INT, INT}; opCodes[0x3E] = new Instruction[]{STRING, INT, INT, INT, FLOAT, BYTE}; // 0x3F -> 0x45 Do not exist opCodes[0x46] = new Instruction[]{BYTE, BYTE}; opCodes[0x47] = new Instruction[]{INT, BOOLEAN, INT, INT, INT}; // 0x4A -> 0x63 Do not exist opCodes[0x64] = new Instruction[]{BYTE, BYTE, STRING, BYTE}; opCodes[0x65] = new Instruction[]{BYTE}; opCodes[0x66] = new Instruction[]{BYTE, SHORT, BOOLEAN, SHORT, BOOLEAN, ITEM}; opCodes[0x67] = new Instruction[]{BYTE, SHORT, ITEM}; opCodes[0x68] = new Instruction[]{BYTE, SHORT_ITEM}; opCodes[0x69] = new Instruction[]{BYTE, SHORT, SHORT}; opCodes[0x6A] = new Instruction[]{BYTE, SHORT, BOOLEAN}; opCodes[0x6B] = new Instruction[]{SHORT, ITEM}; opCodes[0x6C] = new Instruction[]{BYTE, BYTE}; // 0x6D -> 0x81 Do not exist opCodes[0x82] = new Instruction[]{INT, SHORT, INT, STRING, STRING, STRING, STRING}; opCodes[0x83] = new Instruction[]{SHORT, SHORT, UBYTE_BYTE}; opCodes[0x84] = new Instruction[]{INT, SHORT, INT, BYTE, SHORT_BYTE}; // 0x85 -> 0xC7 Do not exist opCodes[0xC8] = new Instruction[]{INT, BYTE}; opCodes[0xC9] = new Instruction[]{STRING, BOOLEAN, SHORT}; opCodes[0xCA] = new Instruction[]{BYTE, BYTE, BYTE}; opCodes[0xCB] = new Instruction[]{STRING}; opCodes[0xCC] = new Instruction[]{STRING, BYTE, BYTE, BYTE}; opCodes[0xCD] = new Instruction[]{BYTE}; // 0xCE -> 0xF9 Do not exist opCodes[0xFA] = new Instruction[]{STRING, SHORT_BYTE}; opCodes[0xFB] = null; // Does not exist opCodes[0xFC] = new Instruction[]{SHORT_BYTE, SHORT_BYTE}; opCodes[0xFD] = new Instruction[]{STRING, SHORT_BYTE, SHORT_BYTE}; opCodes[0xFE] = new Instruction[]{}; opCodes[0xFF] = new Instruction[]{STRING}; crushInstructions(); } private static void crushInstructions() { for (int i = 0; i < opCodes.length; i++) { Instruction[] instructions = opCodes[i]; if (instructions != null) { List<Instruction> crushed = new ArrayList<Instruction>(); int nextJumpSize = 0; for (Instruction child : instructions) { if (child instanceof JumpOpCode) { nextJumpSize += ((JumpOpCode) child).len; } else { if (nextJumpSize != 0) { crushed.add(new JumpOpCode(nextJumpSize)); } crushed.add(child); nextJumpSize = 0; } } if (nextJumpSize != 0) { crushed.add(new JumpOpCode(nextJumpSize)); } opCodes[i] = crushed.toArray(new Instruction[crushed.size()]); } } } public static void readPacket(DataInput in) throws IOException { int packetId = in.readUnsignedByte(); Instruction[] instructions = opCodes[packetId]; if (instructions == null) { throw new IOException("Unknown packet id " + packetId); } for (Instruction instruction : instructions) { instruction.read(in); } } static abstract class Instruction { abstract void read(DataInput in) throws IOException; final void skip(DataInput in, int len) throws IOException { for (int i = 0; i < len; i++) { in.readUnsignedByte(); } } @Override public abstract String toString(); } static class JumpOpCode extends Instruction { private final int len; public JumpOpCode(int len) { if (len < 0) { throw new IndexOutOfBoundsException(); } this.len = len; } @Override void read(DataInput in) throws IOException { skip(in, len); } @Override public String toString() { return "Jump(" + len + ")"; } } static class ByteHeader extends Instruction { private final Instruction child; public ByteHeader(Instruction child) { this.child = child; } @Override void read(DataInput in) throws IOException { byte size = in.readByte(); for (byte b = 0; b < size; b++) { child.read(in); } } @Override public String toString() { return "ByteHeader(" + child + ")"; } } static class ShortHeader extends Instruction { private final Instruction child; public ShortHeader(Instruction child) { this.child = child; } @Override void read(DataInput in) throws IOException { short size = in.readShort(); for (short s = 0; s < size; s++) { child.read(in); } } @Override public String toString() { return "ShortHeader(" + child + ")"; } } static class IntHeader extends Instruction { private final Instruction child; public IntHeader(Instruction child) { this.child = child; } @Override void read(DataInput in) throws IOException { int size = in.readInt(); for (int i = 0; i < size; i++) { child.read(in); } } @Override public String toString() { return "IntHeader(" + child + ")"; } } }
package net.md_5.mc.protocol; import java.io.DataInput; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PacketDefinitions { private static final Instruction[][] opCodes = new Instruction[256][]; private static final Instruction BYTE = new JumpOpCode(1); private static final Instruction BOOLEAN = BYTE; private static final Instruction SHORT = new JumpOpCode(2); private static final Instruction INT = new JumpOpCode(4); private static final Instruction FLOAT = INT; private static final Instruction LONG = new JumpOpCode(8); private static final Instruction DOUBLE = LONG; private static final Instruction SHORT_BYTE = new ShortHeader(BYTE); private static final Instruction BYTE_INT = new ByteHeader(INT); private static final Instruction INT_BYTE = new IntHeader(BYTE); private static final Instruction INT_3 = new IntHeader(new JumpOpCode(3)); private static final Instruction STRING = new Instruction() { @Override void read(DataInput in) throws IOException { short len = in.readShort(); skip(in, len * 2); } @Override public String toString() { return "String"; } }; private static final Instruction ITEM = new Instruction() { @Override void read(DataInput in) throws IOException { short type = in.readShort(); if (type >= 0) { skip(in, 3); SHORT_BYTE.read(in); } } @Override public String toString() { return "Item"; } }; private static final Instruction SHORT_ITEM = new ShortHeader(ITEM); private static final Instruction METADATA = new Instruction() { @Override void read(DataInput in) throws IOException { byte x = in.readByte(); while (x != 127) { int type = x >> 5; switch (type) { case 0: BYTE.read(in); break; case 1: SHORT.read(in); break; case 2: INT.read(in); break; case 3: FLOAT.read(in); break; case 4: STRING.read(in); break; case 5: skip(in, 5); // short, byte, short break; case 6: skip(in, 6); // int, int, int break; default: throw new IllegalArgumentException("Unknown metadata type " + type); } x = in.readByte(); } } @Override public String toString() { return "Metadata"; } }; private static final Instruction BULK_CHUNK = new Instruction() { @Override void read(DataInput in) throws IOException { short count = in.readShort(); INT_BYTE.read(in); skip(in, count * 12); } @Override public String toString() { return "Bulk Chunk"; } }; private static final Instruction UBYTE_BYTE = new Instruction() { @Override void read(DataInput in) throws IOException { int size = in.readUnsignedByte(); skip(in, size); } @Override public String toString() { return "Unsigned Byte Byte"; } }; static { opCodes[0x00] = new Instruction[]{INT}; opCodes[0x01] = new Instruction[]{INT, STRING, BYTE, BYTE, BYTE, BYTE, BYTE}; opCodes[0x02] = new Instruction[]{BYTE, STRING, STRING, INT}; opCodes[0x03] = new Instruction[]{STRING}; opCodes[0x04] = new Instruction[]{LONG}; opCodes[0x05] = new Instruction[]{INT, SHORT, ITEM}; opCodes[0x06] = new Instruction[]{INT, INT, INT}; opCodes[0x07] = new Instruction[]{INT, INT, BOOLEAN}; opCodes[0x08] = new Instruction[]{SHORT, SHORT, FLOAT}; opCodes[0x09] = new Instruction[]{INT, BYTE, BYTE, SHORT, STRING}; opCodes[0x0A] = new Instruction[]{BOOLEAN}; opCodes[0x0B] = new Instruction[]{DOUBLE, DOUBLE, DOUBLE, DOUBLE, BOOLEAN}; opCodes[0x0C] = new Instruction[]{FLOAT, FLOAT, BOOLEAN}; opCodes[0x0D] = new Instruction[]{DOUBLE, DOUBLE, DOUBLE, DOUBLE, FLOAT, FLOAT, BOOLEAN}; opCodes[0x0E] = new Instruction[]{BYTE, INT, BYTE, INT, BYTE}; opCodes[0x0F] = new Instruction[]{INT, BYTE, INT, ITEM, BYTE, BYTE, BYTE}; opCodes[0x10] = new Instruction[]{SHORT}; opCodes[0x11] = new Instruction[]{INT, BYTE, INT, BYTE, INT}; opCodes[0x12] = new Instruction[]{INT, BYTE}; opCodes[0x13] = new Instruction[]{INT, BYTE}; opCodes[0x14] = new Instruction[]{INT, STRING, INT, INT, INT, BYTE, BYTE, SHORT, METADATA}; opCodes[0x15] = new Instruction[]{INT, SHORT, BYTE, SHORT, INT, INT, INT, BYTE, BYTE, BYTE}; opCodes[0x16] = new Instruction[]{INT, INT}; opCodes[0x17] = new Instruction[]{INT, BYTE, INT, INT, INT, INT, SHORT, SHORT, SHORT}; opCodes[0x18] = new Instruction[]{INT, BYTE, INT, INT, INT, BYTE, BYTE, BYTE, SHORT, SHORT, SHORT, METADATA}; opCodes[0x19] = new Instruction[]{INT, STRING, INT, INT, INT, INT}; opCodes[0x1A] = new Instruction[]{INT, INT, INT, INT, SHORT}; opCodes[0x1B] = null; // Does not exist opCodes[0x1C] = new Instruction[]{INT, SHORT, SHORT, SHORT}; opCodes[0x1D] = new Instruction[]{BYTE_INT}; opCodes[0x1E] = new Instruction[]{INT}; opCodes[0x1F] = new Instruction[]{INT, BYTE, BYTE, BYTE}; opCodes[0x20] = new Instruction[]{INT, BYTE, BYTE}; opCodes[0x21] = new Instruction[]{INT, BYTE, BYTE, BYTE, BYTE, BYTE}; opCodes[0x22] = new Instruction[]{INT, INT, INT, INT, BYTE, BYTE}; opCodes[0x23] = new Instruction[]{INT, BYTE}; opCodes[0x24] = null; // Does not exist opCodes[0x25] = null; // Does not exist opCodes[0x26] = new Instruction[]{INT, BYTE}; opCodes[0x27] = new Instruction[]{INT, INT}; opCodes[0x28] = new Instruction[]{INT, METADATA}; opCodes[0x29] = new Instruction[]{INT, BYTE, BYTE, SHORT}; opCodes[0x2A] = new Instruction[]{INT, BYTE}; opCodes[0x2B] = new Instruction[]{FLOAT, SHORT, SHORT}; // 0x2C -> 0x32 Do not exist opCodes[0x33] = new Instruction[]{INT, INT, BOOLEAN, SHORT, SHORT, INT_BYTE}; opCodes[0x34] = new Instruction[]{INT, INT, SHORT, INT_BYTE}; opCodes[0x35] = new Instruction[]{INT, BYTE, INT, SHORT, BYTE}; opCodes[0x36] = new Instruction[]{INT, SHORT, INT, BYTE, BYTE, SHORT}; opCodes[0x37] = new Instruction[]{INT, INT, INT, INT, BYTE}; opCodes[0x38] = new Instruction[]{BULK_CHUNK}; opCodes[0x39] = null; // Does not exist opCodes[0x3A] = null; // Does not exist opCodes[0x3B] = null; // Does not exist opCodes[0x3C] = new Instruction[]{DOUBLE, DOUBLE, DOUBLE, FLOAT, INT_3, FLOAT, FLOAT, FLOAT}; opCodes[0x3D] = new Instruction[]{INT, INT, BYTE, INT, INT}; opCodes[0x3E] = new Instruction[]{STRING, INT, INT, INT, FLOAT, BYTE}; // 0x3F -> 0x45 Do not exist opCodes[0x46] = new Instruction[]{BYTE, BYTE}; opCodes[0x47] = new Instruction[]{INT, BOOLEAN, INT, INT, INT}; // 0x4A -> 0x63 Do not exist opCodes[0x64] = new Instruction[]{BYTE, BYTE, STRING, BYTE}; opCodes[0x65] = new Instruction[]{BYTE}; opCodes[0x66] = new Instruction[]{BYTE, SHORT, BOOLEAN, SHORT, BOOLEAN, ITEM}; opCodes[0x67] = new Instruction[]{BYTE, SHORT, ITEM}; opCodes[0x68] = new Instruction[]{BYTE, SHORT_ITEM}; opCodes[0x69] = new Instruction[]{BYTE, SHORT, SHORT}; opCodes[0x6A] = new Instruction[]{BYTE, SHORT, BOOLEAN}; opCodes[0x6B] = new Instruction[]{SHORT, ITEM}; opCodes[0x6C] = new Instruction[]{BYTE, BYTE}; // 0x6D -> 0x81 Do not exist opCodes[0x82] = new Instruction[]{INT, SHORT, INT, STRING, STRING, STRING, STRING}; opCodes[0x83] = new Instruction[]{SHORT, SHORT, UBYTE_BYTE}; opCodes[0x84] = new Instruction[]{INT, SHORT, INT, BYTE, SHORT_BYTE}; // 0x85 -> 0xC7 Do not exist opCodes[0xC8] = new Instruction[]{INT, BYTE}; opCodes[0xC9] = new Instruction[]{STRING, BOOLEAN, SHORT}; opCodes[0xCA] = new Instruction[]{BYTE, BYTE, BYTE}; opCodes[0xCB] = new Instruction[]{STRING}; opCodes[0xCC] = new Instruction[]{STRING, BYTE, BYTE, BYTE}; opCodes[0xCD] = new Instruction[]{BYTE}; // 0xCE -> 0xF9 Do not exist opCodes[0xFA] = new Instruction[]{STRING, SHORT_BYTE}; opCodes[0xFB] = null; // Does not exist opCodes[0xFC] = new Instruction[]{SHORT_BYTE, SHORT_BYTE}; opCodes[0xFD] = new Instruction[]{STRING, SHORT_BYTE, SHORT_BYTE}; opCodes[0xFE] = new Instruction[]{}; opCodes[0xFF] = new Instruction[]{STRING}; crushInstructions(); } private static void crushInstructions() { for (int i = 0; i < opCodes.length; i++) { Instruction[] instructions = opCodes[i]; if (instructions != null) { List<Instruction> crushed = new ArrayList<Instruction>(); int nextJumpSize = 0; for (Instruction child : instructions) { if (child instanceof JumpOpCode) { nextJumpSize += ((JumpOpCode) child).len; } else { if (nextJumpSize != 0) { crushed.add(new JumpOpCode(nextJumpSize)); } crushed.add(child); nextJumpSize = 0; } } if (nextJumpSize != 0) { crushed.add(new JumpOpCode(nextJumpSize)); } opCodes[i] = crushed.toArray(new Instruction[crushed.size()]); } } } public static void readPacket(DataInput in) throws IOException { int packetId = in.readUnsignedByte(); Instruction[] instructions = opCodes[packetId]; if (instructions == null) { throw new IOException("Unknown packet id " + packetId); } for (Instruction instruction : instructions) { instruction.read(in); } } static abstract class Instruction { abstract void read(DataInput in) throws IOException; final void skip(DataInput in, int len) throws IOException { for (int i = 0; i < len; i++) { in.readByte(); } } @Override public abstract String toString(); } static class JumpOpCode extends Instruction { private final int len; public JumpOpCode(int len) { if (len < 0) { throw new IndexOutOfBoundsException(); } this.len = len; } @Override void read(DataInput in) throws IOException { skip(in, len); } @Override public String toString() { return "Jump(" + len + ")"; } } static class ByteHeader extends Instruction { private final Instruction child; public ByteHeader(Instruction child) { this.child = child; } @Override void read(DataInput in) throws IOException { byte size = in.readByte(); for (byte b = 0; b < size; b++) { child.read(in); } } @Override public String toString() { return "ByteHeader(" + child + ")"; } } static class ShortHeader extends Instruction { private final Instruction child; public ShortHeader(Instruction child) { this.child = child; } @Override void read(DataInput in) throws IOException { short size = in.readShort(); for (short s = 0; s < size; s++) { child.read(in); } } @Override public String toString() { return "ShortHeader(" + child + ")"; } } static class IntHeader extends Instruction { private final Instruction child; public IntHeader(Instruction child) { this.child = child; } @Override void read(DataInput in) throws IOException { int size = in.readInt(); for (int i = 0; i < size; i++) { child.read(in); } } @Override public String toString() { return "IntHeader(" + child + ")"; } } }
package nl.wiegman.home.repository; import nl.wiegman.home.model.Klimaat; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import javax.transaction.Transactional; import java.util.Date; import java.util.List; @Transactional public interface KlimaatRepo extends JpaRepository<Klimaat, Long> { // JPQL queries String MOST_RECENT = "SELECT k FROM Klimaat k WHERE k.datumtijd = (SELECT MAX(mostrecent.datumtijd) FROM Klimaat mostrecent)"; // Native queries String PEAK_HIGH_TEMPERATURE_DATES = "SELECT datum FROM (SELECT date(datumtijd) AS datum, MAX(temperatuur) AS temperatuur FROM klimaat GROUP BY date(datumtijd) HAVING datum >= :van and datum < :tot ORDER BY temperatuur DESC LIMIT :limit) datums"; String FIRST_HIGHEST_TEMPERATURE_ON_DAY = "SELECT * FROM klimaat WHERE date(datumtijd) = :date ORDER BY temperatuur DESC, datumtijd ASC LIMIT 1"; String PEAK_LOW_TEMPERATURE_DATES = "SELECT datum FROM (SELECT date(datumtijd) AS datum, MIN(temperatuur) AS temperatuur FROM klimaat GROUP BY date(datumtijd) HAVING datum >= :van and datum < :tot ORDER BY temperatuur ASC LIMIT :limit) datums"; String FIRST_LOWEST_TEMPERATURE_ON_DAY = "SELECT * FROM klimaat WHERE date(datumtijd) = :date ORDER BY temperatuur ASC, datumtijd ASC LIMIT 1"; String PEAK_HIGH_HUMIDITY_DATES = "SELECT datum FROM (SELECT date(datumtijd) AS datum, MAX(luchtvochtigheid) AS luchtvochtigheid FROM klimaat GROUP BY date(datumtijd) HAVING luchtvochtigheid IS NOT NULL AND datum >= :van and datum < :tot ORDER BY luchtvochtigheid DESC LIMIT :limit) datums"; String FIRST_HIGHEST_HUMIDITY_ON_DAY = "SELECT * FROM klimaat WHERE date(datumtijd) = :date ORDER BY luchtvochtigheid DESC, datumtijd ASC LIMIT 1"; String PEAK_LOW_HUMIDITY_DATES = "SELECT datum FROM (SELECT date(datumtijd) AS datum, MIN(luchtvochtigheid) AS luchtvochtigheid FROM klimaat GROUP BY date(datumtijd) HAVING luchtvochtigheid IS NOT NULL AND datum >= :van AND datum < :tot ORDER BY luchtvochtigheid ASC LIMIT :limit) datums"; String FIRST_LOWEST_HUMIDITY_ON_DAY = "SELECT * FROM klimaat WHERE date(datumtijd) = :date ORDER BY luchtvochtigheid ASC, datumtijd ASC LIMIT 1"; List<Klimaat> findByDatumtijdBetweenOrderByDatumtijd(@Param("van") Date van, @Param("tot") Date tot); @Query(value = MOST_RECENT) Klimaat getMostRecent(); @Query(value = PEAK_HIGH_TEMPERATURE_DATES, nativeQuery = true) List<Date> getPeakHighTemperatureDates(@Param("van") Date van, @Param("tot") Date tot, @Param("limit") int limit); @Query(value = FIRST_HIGHEST_TEMPERATURE_ON_DAY, nativeQuery = true) Klimaat firstHighestTemperatureOnDay(@Param("date") Date day); @Query(value = PEAK_LOW_TEMPERATURE_DATES, nativeQuery = true) List<Date> getPeakLowTemperatureDates(@Param("van") Date van, @Param("tot") Date tot, @Param("limit") int limit); @Query(value = FIRST_LOWEST_TEMPERATURE_ON_DAY, nativeQuery = true) Klimaat firstLowestTemperatureOnDay(@Param("date") Date day); @Query(value = PEAK_HIGH_HUMIDITY_DATES, nativeQuery = true) List<Date> getPeakHighHumidityDates(@Param("van") Date van, @Param("tot") Date tot, @Param("limit") int limit); @Query(value = FIRST_HIGHEST_HUMIDITY_ON_DAY, nativeQuery = true) Klimaat firstHighestHumidityOnDay(@Param("date") Date day); @Query(value = PEAK_LOW_HUMIDITY_DATES, nativeQuery = true) List<Date> getPeakLowHumidityDates(@Param("van") Date van, @Param("tot") Date tot, @Param("limit") int limit); @Query(value = FIRST_LOWEST_HUMIDITY_ON_DAY, nativeQuery = true) Klimaat firstLowestHumidityOnDay(@Param("date") Date day); }
package org.analogweb.core.response; import java.nio.charset.Charset; import java.util.Map; import org.analogweb.Renderable; import org.analogweb.RequestContext; import org.analogweb.ResponseContext; import org.analogweb.ResponseContext.ResponseEntity; import org.analogweb.core.DefaultResponseEntity; import org.analogweb.util.StringUtils; /** * {@link Renderable}<br/> * Content-Typetext/plain UTF-8 * @author snowgoose */ public class TextFormat<T extends TextFormat<T>> extends BuildableResponse<T> implements Renderable { private static final String DEFAULT_CHARSET = "UTF-8"; private static final String DEFAULT_CONTENT_TYPE = "text/plain"; private final String responseText; private String contentType = DEFAULT_CONTENT_TYPE; private String charset = DEFAULT_CHARSET; protected TextFormat() { this(StringUtils.EMPTY, DEFAULT_CONTENT_TYPE, DEFAULT_CHARSET); } protected TextFormat(String input) { this(input, DEFAULT_CONTENT_TYPE, DEFAULT_CHARSET); } protected TextFormat(String input, String contentType, String charset) { super(); this.responseText = StringUtils.isEmpty(input) ? StringUtils.EMPTY : input; this.charset = charset; this.contentType = contentType; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T extends TextFormat> T with(final String responseText) { return (T) new TextFormat(responseText); } @SuppressWarnings("unchecked") public T typeAs(String contentType) { this.contentType = contentType; return (T) this; } @SuppressWarnings("unchecked") public T withCharset(String charset) { if (StringUtils.isNotEmpty(charset)) { this.charset = charset; } return (T) this; } @SuppressWarnings("unchecked") public T withoutCharset() { this.charset = StringUtils.EMPTY; return (T) this; } @Override protected ResponseEntity extractResponseEntity(RequestContext request, ResponseContext response) { Charset cs = getCharset(); if (cs == null) { return new DefaultResponseEntity(getResponseText()); } else { return new DefaultResponseEntity(getResponseText(), cs); } } @Override protected void mergeHeaders(RequestContext request, ResponseContext response, Map<String, String> headers, ResponseEntity entity) { super.mergeHeaders(request, response, headers, entity); String contentType = resolveContentType(); if (StringUtils.isNotEmpty(contentType)) { response.getResponseHeaders().putValue("Content-Type", contentType); } } protected String getResponseText() { return this.responseText; } public Charset getCharset() { String cs = getCharsetAsText(); if (StringUtils.isEmpty(cs)) { return null; } return Charset.forName(cs); } public final String getCharsetAsText() { return this.charset; } protected String resolveContentType() { String charset = getCharsetAsText(); if (StringUtils.isEmpty(charset)) { return this.contentType; } else { return new StringBuilder(32).append(this.contentType).append("; charset=") .append(getCharsetAsText()).toString(); } } @Override public String toString() { return responseText; } }
package org.cobbzilla.util.daemon; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.SystemUtils; import org.cobbzilla.util.collection.ToStringTransformer; import org.cobbzilla.util.error.ExceptionHandler; import org.cobbzilla.util.error.GeneralErrorHandler; import org.cobbzilla.util.io.StreamUtil; import org.cobbzilla.util.string.StringUtil; import org.slf4j.Logger; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import static java.lang.Long.toHexString; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.LongStream.range; import static org.apache.commons.collections.CollectionUtils.collect; import static org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace; import static org.cobbzilla.util.error.ExceptionHandler.DEFAULT_EX_RUNNABLE; import static org.cobbzilla.util.io.FileUtil.abs; import static org.cobbzilla.util.io.FileUtil.list; import static org.cobbzilla.util.reflect.ReflectionUtil.instantiate; import static org.cobbzilla.util.security.ShaUtil.sha256_hex; import static org.cobbzilla.util.string.StringUtil.ellipsis; import static org.cobbzilla.util.string.StringUtil.truncate; import static org.cobbzilla.util.system.Sleep.sleep; import static org.cobbzilla.util.time.TimeUtil.formatDuration; /** * the Zilla doesn't mess around. */ @Slf4j public class ZillaRuntime { public static final String CLASSPATH_PREFIX = "classpath:"; public static String getJava() { return System.getProperty("java.home") + "/bin/java"; } public static boolean terminate(Thread thread, long timeout) { if (thread == null || !thread.isAlive()) return true; thread.interrupt(); final long start = realNow(); while (thread.isAlive() && realNow() - start < timeout) { sleep(100, "terminate: waiting for thread to exit: "+thread); } if (thread.isAlive()) { log.warn("terminate: thread did not respond to interrupt, killing it: "+thread); thread.stop(); return false; } else { log.warn("terminate: thread exited after interrupt: "+thread); return true; } } public static boolean bool(Boolean b) { return b != null && b; } public static boolean bool(Boolean b, boolean val) { return b != null ? b : val; } public static Thread background (Runnable r) { return background(r, DEFAULT_EX_RUNNABLE); } public static Thread background (Runnable r, ExceptionHandler ex) { final Thread t = new Thread(() -> { try { r.run(); } catch (Exception e) { ex.handle(e); } }); t.start(); return t; } public static final Function<Integer, Long> DEFAULT_RETRY_BACKOFF = SECONDS::toMillis; public static <T> T retry (Callable<T> func, int tries) { return retry(func, tries, DEFAULT_RETRY_BACKOFF, DEFAULT_EX_RUNNABLE); } public static <T> T retry (Callable<T> func, int tries, Function<Integer, Long> backoff) { return retry(func, tries, backoff, DEFAULT_EX_RUNNABLE); } public static <T> T retry (Callable<T> func, int tries, Logger logger) { return retry(func, tries, DEFAULT_RETRY_BACKOFF, e -> logger.error("Error: "+e)); } public static <T> T retry (Callable<T> func, int tries, Function<Integer, Long> backoff, Logger logger) { return retry(func, tries, backoff, e -> logger.error("Error: "+e)); } public static <T> T retry (Callable<T> func, int tries, Function<Integer, Long> backoff, ExceptionHandler ex) { Exception lastEx = null; try { for (int i = 0; i < tries; i++) { try { final T rVal = func.call(); log.debug("retry: successful, returning: " + rVal); return rVal; } catch (Exception e) { lastEx = e; log.debug("retry: failed (attempt " + (i + 1) + "/" + tries + "): " + e); ex.handle(e); sleep(backoff.apply(i), "waiting to retry " + func.getClass().getSimpleName()); } } } catch (Exception e) { return die("retry: fatal exception, exiting: "+e); } return die("retry: max tries ("+tries+") exceeded. last exception: "+lastEx); } public static Thread daemon (Runnable r) { return daemon(r, null); } public static Thread daemon (Runnable r, String name) { final Thread t = new Thread(r); t.setDaemon(true); t.setName(empty(name) ? r.getClass().getSimpleName() : name); t.start(); return t; } @Getter @Setter private static ErrorApi errorApi; public static <T> T die(String message) { return _throw(new IllegalStateException(message, null)); } public static <T> T die(String message, Exception e) { return _throw(new IllegalStateException(message, e)); } public static <T> T die(Exception e) { return _throw(new IllegalStateException("(no message)", e)); } public static <T> T notSupported() { return notSupported("not supported"); } public static <T> T notSupported(String message) { return _throw(new UnsupportedOperationException(message)); } private static <T> T _throw (RuntimeException e) { final String message = e.getMessage(); final Throwable cause = e.getCause(); if (errorApi != null) { if (cause instanceof Exception) errorApi.report(message, (Exception) cause); else errorApi.report(e); } if (cause != null) { if (log.isDebugEnabled()) { log.debug("Inner exception: " + message, cause); } else { log.error("Inner exception: " + message + ": "+ shortError(cause)); } } throw e; } public static String shortError(Throwable e) { return e == null ? "null" : e.getClass().getName()+": "+e.getMessage(); } public static String errorString(Exception e) { return errorString(e, 1000); } public static String errorString(Exception e, int maxlen) { return truncate(shortError(e)+"\n"+ getStackTrace(e), maxlen); } public static String fullError(Exception e) { final StringBuilder b = new StringBuilder(shortError(e)); Throwable cause = e.getCause(); while (cause != null) { b.append("\ncaused by: ").append(shortError(cause)); cause = cause.getCause(); } b.append("\n\n return b.toString(); } public static boolean empty(String s) { return s == null || s.length() == 0; } public static boolean notEmpty(String s) { return !empty(s); } /** * Determines if the parameter is "empty", by criteria described in @return * Tries to avoid throwing exceptions, handling just about any case in a true/false fashion. * * @param o anything * @return true if and only o is: * * null * * a collection, map, iterable or array that contains no objects * * a file that does not exist or whose size is zero * * a directory that does not exist or that contains no files * * any object whose .toString method returns a zero-length string */ public static boolean empty(Object o) { if (o == null) return true; if (o instanceof String) return o.toString().length() == 0; if (o instanceof Collection) return ((Collection)o).isEmpty(); if (o instanceof Map) return ((Map)o).isEmpty(); if (o instanceof JsonNode) { if (o instanceof ObjectNode) return ((ObjectNode) o).size() == 0; if (o instanceof ArrayNode) return ((ArrayNode) o).size() == 0; final String json = ((JsonNode) o).textValue(); return json == null || json.length() == 0; } if (o instanceof Iterable) return !((Iterable)o).iterator().hasNext(); if (o instanceof File) { final File f = (File) o; return !f.exists() || f.length() == 0 || (f.isDirectory() && list(f).length == 0); } if (o.getClass().isArray()) { if (o.getClass().getComponentType().isPrimitive()) { switch (o.getClass().getComponentType().getName()) { case "boolean": return ((boolean[]) o).length == 0; case "byte": return ((byte[]) o).length == 0; case "short": return ((short[]) o).length == 0; case "char": return ((char[]) o).length == 0; case "int": return ((int[]) o).length == 0; case "long": return ((long[]) o).length == 0; case "float": return ((float[]) o).length == 0; case "double": return ((double[]) o).length == 0; default: return o.toString().length() == 0; } } else { return ((Object[]) o).length == 0; } } return o.toString().length() == 0; } public static <T> T first (Iterable<T> o) { return (T) ((Iterable) o).iterator().next(); } public static <K, T> T first (Map<K, T> o) { return first(o.values()); } public static <T> T first (T[] o) { return o[0]; } public static <T> T sorted(T o) { if (empty(o)) return o; if (o.getClass().isArray()) { final Object[] copy = (Object[]) Array.newInstance(o.getClass().getComponentType(), ((Object[])o).length); System.arraycopy(o, 0, copy, 0 , copy.length); Arrays.sort(copy); return (T) copy; } if (o instanceof Collection) { final List list = new ArrayList((Collection) o); Collections.sort(list); final Collection copy = (Collection) instantiate(o.getClass()); copy.addAll(list); return (T) copy; } return die("sorted: cannot sort a "+o.getClass().getSimpleName()+", can only sort arrays and Collections"); } public static <T> List toList(T o) { if (o == null) return null; if (o instanceof Collection) return new ArrayList((Collection) o); if (o instanceof Object[]) return Arrays.asList((Object[]) o); return die("sortedList: cannot sort a "+o.getClass().getSimpleName()+", can only sort arrays and Collections"); } public static Boolean safeBoolean(String val, Boolean ifNull) { return empty(val) ? ifNull : Boolean.valueOf(val); } public static Boolean safeBoolean(String val) { return safeBoolean(val, null); } public static Integer safeInt(String val, Integer ifNull) { return empty(val) ? ifNull : Integer.valueOf(val); } public static Integer safeInt(String val) { return safeInt(val, null); } public static Long safeLong(String val, Long ifNull) { return empty(val) ? ifNull : Long.valueOf(val); } public static Long safeLong(String val) { return safeLong(val, null); } public static BigInteger bigint(long val) { return new BigInteger(String.valueOf(val)); } public static BigInteger bigint(int val) { return new BigInteger(String.valueOf(val)); } public static BigInteger bigint(byte val) { return new BigInteger(String.valueOf(val)); } public static BigDecimal big(String val) { return new BigDecimal(val); } public static BigDecimal big(double val) { return new BigDecimal(String.valueOf(val)); } public static BigDecimal big(float val) { return new BigDecimal(String.valueOf(val)); } public static BigDecimal big(long val) { return new BigDecimal(String.valueOf(val)); } public static BigDecimal big(int val) { return new BigDecimal(String.valueOf(val)); } public static BigDecimal big(byte val) { return new BigDecimal(String.valueOf(val)); } public static int percent(int value, double pct) { return percent(value, pct, RoundingMode.HALF_UP); } public static int percent(int value, double pct, RoundingMode rounding) { return big(value).multiply(big(pct)).setScale(0, rounding).intValue(); } public static int percent(BigDecimal value, BigDecimal pct) { return percent(value.intValue(), pct.multiply(big(0.01)).doubleValue(), RoundingMode.HALF_UP); } public static String uuid() { return UUID.randomUUID().toString(); } private static AtomicLong systemTimeOffset = new AtomicLong(0L); public static long getSystemTimeOffset () { return systemTimeOffset.get(); } public static void setSystemTimeOffset (long t) { systemTimeOffset.set(t); } public static long incrementSystemTimeOffset(long t) { return systemTimeOffset.addAndGet(t); } public static long now() { return System.currentTimeMillis() + systemTimeOffset.get(); } public static String hexnow() { return toHexString(now()); } public static String hexnow(long now) { return toHexString(now); } public static long realNow() { return System.currentTimeMillis(); } public static <T> T pickRandom(T[] things) { return things[RandomUtils.nextInt(0, things.length)]; } public static <T> T pickRandom(List<T> things) { return things.get(RandomUtils.nextInt(0, things.size())); } public static BufferedReader stdin() { return new BufferedReader(new InputStreamReader(System.in)); } public static BufferedWriter stdout() { return new BufferedWriter(new OutputStreamWriter(System.out)); } public static String readStdin() { return StreamUtil.toStringOrDie(System.in); } public static int envInt (String name, int defaultValue) { return envInt(name, defaultValue, null, null); } public static int envInt (String name, int defaultValue, Integer maxValue) { return envInt(name, defaultValue, null, maxValue); } public static int envInt (String name, int defaultValue, Integer minValue, Integer maxValue) { return envInt(name, defaultValue, minValue, maxValue, System.getenv()); } public static int envInt (String name, int defaultValue, Integer minValue, Integer maxValue, Map<String, String> env) { final String s = env.get(name); if (!empty(s)) { try { final int val = Integer.parseInt(s); if (val <= 0) { log.warn("envInt: invalid value("+name+"): " +val+", returning "+defaultValue); return defaultValue; } else if (maxValue != null && val > maxValue) { log.warn("envInt: value too large ("+name+"): " +val+ ", returning " + maxValue); return maxValue; } else if (minValue != null && val < minValue) { log.warn("envInt: value too small ("+name+"): " +val+ ", returning " + minValue); return minValue; } return val; } catch (Exception e) { log.warn("envInt: invalid value("+name+"): " +s+", returning "+defaultValue); return defaultValue; } } return defaultValue; } public static int processorCount() { return Runtime.getRuntime().availableProcessors(); } public static String hashOf (Object... things) { final StringBuilder b = new StringBuilder(); for (Object thing : things) { if (b.length() > 0) b.append("\t"); if (thing == null) { b.append("null"); } else if (thing instanceof String) { b.append(thing); } else if (thing instanceof Object[]) { b.append(Arrays.deepHashCode((Object[]) thing)); } else { b.append(thing.hashCode()); } } return sha256_hex(b.toString()); } public static String hexToBase36(String hex) { return new BigInteger(hex, 16).toString(36); } public static Collection<String> stringRange(Number start, Number end) { return collect(range(start.longValue(), end.longValue()).boxed().iterator(), ToStringTransformer.instance); } public static String zcat() { return SystemUtils.IS_OS_MAC ? "gzcat" : "zcat"; } public static String zcat(File f) { return (SystemUtils.IS_OS_MAC ? "gzcat" : "zcat") + " " + abs(f); } public static final String[] JAVA_DEBUG_OPTIONS = {"-Xdebug", "-agentlib", "-Xrunjdwp"}; public static boolean isDebugOption (String arg) { for (String opt : JAVA_DEBUG_OPTIONS) if (arg.startsWith(opt)) return true; return false; } public static String javaOptions() { return javaOptions(true); } public static String javaOptions(boolean excludeDebugOptions) { final List<String> opts = new ArrayList<>(); for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) { if (excludeDebugOptions && isDebugOption(arg)) continue; opts.add(arg); } return StringUtil.toString(opts, " "); } public static <T> T dcl (AtomicReference<T> target, Callable<T> init) { return dcl(target, init, null); } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") public static <T> T dcl (AtomicReference<T> target, Callable<T> init, GeneralErrorHandler error) { if (target.get() == null) { synchronized (target) { if (target.get() == null) { try { target.set(init.call()); } catch (Exception e) { if (error != null) { error.handleError("dcl: error initializing: "+e, e); } else { log.warn("dcl: "+e); return null; } } } } } return target.get(); } public static String stacktrace() { return getStackTrace(new Exception()); } public static String shortStacktrace(int max) { return ellipsis(stacktrace(), max); } private static final AtomicLong selfDestructInitiated = new AtomicLong(-1); public static void setSelfDestruct (long t) { setSelfDestruct(t, 0); } public static void setSelfDestruct (long t, int status) { synchronized (selfDestructInitiated) { final long dieTime = selfDestructInitiated.get(); if (dieTime == -1) { selfDestructInitiated.set(now()+t); daemon(() -> { sleep(t); System.exit(status); }); } else { log.warn("setSelfDestruct: already set: self-destructing in "+formatDuration(dieTime-now())); } } } }
package org.commcare.suite.model; import org.commcare.util.DatumUtil; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.ExtWrapTagged; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.expr.XPathPathExpr; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * Data class for list query data elements * * <pre>{@code * <data * key="case_id_list"> * nodeset="instance('selected-cases')/session-data/value" * exclude="count(instance('casedb')/casedb/case[@case_id = current()/.]) = 1" * ref="." * /> * }</pre> * * The {@code exclude} attribute is optional. */ public class ListQueryData implements QueryData { private String key; private TreeReference nodeset; private XPathExpression excludeExpr; private XPathPathExpr ref; @SuppressWarnings("unused") public ListQueryData() {} public ListQueryData(String key, TreeReference nodeset, XPathExpression excludeExpr, XPathPathExpr ref) { this.key = key; this.nodeset = nodeset; this.excludeExpr = excludeExpr; this.ref = ref; } @Override public String getKey() { return key; } @Override public Iterable<String> getValues(EvaluationContext ec) { List<String> values = new ArrayList<String>(); Vector<TreeReference> result = ec.expandReference(nodeset); for (TreeReference node : result) { EvaluationContext temp = new EvaluationContext(ec, node); if (excludeExpr == null || !(boolean) excludeExpr.eval(temp)) { values.add(DatumUtil.getReturnValueFromSelection(node, ref, ec)); } } return values; } @Override public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { key = ExtUtil.readString(in); nodeset = (TreeReference)ExtUtil.read(in, TreeReference.class, pf); ref = (XPathPathExpr) ExtUtil.read(in, new ExtWrapTagged(), pf); boolean excludeIsNull = ExtUtil.readBool(in); if (excludeIsNull) { excludeExpr = null; } else { excludeExpr = (XPathExpression) ExtUtil.read(in, new ExtWrapTagged(), pf); } } @Override public void writeExternal(DataOutputStream out) throws IOException { ExtUtil.writeString(out, key); ExtUtil.write(out, nodeset); ExtUtil.write(out, new ExtWrapTagged(ref)); boolean excludeIsNull = excludeExpr == null; ExtUtil.write(out, excludeIsNull); } }
package org.graphwalker.java.test; import org.graphwalker.core.condition.ReachedStopCondition; import org.graphwalker.core.condition.StopCondition; import org.graphwalker.core.generator.PathGenerator; import org.graphwalker.core.machine.Context; import org.graphwalker.core.machine.Machine; import org.graphwalker.core.machine.MachineException; import org.graphwalker.core.machine.SimpleMachine; import org.graphwalker.core.model.*; import org.graphwalker.io.factory.ContextFactoryScanner; import org.graphwalker.java.annotation.*; import org.graphwalker.java.annotation.Model; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.nio.file.Paths; import java.nio.file.Path; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.graphwalker.core.model.Model.RuntimeModel; /** * @author Nils Olsson */ public final class TestExecutor { private final Configuration configuration; private final Set<Machine> machines = new HashSet<>(); private final Map<Context, MachineException> failures = new HashMap<>(); public TestExecutor(Configuration configuration) { this.configuration = configuration; List<Context> contexts = createContexts(); if (!contexts.isEmpty()) { this.machines.add(new SimpleMachine(contexts)); } } public Set<Machine> getMachines() { return machines; } private List<Context> createContexts() { List<Context> contexts = new ArrayList<>(); for (Class<?> testClass: AnnotationUtils.findTests()) { GraphWalker annotation = testClass.getAnnotation(GraphWalker.class); if (isTestIncluded(annotation, testClass.getName())) { Context context = createContext(testClass); context.setPathGenerator(createPathGenerator(annotation)); if (!"".equals(annotation.start())) { context.setNextElement(getElement(context.getModel(), annotation.start())); } contexts.add(context); } } return contexts; } private boolean isTestIncluded(GraphWalker annotation, String name) { boolean belongsToGroup = false; for (String group: annotation.groups()) { for (String definedGroups: configuration.getGroups()) { if (SelectorUtils.match(definedGroups, group)) { belongsToGroup = true; break; } } } if (belongsToGroup) { for (String exclude : configuration.getExcludes()) { if (SelectorUtils.match(exclude, name)) { return false; } } for (String include : configuration.getIncludes()) { if (SelectorUtils.match(include, name)) { return true; } } } return false; } private Context createContext(Class<?> testClass) { try { // TODO: support classes with multiple models Set<Model> models = AnnotationUtils.getAnnotations(testClass, Model.class); Context context = (Context)testClass.newInstance(); Path path = Paths.get(models.iterator().next().file()); return ContextFactoryScanner.get(path).create(path, context); } catch (Throwable e) { throw new RuntimeException(e); // TODO: change exception } } private PathGenerator createPathGenerator(GraphWalker annotation) { try { Constructor constructor = null; try { constructor = annotation.pathGenerator().getConstructor(StopCondition.class); } catch (Throwable _) { constructor = annotation.pathGenerator().getConstructor(ReachedStopCondition.class); } if (null == constructor) { throw new TestExecutionException("Couldn't find a valid constructor"); } return (PathGenerator)constructor.newInstance(createStopCondition(annotation)); } catch (Throwable e) { throw new TestExecutionException(e); } } private StopCondition createStopCondition(GraphWalker annotation) { String value = annotation.stopConditionValue(); Class<? extends StopCondition> stopCondition = annotation.stopCondition(); if (value.isEmpty()) { try { return stopCondition.newInstance(); } catch (Throwable e) { // ignore } } try { return stopCondition.getConstructor(new Class[]{String.class}).newInstance(value); } catch (Throwable e) { // ignore } try { return stopCondition.getConstructor(new Class[]{Long.TYPE}).newInstance(Long.parseLong(value)); } catch (Throwable e) { // ignore } try { return stopCondition.getConstructor(new Class[]{Integer.TYPE}).newInstance(Integer.parseInt(value)); } catch (Throwable e) { // ignore } try { return stopCondition.getConstructor(new Class[]{Double.TYPE}).newInstance(Double.parseDouble(value)); } catch (Throwable e) { // ignore } try { return stopCondition.getConstructor(new Class[]{Float.TYPE}).newInstance(Float.parseFloat(value)); } catch (Throwable e) { // ignore } throw new TestExecutionException(); } private Element getElement(RuntimeModel model, String name) { List<Element> elements = model.findElements(name); if (null != elements && !elements.isEmpty()) { Random random = new Random(System.nanoTime()); return elements.get(random.nextInt(elements.size())); } return null; } public void execute() { if (!machines.isEmpty()) { executeAnnotation(BeforeExecution.class, machines); ExecutorService executorService = Executors.newFixedThreadPool(machines.size()); for (final Machine machine : machines) { executorService.execute(new Runnable() { @Override public void run() { machine.addObserver(new LogObserver()); try { Context context = null; while (machine.hasNextStep()) { if (null != context) { executeAnnotation(BeforeElement.class, context); } context = machine.getNextStep(); executeAnnotation(AfterElement.class, context); } } catch (MachineException e) { failures.put(e.getContext(), e); } } }); } executorService.shutdown(); try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch (InterruptedException e) { // ignore } executeAnnotation(AfterExecution.class, machines); } } private void executeAnnotation(Class<? extends Annotation> annotation, Set<Machine> machines) { for (Machine machine: machines) { executeAnnotation(annotation, machine); } } private void executeAnnotation(Class<? extends Annotation> annotation, Machine machine) { for (Context context: machine.getContexts()) { executeAnnotation(annotation, context); } } private void executeAnnotation(Class<? extends Annotation> annotation, Context context) { AnnotationUtils.execute(annotation, context); } public boolean isFailure(Context context) { return failures.containsKey(context); } public MachineException getFailure(Context context) { return failures.get(context); } }
package org.jboss.planet.service; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.ejb.Stateless; import javax.inject.Inject; import javax.inject.Named; import org.jboss.planet.exception.ParserException; import org.jboss.planet.exception.ParserException.CAUSE_TYPE; import org.jboss.planet.model.Category; import org.jboss.planet.model.Configuration; import org.jboss.planet.model.Post; import org.jboss.planet.model.PostStatus; import org.jboss.planet.model.RemoteFeed; import org.jboss.planet.util.StringTools; import com.sun.syndication.feed.synd.SyndCategory; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.io.FeedException; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; import com.sun.syndication.io.impl.Base64; /** * Service related to parsing feeds * * @author Libor Krzyzanek * @author Adam Warski (adam at warski dot org) */ @Named @Stateless public class ParserService { @Inject private CategoryService categoryService; @Inject private ConfigurationService configurationManager; public static final String USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Ubuntu Chromium/24.0.1312.56 Chrome/24.0.1312.56 Safari/537.17"; /** * Parse feed from defined address * * @param link * @param username * username if basic authentication is needed * @param password * password for basic authentication * @return * @throws ParserException */ public RemoteFeed parse(String link, String username, String password) throws ParserException { try { URLConnection conn = getConnection(link); if (username != null && password != null) { String encoding = Base64.encode(username + ":" + password); conn.setRequestProperty("Authorization", "Basic " + encoding); } conn.connect(); return parse(conn.getInputStream()); } catch (MalformedURLException e) { throw new ParserException(e, CAUSE_TYPE.CONNECTION_PROBLEM); } catch (IOException e) { throw new ParserException(e, CAUSE_TYPE.CONNECTION_PROBLEM); } } public SyndFeed getRemoteFeed(String link) throws IllegalArgumentException, FeedException, IOException { URLConnection conn = getConnection(link); InputStream is = conn.getInputStream(); SyndFeedInput input = new SyndFeedInput(); SyndFeed syndFeed = input.build(new XmlReader(is)); is.close(); return syndFeed; } protected URLConnection getConnection(String link) throws IOException { Configuration conf = configurationManager.getConfiguration(); URLConnection conn = new URL(link).openConnection(); conn.setReadTimeout(conf.getReadTimeout()); conn.setConnectTimeout(conf.getConnectionTimeout()); conn.setRequestProperty("User-Agent", USER_AGENT); conn.connect(); return conn; } public RemoteFeed parse(InputStream is) throws ParserException { SyndFeed syndFeed = null; try { SyndFeedInput input = new SyndFeedInput(); syndFeed = input.build(new XmlReader(is)); } catch (FeedException e) { throw new ParserException(e, CAUSE_TYPE.PARSING_EXCEPTION); } catch (IOException e) { throw new ParserException(e, CAUSE_TYPE.CONNECTION_PROBLEM); } RemoteFeed feed = new RemoteFeed(); feed.setAuthor(syndFeed.getAuthor()); feed.setDescription(syndFeed.getDescription()); feed.setLink(syndFeed.getLink()); feed.setTitle(syndFeed.getTitle()); List<Post> posts = new ArrayList<Post>(); feed.setPosts(posts); if (syndFeed.getEntries() != null) { for (Object entryObj : syndFeed.getEntries()) { SyndEntry entry = (SyndEntry) entryObj; Post post = new Post(); post.setFeed(feed); post.setAuthor(StringTools.isEmpty(entry.getAuthor()) ? null : entry.getAuthor()); // Setting content String longestContent = entry.getDescription() == null ? "" : entry.getDescription().getValue(); for (Object contentObj : entry.getContents()) { SyndContent content = (SyndContent) contentObj; String currentContent = content == null ? "" : content.getValue(); if (currentContent.length() > longestContent.length()) { longestContent = currentContent; } } post.setContent(longestContent); // Setting categories post.setCategories(new ArrayList<Category>()); for (Object categoryObj : entry.getCategories()) { SyndCategory category = (SyndCategory) categoryObj; post.getCategories().add(categoryService.getCategory(category.getName())); } // Setting the published date Date publishedDate = entry.getPublishedDate(); if (publishedDate == null) { publishedDate = entry.getUpdatedDate(); } post.setPublished(publishedDate); // And other properties post.setTitle(entry.getTitle()); post.setModified(entry.getUpdatedDate() == null ? post.getPublished() : entry.getUpdatedDate()); post.setLink(entry.getLink()); post.setStatus(PostStatus.CREATED); posts.add(post); } } // TODO Check if sort is needed // Collections.sort(posts); try { is.close(); return feed; } catch (IOException e) { throw new ParserException(e, CAUSE_TYPE.CONNECTION_PROBLEM); } } }
package org.jtrfp.trcl.beh; import java.util.Collection; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.InterpolatingAltitudeMap; import org.jtrfp.trcl.OverworldSystem; import org.jtrfp.trcl.Submitter; import org.jtrfp.trcl.World; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.obj.TerrainChunk; import org.jtrfp.trcl.obj.WorldObject; public class CollidesWithTerrain extends Behavior { private boolean groundLock = false; private Vector3D surfaceNormalVar; public static final double CEILING_Y_NUDGE = -5000; private int tickCounter = 0; private boolean autoNudge = false; private double nudgePadding = 5000; private boolean recentlyCollided = false; @Override public void _tick(long tickTimeMillis) { if (tickCounter++ % 2 == 0 && !recentlyCollided) return; recentlyCollided=false; final WorldObject p = getParent(); final TR tr = p.getTr(); final World world = tr.getWorld(); final InterpolatingAltitudeMap aMap; try{ aMap = tr.getGame(). getCurrentMission(). getOverworldSystem(). getAltitudeMap(); }catch(NullPointerException e){return;} if(tr.getGame().getCurrentMission().getOverworldSystem().isTunnelMode()) return;//No terrain to collide with while in tunnel mode. if(aMap==null)return; final double[] thisPos = p.getPosition(); final double groundHeightNorm = aMap.heightAt( (thisPos[0] / TR.mapSquareSize), (thisPos[2] / TR.mapSquareSize)); final double groundHeight = groundHeightNorm * (world.sizeY / 2); final double ceilingHeight = (1.99 - aMap.heightAt( (thisPos[0] / TR.mapSquareSize), (thisPos[2] / TR.mapSquareSize))) * (world.sizeY / 2) + CEILING_Y_NUDGE; final Vector3D groundNormal = (aMap.normalAt( (thisPos[0] / TR.mapSquareSize), (thisPos[2] / TR.mapSquareSize))); Vector3D downhillDirectionXZ = new Vector3D(groundNormal.getX(), 0, groundNormal.getZ()); if (downhillDirectionXZ.getNorm() != 0) downhillDirectionXZ = downhillDirectionXZ.normalize(); else downhillDirectionXZ = Vector3D.PLUS_J; final OverworldSystem overworldSystem = tr.getGame().getCurrentMission().getOverworldSystem(); if(overworldSystem==null)return; final boolean terrainMirror = overworldSystem.isChamberMode(); final double thisY = thisPos[1]; boolean groundImpact = thisY < (groundHeight + (autoNudge ? nudgePadding : 0)); final boolean ceilingImpact = (thisY > ceilingHeight && terrainMirror); final Vector3D ceilingNormal = new Vector3D(groundNormal.getX(), -groundNormal.getY(), groundNormal.getZ()); Vector3D surfaceNormal = groundImpact ? groundNormal : ceilingNormal; if (terrainMirror && groundHeightNorm > .97) { groundImpact = true; surfaceNormal = downhillDirectionXZ; }//end if(smushed between floor and ceiling) if (groundLock) { recentlyCollided=true; thisPos[1] = groundHeight; p.notifyPositionChange(); return; }//end if(groundLock) if (groundImpact || ceilingImpact) {// detect collision recentlyCollided=true; double padding = autoNudge ? nudgePadding : 0; padding *= groundImpact ? 1 : -1; thisPos[1] = (groundImpact ? groundHeight : ceilingHeight) + padding; p.notifyPositionChange(); // Call impact listeners surfaceNormalVar = surfaceNormal; final Behavior behavior = p.getBehavior(); behavior.probeForBehaviors(sub, SurfaceImpactListener.class); }// end if(collision) }// end _tick private final Submitter<SurfaceImpactListener> sub = new Submitter<SurfaceImpactListener>() { @Override public void submit(SurfaceImpactListener item) { item.collidedWithSurface(new TerrainChunk(getParent().getTr()), surfaceNormalVar.toArray()); } @Override public void submit(Collection<SurfaceImpactListener> items) { for (SurfaceImpactListener l : items) { submit(l); }//end for(items) }//end submit(...) }; /** * @return the autoNudge */ public boolean isAutoNudge() { return autoNudge; } /** * @param autoNudge * the autoNudge to set */ public CollidesWithTerrain setAutoNudge(boolean autoNudge) { this.autoNudge = autoNudge; return this; } /** * @return the nudgePadding */ public double getNudgePadding() { return nudgePadding; } /** * @param nudgePadding * the nudgePadding to set */ public CollidesWithTerrain setNudgePadding(double nudgePadding) { this.nudgePadding = nudgePadding; return this; } }// end BouncesOffTerrain
package org.junit.runners.model; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.List; import org.junit.runners.BlockJUnit4ClassRunner; /** * Represents a field on a test class (currently used only for Rules in * {@link BlockJUnit4ClassRunner}, but custom runners can make other uses) * * @since 4.7 */ public class FrameworkField extends FrameworkMember<FrameworkField> { private final Field field; /** * Returns a new {@code FrameworkField} for {@code field}. * * <p>Access relaxed to {@code public} since version 4.14. */ public FrameworkField(Field field) { if (field == null) { throw new NullPointerException( "FrameworkField cannot be created without an underlying field."); } this.field = field; if (isPublic()) { // This field could be a public field in a package-scope base class try { field.setAccessible(true); } catch (SecurityException e) { } } } @Override public String getName() { return getField().getName(); } public Annotation[] getAnnotations() { return field.getAnnotations(); } public <T extends Annotation> T getAnnotation(Class<T> annotationType) { return field.getAnnotation(annotationType); } @Override public boolean isShadowedBy(FrameworkField otherMember) { return otherMember.getName().equals(getName()); } @Override boolean isBridgeMethod() { return false; } @Override protected int getModifiers() { return field.getModifiers(); } /** * @return the underlying java Field */ public Field getField() { return field; } /** * @return the underlying Java Field type * @see java.lang.reflect.Field#getType() */ @Override public Class<?> getType() { return field.getType(); } @Override public Class<?> getDeclaringClass() { return field.getDeclaringClass(); } /** * Attempts to retrieve the value of this field on {@code target} */ public Object get(Object target) throws IllegalArgumentException, IllegalAccessException { return field.get(target); } @Override public String toString() { return field.toString(); } }
package org.lightmare.deploy; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.lightmare.cache.MetaContainer; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * Manager class for application deployment * * @author levan * */ public class LoaderPoolManager { // Amount of deployment thread pool private static final int LOADER_POOL_SIZE = 5; // Name prefix of deployment threads private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-"; // Lock for pool reopening private static final Lock LOCK = new ReentrantLock(); /** * Tries to lock Lock object if it it not locked else runs loop while Lock * releases and locks it again * * @return <code>boolean</code> */ private static boolean tryLock() { boolean locked = LOCK.tryLock(); while (ObjectUtils.notTrue(locked)) { locked = LOCK.tryLock(); } return locked; } /** * Gets class loader for existing {@link org.lightmare.deploy.MetaCreator} * instance * * @return {@link ClassLoader} */ protected static ClassLoader getCurrent() { ClassLoader current; MetaCreator creator = MetaContainer.getCreator(); ClassLoader creatorLoader; if (ObjectUtils.notNull(creator)) { // Gets class loader for this deployment creatorLoader = creator.getCurrent(); if (ObjectUtils.notNull(creatorLoader)) { current = creatorLoader; } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } return current; } /** * Implementation of {@link ThreadFactory} interface for application loading * * @author levan * */ private static final class LoaderThreadFactory implements ThreadFactory { /** * Constructs and sets thread name * * @param thread */ private void nameThread(Thread thread) { String name = StringUtils .concat(LOADER_THREAD_NAME, thread.getId()); thread.setName(name); } /** * Sets priority of {@link Thread} instance * * @param thread */ private void setPriority(Thread thread) { thread.setPriority(Thread.MAX_PRIORITY); } /** * Sets {@link ClassLoader} to passed {@link Thread} instance * * @param thread */ private void setContextClassLoader(Thread thread) { ClassLoader parent = getCurrent(); thread.setContextClassLoader(parent); } /** * Configures (sets name, priority and {@link ClassLoader}) passed * {@link Thread} instance * * @param thread */ private void configureThread(Thread thread) { nameThread(thread); setPriority(thread); setContextClassLoader(thread); } @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable); configureThread(thread); return thread; } } // Thread pool for deploying and removal of beans and temporal resources private static ExecutorService LOADER_POOL; /** * Checks if loader {@link ExecutorService} is null or is shut down or is * terminated * * @return <code>boolean</code> */ private static boolean invalid() { return LOADER_POOL == null || LOADER_POOL.isShutdown() || LOADER_POOL.isTerminated(); } private static void initLoaderPool() { if (invalid()) { LOADER_POOL = Executors.newFixedThreadPool(LOADER_POOL_SIZE, new LoaderThreadFactory()); } } /** * Checks and if not valid reopens deploy {@link ExecutorService} instance * * @return {@link ExecutorService} */ protected static ExecutorService getLoaderPool() { if (invalid()) { boolean locked = tryLock(); if (locked) { try { initLoaderPool(); } finally { LOCK.unlock(); } } } return LOADER_POOL; } /** * Submit passed {@link Runnable} implementation in loader pool * * @param runnable */ public static void submit(Runnable runnable) { getLoaderPool().submit(runnable); } /** * Submits passed {@link Callable} implementation in loader pool * * @param callable * @return {@link Future}<code><T></code> */ public static <T> Future<T> submit(Callable<T> callable) { Future<T> future = getLoaderPool().submit(callable); return future; } /** * Clears existing {@link ExecutorService}s from loader threads */ public static void reload() { boolean locked = tryLock(); if (locked) { try { if (ObjectUtils.notNull(LOADER_POOL)) { LOADER_POOL.shutdown(); LOADER_POOL = null; } } finally { LOCK.unlock(); } } getLoaderPool(); } }
package org.lightmare.jpa.jta; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import javax.ejb.EJBException; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.hibernate.cfg.NotYetImplementedException; import org.lightmare.cache.MetaData; import org.lightmare.cache.TransactionHolder; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Class to manage {@link javax.transaction.UserTransaction} for * {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls * * @author levan * */ public class BeanTransactions { private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction"; private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction"; private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented"; /** * Inner class to cache {@link EntityTransaction}s and {@link EntityManager} * s in one {@link Collection} for {@link UserTransaction} implementation * * @author levan * */ private static class TransactionData { EntityManager em; EntityTransaction entityTransaction; } private static TransactionData createTransactionData( EntityTransaction entityTransaction, EntityManager em) { TransactionData transactionData = new TransactionData(); transactionData.em = em; transactionData.entityTransaction = entityTransaction; return transactionData; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction( EntityTransaction... entityTransactions) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = new UserTransactionImpl(entityTransactions); TransactionHolder.setTransaction(transaction); } // If entityTransactions array is available then adds it to // UserTransaction object if (CollectionUtils.valid(entityTransactions)) { UserTransactionImpl userTransactionImpl = ObjectUtils.cast( transaction, UserTransactionImpl.class); userTransactionImpl.addTransactions(entityTransactions); } return transaction; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction(Collection<EntityManager> ems) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(); TransactionHolder.setTransaction(transaction); } Collection<TransactionData> entityTransactions = getEntityTransactions(ems); addEntityTransactions((UserTransactionImpl) transaction, entityTransactions); return transaction; } /** * Gets appropriated {@link TransactionAttributeType} for instant * {@link Method} of {@link javax.ejb.Stateless} bean * * @param metaData * @param method * @return {@link TransactionAttributeType} */ public static TransactionAttributeType getTransactionType( MetaData metaData, Method method) { TransactionAttributeType type; if (method == null) { type = null; } else { TransactionAttributeType attrType = metaData .getTransactionAttrType(); TransactionManagementType manType = metaData .getTransactionManType(); TransactionAttribute attr = method .getAnnotation(TransactionAttribute.class); if (manType.equals(TransactionManagementType.CONTAINER)) { if (attr == null) { type = attrType; } else { type = attr.value(); } } else { type = null; } } return type; } /** * Gets status of passed transaction by {@link UserTransaction#getStatus()} * method call * * @param transaction * @return <code>int</code> * @throws IOException */ private static int getStatus(UserTransaction transaction) throws IOException { int status; try { status = transaction.getStatus(); } catch (SystemException ex) { throw new IOException(ex); } return status; } /** * Checks if transaction is active and if it is not vegins transaction * * @param entityTransaction */ private static void beginEntityTransaction( EntityTransaction entityTransaction) { if (ObjectUtils.notTrue(entityTransaction.isActive())) { entityTransaction.begin(); } } private static EntityTransaction getEntityTransaction(EntityManager em) { EntityTransaction entityTransaction; if (em == null) { entityTransaction = null; } else { entityTransaction = em.getTransaction(); beginEntityTransaction(entityTransaction); } return entityTransaction; } private static Collection<TransactionData> getEntityTransactions( Collection<EntityManager> ems) { Collection<TransactionData> entityTransactions; if (CollectionUtils.valid(ems)) { entityTransactions = new ArrayList<TransactionData>(); for (EntityManager em : ems) { EntityTransaction entityTransaction = getEntityTransaction(em); TransactionData transactionData = createTransactionData( entityTransaction, em); entityTransactions.add(transactionData); } } else { entityTransactions = null; } return entityTransactions; } private static void addEntityTransaction(UserTransactionImpl transaction, EntityTransaction entityTransaction, EntityManager em) { if (ObjectUtils.notNull(entityTransaction)) { transaction.addTransaction(entityTransaction); } if (ObjectUtils.notNull(em)) { transaction.addEntityManager(em); } } private static void addEntityTransactions(UserTransactionImpl transaction, Collection<TransactionData> entityTransactions) { if (CollectionUtils.valid(entityTransactions)) { for (TransactionData transactionData : entityTransactions) { addEntityTransaction(transaction, transactionData.entityTransaction, transactionData.em); } } } private static void addEntityManager(UserTransactionImpl transaction, EntityManager em) { if (ObjectUtils.notNull(em)) { transaction.addEntityManager(em); } } private static void addEntityManagers(UserTransactionImpl transaction, Collection<EntityManager> ems) { if (CollectionUtils.valid(ems)) { for (EntityManager em : ems) { addEntityManager(transaction, em); } } } private static void addReqNewTransaction(UserTransactionImpl transaction, EntityTransaction entityTransaction, EntityManager em) { if (ObjectUtils.notNull(entityTransaction)) { transaction.pushReqNew(entityTransaction); } if (ObjectUtils.notNull(em)) { transaction.pushReqNewEm(em); } } private static void addReqNewTransactions(UserTransactionImpl transaction, Collection<TransactionData> entityTransactions) { if (CollectionUtils.valid(entityTransactions)) { for (TransactionData transactionData : entityTransactions) { addReqNewTransaction(transaction, transactionData.entityTransaction, transactionData.em); } } } private static void addCaller(UserTransactionImpl transaction, BeanHandler handler) { Object caller = transaction.getCaller(); if (caller == null) { transaction.setCaller(handler); } } /** * Decides whether create or join {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param type * @param transaction * @param em * @throws IOException */ private static void addTransaction(BeanHandler handler, TransactionAttributeType type, UserTransactionImpl transaction, Collection<EntityManager> ems) throws IOException { Collection<TransactionData> entityTransactions; addCaller(transaction, handler); if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) { addEntityManagers(transaction, ems); } else if (type.equals(TransactionAttributeType.REQUIRED)) { entityTransactions = getEntityTransactions(ems); addEntityTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { entityTransactions = getEntityTransactions(ems); addReqNewTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.MANDATORY)) { int status = getStatus(transaction); if (status == 0) { addEntityManagers(transaction, ems); throw new EJBException(MANDATORY_ERROR); } else { entityTransactions = getEntityTransactions(ems); addEntityTransactions(transaction, entityTransactions); } } else if (type.equals(TransactionAttributeType.NEVER)) { try { int status = getStatus(transaction); if (status > 0) { throw new EJBException(NEVER_ERROR); } } finally { addEntityManagers(transaction, ems); } } else if (type.equals(TransactionAttributeType.SUPPORTS)) { try { throw new NotYetImplementedException(SUPPORTS_ERROR); } finally { addEntityManagers(transaction, ems); } } } /** * Defines which {@link TransactionAttribute} is used on bean {@link Class} * and decides whether create or join {@link UserTransaction} by this * annotation * * @param handler * @param method * @param entityTransaction * @throws IOException */ public static TransactionAttributeType addTransaction(BeanHandler handler, Method method, Collection<EntityManager> ems) throws IOException { TransactionAttributeType type; MetaData metaData = handler.getMetaData(); type = getTransactionType(metaData, method); UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (ObjectUtils.notNull(type)) { addTransaction(handler, type, transaction, ems); } else { addEntityManagers(transaction, ems); } return type; } /** * Commits passed {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void commit(UserTransaction transaction) throws IOException { try { transaction.commit(); } catch (SecurityException ex) { throw new IOException(ex); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (RollbackException ex) { throw new IOException(ex); } catch (HeuristicMixedException ex) { throw new IOException(ex); } catch (HeuristicRollbackException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Commits all {@link TransactionAttributeType.REQUIRES_NEW} transactions * for passed {@link UserTransactionImpl} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void commitReqNew(UserTransactionImpl transaction) throws IOException { try { transaction.commitReqNew(); } catch (SecurityException ex) { throw new IOException(ex); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (RollbackException ex) { throw new IOException(ex); } catch (HeuristicMixedException ex) { throw new IOException(ex); } catch (HeuristicRollbackException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Calls {@link UserTransaction#rollback()} method of passed * {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void rollback(UserTransaction transaction) throws IOException { try { transaction.rollback(); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Decides whether rollback or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void rollbackTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); UserTransaction userTransaction = getTransaction(); UserTransactionImpl transaction = ObjectUtils.cast(userTransaction, UserTransactionImpl.class); try { if (ObjectUtils.notNull(type)) { rollback(transaction); } else { transaction.closeEntityManagers(); } } catch (IOException ex) { transaction.closeEntityManagers(); throw ex; } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param type * @param handler * @throws IOException */ public static void commitTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (type.equals(TransactionAttributeType.REQUIRED)) { boolean check = transaction.checkCaller(handler); if (check) { commit(transaction); } } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { commitReqNew(transaction); } else { transaction.closeEntityManagers(); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void commitTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { commitTransaction(type, handler); } else { closeEntityManagers(); } } /** * Closes cached {@link EntityManager}s after method calll */ public static void closeEntityManagers() { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); transaction.closeEntityManagers(); } /** * Removes {@link UserTransaction} attribute from cache if passed * {@link BeanHandler} is first in EJB injection method chain * * @param handler * @param type */ private static void remove(BeanHandler handler, TransactionAttributeType type) { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); boolean check = transaction.checkCaller(handler); if (check) { TransactionHolder.removeTransaction(); } } /** * Removes {@link UserTransaction} attribute from cache if * {@link TransactionAttributeType} is null or if passed {@link BeanHandler} * is first in EJB injection method chain * * @param handler * @param method */ public static void remove(BeanHandler handler, Method method) { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { remove(handler, type); } else { TransactionHolder.removeTransaction(); } } }
package org.lightmare.jpa.jta; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import javax.ejb.EJBException; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.hibernate.cfg.NotYetImplementedException; import org.lightmare.cache.MetaData; import org.lightmare.cache.TransactionHolder; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Class to manage {@link javax.transaction.UserTransaction} for * {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls * * @author levan * */ public class BeanTransactions { // Error messages for inappropriate use of user transactions private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction"; private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction"; private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented"; /** * Inner class to cache {@link EntityTransaction}s and {@link EntityManager} * s in one {@link Collection} for {@link UserTransaction} implementation * * @author levan * */ protected static class TransactionData { EntityManager em; EntityTransaction entityTransaction; } private static TransactionData createTransactionData( EntityTransaction entityTransaction, EntityManager em) { TransactionData transactionData = new TransactionData(); transactionData.em = em; transactionData.entityTransaction = entityTransaction; return transactionData; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction( EntityTransaction... entityTransactions) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(entityTransactions); TransactionHolder.setTransaction(transaction); } else { // If entityTransactions array is available then adds it to // UserTransaction object UserTransactionFactory.join(transaction, entityTransactions); } return transaction; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction(Collection<EntityManager> ems) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(); TransactionHolder.setTransaction(transaction); } Collection<TransactionData> entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); return transaction; } /** * Gets appropriated {@link TransactionAttributeType} for instant * {@link Method} of {@link javax.ejb.Stateless} bean * * @param metaData * @param method * @return {@link TransactionAttributeType} */ public static TransactionAttributeType getTransactionType( MetaData metaData, Method method) { TransactionAttributeType type; if (method == null) { type = null; } else { TransactionAttributeType attrType = metaData .getTransactionAttrType(); TransactionManagementType manType = metaData .getTransactionManType(); TransactionAttribute attr = method .getAnnotation(TransactionAttribute.class); if (manType.equals(TransactionManagementType.CONTAINER)) { if (attr == null) { type = attrType; } else { type = attr.value(); } } else { type = null; } } return type; } /** * Gets status of passed transaction by {@link UserTransaction#getStatus()} * method call * * @param transaction * @return <code>int</code> * @throws IOException */ private static int getStatus(UserTransaction transaction) throws IOException { int status; try { status = transaction.getStatus(); } catch (SystemException ex) { throw new IOException(ex); } return status; } /** * Checks if transaction is active and if it is not begins transaction * * @param entityTransaction */ private static void beginEntityTransaction( EntityTransaction entityTransaction) { if (ObjectUtils.notTrue(entityTransaction.isActive())) { entityTransaction.begin(); } } /** * Gets {@link EntityTransaction} from passed {@link EntityManager} and * begins it * * @param em * @return {@link EntityTransaction} */ private static EntityTransaction getEntityTransaction(EntityManager em) { EntityTransaction entityTransaction; if (em == null) { entityTransaction = null; } else { entityTransaction = em.getTransaction(); beginEntityTransaction(entityTransaction); } return entityTransaction; } /** * Gets {@link EntityTransaction} for each {@link EntityManager} and begins * it * * @param ems * @return {@link Collection}<EntityTransaction> */ private static Collection<TransactionData> getEntityTransactions( Collection<EntityManager> ems) { Collection<TransactionData> entityTransactions; if (CollectionUtils.valid(ems)) { entityTransactions = new ArrayList<TransactionData>(); for (EntityManager em : ems) { EntityTransaction entityTransaction = getEntityTransaction(em); TransactionData transactionData = createTransactionData( entityTransaction, em); entityTransactions.add(transactionData); } } else { entityTransactions = null; } return entityTransactions; } /** * Decides whether create or join {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param type * @param transaction * @param em * @throws IOException */ private static void addTransaction(BeanHandler handler, TransactionAttributeType type, UserTransaction transaction, Collection<EntityManager> ems) throws IOException { Collection<TransactionData> entityTransactions; TransactionManager.addCaller(transaction, handler); if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) { TransactionManager.addEntityManagers(transaction, ems); } else if (type.equals(TransactionAttributeType.REQUIRED)) { entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { entityTransactions = getEntityTransactions(ems); TransactionManager.addReqNewTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.MANDATORY)) { int status = getStatus(transaction); if (status == 0) { TransactionManager.addEntityManagers(transaction, ems); throw new EJBException(MANDATORY_ERROR); } else { entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); } } else if (type.equals(TransactionAttributeType.NEVER)) { try { int status = getStatus(transaction); if (status > 0) { throw new EJBException(NEVER_ERROR); } } finally { TransactionManager.addEntityManagers(transaction, ems); } } else if (type.equals(TransactionAttributeType.SUPPORTS)) { try { throw new NotYetImplementedException(SUPPORTS_ERROR); } finally { TransactionManager.addEntityManagers(transaction, ems); } } } /** * Defines which {@link TransactionAttribute} is used on bean {@link Class} * and decides whether create or join {@link UserTransaction} by this * annotation * * @param handler * @param method * @param entityTransaction * @throws IOException */ public static TransactionAttributeType addTransaction(BeanHandler handler, Method method, Collection<EntityManager> ems) throws IOException { TransactionAttributeType type; MetaData metaData = handler.getMetaData(); type = getTransactionType(metaData, method); UserTransaction transaction = getTransaction(); if (ObjectUtils.notNull(type)) { addTransaction(handler, type, transaction, ems); } else { TransactionManager.addEntityManagers(transaction, ems); } return type; } /** * Rollbacks passed {@link UserTransaction} by * {@link TransactionAttributeType} distinguishes only * {@link TransactionAttributeType#REQUIRES_NEW} case or uses standard * rollback for all other * * @param type * @param handler * @throws IOException */ private static void rollbackTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransaction transaction = getTransaction(); if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { TransactionManager.rollbackReqNew(transaction); } else { TransactionManager.rollback(transaction); } } /** * Decides which rollback method to call of {@link UserTransaction} * implementation by {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void rollbackTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { rollbackTransaction(type, handler); } else { closeEntityManagers(); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param type * @param handler * @throws IOException */ private static void commitTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransaction transaction = getTransaction(); if (type.equals(TransactionAttributeType.REQUIRED)) { boolean check = TransactionManager .checkCaller(transaction, handler); if (check) { TransactionManager.commit(transaction); } } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { TransactionManager.commitReqNew(transaction); } else { TransactionManager.closeEntityManagers(transaction); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void commitTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { commitTransaction(type, handler); } else { closeEntityManagers(); } } /** * Closes cached {@link EntityManager}s after method call */ public static void closeEntityManagers() { UserTransaction transaction = getTransaction(); TransactionManager.closeEntityManagers(transaction); } /** * Removes {@link UserTransaction} attribute from cache if passed * {@link BeanHandler} is first in EJB injection method chain * * @param handler * @param type */ private static void remove(BeanHandler handler, TransactionAttributeType type) { UserTransaction transaction = getTransaction(); boolean check = TransactionManager.checkCaller(transaction, handler); if (check) { TransactionHolder.removeTransaction(); } } /** * Removes {@link UserTransaction} attribute from cache if * {@link TransactionAttributeType} is null or if passed {@link BeanHandler} * is first in EJB injection method chain * * @param handler * @param method */ public static void remove(BeanHandler handler, Method method) { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { remove(handler, type); } else { TransactionHolder.removeTransaction(); } } }
package org.lima.parser.sstax.util; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public class GenericUtil { public static boolean isPrimitiveType(Class<?> type) { return (getPrimitiveValueOfStringMethod(type) != null)?true:false; } public static Method getPrimitiveValueOfStringMethod(Class<?> type) { Method m = null; try { m = type.getDeclaredMethod("valueOf", String.class); if(!Modifier.isStatic(m.getModifiers())) { m = null; } } catch (Exception e) { m = null; } return m; } public static Class<?>[] getActualTypes(Type genericType) { if (ParameterizedType.class.isAssignableFrom(genericType.getClass())) { ParameterizedType type = (ParameterizedType) genericType; Type[] actualTypeArgs = type.getActualTypeArguments(); Class<?>[] actualTypes = new Class<?>[actualTypeArgs.length]; for(int i=0; i<actualTypeArgs.length; i++) { actualTypes[i] = (Class<?>)actualTypeArgs[i]; } return actualTypes; } return null; } }
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Sun Sep 24 11:00:00 UTC 2017"); System.out.println("Sun Sep 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Sep 22 11:00:00 UTC 2017"); System.out.println("Fri Sep 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Sep 20 11:00:00 UTC 2017"); System.out.println("Wed Sep 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Sep 18 11:00:00 UTC 2017"); System.out.println("Mon Sep 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Sep 16 11:00:00 UTC 2017"); System.out.println("Sat Sep 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Sep 14 11:00:00 UTC 2017"); System.out.println("Thu Sep 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Sep 12 11:00:00 UTC 2017"); System.out.println("Tue Sep 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Sep 10 11:00:00 UTC 2017"); System.out.println("Sun Sep 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Sep 8 11:00:00 UTC 2017"); System.out.println("Fri Sep 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Sep 6 11:00:00 UTC 2017"); System.out.println("Wed Sep 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Sep 4 11:00:00 UTC 2017"); System.out.println("Mon Sep 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Sep 2 11:00:00 UTC 2017"); System.out.println("Sat Sep 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Aug 30 11:00:00 UTC 2017"); System.out.println("Wed Aug 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Aug 28 11:00:00 UTC 2017"); System.out.println("Mon Aug 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Aug 26 11:00:00 UTC 2017"); System.out.println("Sat Aug 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Aug 24 11:00:00 UTC 2017"); System.out.println("Thu Aug 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Aug 22 11:00:00 UTC 2017"); System.out.println("Tue Aug 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Aug 20 11:00:00 UTC 2017"); System.out.println("Sun Aug 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Aug 18 11:00:00 UTC 2017"); System.out.println("Fri Aug 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Aug 16 11:00:00 UTC 2017"); System.out.println("Wed Aug 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Aug 14 11:00:00 UTC 2017"); System.out.println("Mon Aug 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Aug 12 11:00:00 UTC 2017"); System.out.println("Sat Aug 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Aug 10 11:00:00 UTC 2017"); System.out.println("Thu Aug 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Aug 8 11:00:00 UTC 2017"); System.out.println("Tue Aug 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Aug 6 11:00:00 UTC 2017"); System.out.println("Sun Aug 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Aug 4 11:00:00 UTC 2017"); System.out.println("Fri Aug 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Aug 2 11:00:00 UTC 2017"); System.out.println("Wed Aug 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jul 30 11:00:00 UTC 2017"); System.out.println("Sun Jul 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jul 28 11:00:00 UTC 2017"); System.out.println("Fri Jul 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Jul 26 11:00:00 UTC 2017"); System.out.println("Wed Jul 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jul 24 11:00:00 UTC 2017"); System.out.println("Mon Jul 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jul 22 11:00:00 UTC 2017"); System.out.println("Sat Jul 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Jul 20 11:00:00 UTC 2017"); System.out.println("Thu Jul 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Jul 18 11:00:00 UTC 2017"); System.out.println("Tue Jul 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jul 16 11:00:00 UTC 2017"); System.out.println("Sun Jul 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jul 14 11:00:00 UTC 2017"); System.out.println("Fri Jul 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Jul 12 11:00:00 UTC 2017"); System.out.println("Wed Jul 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jul 10 11:00:00 UTC 2017"); System.out.println("Mon Jul 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jul 8 11:00:00 UTC 2017"); System.out.println("Sat Jul 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Jul 6 11:00:00 UTC 2017"); System.out.println("Thu Jul 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Jul 4 11:00:00 UTC 2017"); System.out.println("Tue Jul 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jul 2 11:00:00 UTC 2017"); System.out.println("Sun Jul 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jun 30 11:00:00 UTC 2017"); System.out.println("Fri Jun 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Jun 28 11:00:00 UTC 2017"); System.out.println("Wed Jun 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jun 26 11:00:00 UTC 2017"); System.out.println("Mon Jun 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jun 24 11:00:00 UTC 2017"); System.out.println("Sat Jun 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Jun 22 11:00:00 UTC 2017"); System.out.println("Thu Jun 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Jun 20 11:00:00 UTC 2017"); System.out.println("Tue Jun 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jun 18 11:00:00 UTC 2017"); System.out.println("Sun Jun 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jun 16 11:00:00 UTC 2017"); System.out.println("Fri Jun 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Jun 14 11:00:00 UTC 2017"); System.out.println("Wed Jun 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jun 12 11:00:00 UTC 2017"); System.out.println("Mon Jun 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jun 10 11:00:00 UTC 2017"); System.out.println("Sat Jun 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Jun 8 11:00:00 UTC 2017"); System.out.println("Thu Jun 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Jun 6 11:00:00 UTC 2017"); System.out.println("Tue Jun 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jun 4 11:00:00 UTC 2017"); System.out.println("Sun Jun 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jun 2 11:00:00 UTC 2017"); System.out.println("Fri Jun 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 30 11:00:00 UTC 2017"); System.out.println("Tue May 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun May 28 11:00:00 UTC 2017"); System.out.println("Sun May 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri May 26 11:00:00 UTC 2017"); System.out.println("Fri May 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed May 24 11:00:00 UTC 2017"); System.out.println("Wed May 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon May 22 11:00:00 UTC 2017"); System.out.println("Mon May 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat May 20 11:00:00 UTC 2017"); System.out.println("Sat May 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu May 18 11:00:00 UTC 2017"); System.out.println("Thu May 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 16 11:00:00 UTC 2017"); System.out.println("Tue May 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun May 14 11:00:00 UTC 2017"); System.out.println("Sun May 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri May 12 11:00:00 UTC 2017"); System.out.println("Fri May 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed May 10 11:00:00 UTC 2017"); System.out.println("Wed May 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon May 8 11:00:00 UTC 2017"); System.out.println("Mon May 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat May 6 11:00:00 UTC 2017"); System.out.println("Sat May 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu May 4 11:00:00 UTC 2017"); System.out.println("Thu May 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 2 11:00:00 UTC 2017"); System.out.println("Tue May 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Tue May 2 11:00:00 UTC 2017"); System.out.println("Tue May 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
package org.myrobotlab.service.meta; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.logging.LoggerFactory; import org.slf4j.Logger; public class OpenCVMeta { public final static Logger log = LoggerFactory.getLogger(OpenCVMeta.class); /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType("org.myrobotlab.service.OpenCV"); Platform platform = Platform.getLocalInstance(); meta.addDescription("OpenCV (computer vision) service wrapping many of the functions and filters of OpenCV"); meta.addCategory("video", "vision", "sensors"); // meta.addPeer("streamer", "VideoStreamer", "video streaming service meta.sharePeer("streamer", "streamer", "VideoStreamer", "Shared Video Streamer"); String javaCvVersion = "1.5.3"; meta.addDependency("org.bytedeco", "javacv", javaCvVersion); meta.addDependency("org.bytedeco", "javacv-platform", javaCvVersion); // FIXME - finish with cmdLine flag -gpu vs cudaEnabled for DL4J ? boolean gpu = false; if (gpu) { // TODO: integrate in the following dependencies for GPU support in // OpenCV. // add additional metadata dependencies. // <dependency> // <groupId>org.bytedeco.javacpp-presets</groupId> // <artifactId>opencv</artifactId> // <version>3.4.1-1.4.1</version> // <classifier>linux-x86_64-gpu</classifier> // </dependency> // <dependency> // <groupId>org.bytedeco.javacpp-presets</groupId> // <artifactId>opencv</artifactId> // <version>3.4.1-1.4.1</version> // <classifier>macosx-x86_64-gpu</classifier> // </dependency> // <dependency> // <groupId>org.bytedeco.javacpp-presets</groupId> // <artifactId>opencv</artifactId> // <version>3.4.1-1.4.1</version> // <classifier>windows-x86_64-gpu</classifier> // </dependency> } // sarxos webcam meta.addDependency("com.github.sarxos", "webcam-capture", "0.3.10"); // FaceRecognizer no worky if missing it meta.addDependency("org.apache.commons", "commons-lang3", "3.3.2"); // for the mjpeg streamer frame grabber meta.addDependency("net.sf.jipcam", "jipcam", "0.9.1"); meta.exclude("javax.servlet", "servlet-api"); // jipcam use commons-lang-1.0 it break marySpeech meta.exclude("commons-lang", "commons-lang"); meta.addDependency("commons-lang", "commons-lang", "2.6"); // the haar / hog / lp classifier xml files for opencv from the MRL repo meta.addDependency("opencv", "opencv_classifiers", "0.0.2", "zip"); // the DNN Face Detection module meta.addDependency("opencv", "opencv_facedetectdnn", "1.0.1", "zip"); // text detection using EAST classifier meta.addDependency("opencv", "opencv_east_text_detection", "0.0.1", "zip"); // youtube downloader meta.addDependency("com.github.axet", "vget", "1.1.34"); // yolo models meta.addDependency("yolo", "yolov2", "0.0.2", "zip"); return meta; } }
package org.newdawn.slick.command; /** * A simple named command * * @author kevin */ public class BasicCommand implements Command { /** The name of the command */ private String name; /** * Create a new basic command * * @param name The name to give this command */ public BasicCommand(String name) { this.name = name; } /** * Get the name given for this basic command * * @return The name given for this basic command */ public String getName() { return name; } @Override public String toString() { return "[Command="+name+"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof BasicCommand)) { return false; } BasicCommand other = (BasicCommand) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } }
package org.nnsoft.shs.http; import java.io.IOException; import java.io.OutputStream; /** * Response body are generated via {@link ResponseBodyWriter} implementations. */ public interface ResponseBodyWriter { /** * Returns the body content length if known, -1 otherwise. * * @return the body content length if known, -1 otherwise. */ long getContentLength(); /** * Generates the body response into the target output stream. * * @param output the target output where body has to be generated * @throws IOException is any error occurs during the body generation */ void write( OutputStream output ) throws IOException; }
package org.ow2.petals.activitibpmn; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DEFAULT_ENGINE_ENABLE_JOB_EXECUTOR; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DEFAULT_MONIT_TRACE_DELAY; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DEFAULT_SCHEDULED_LOGGER_CORE_SIZE; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.ENGINE_ENABLE_JOB_EXECUTOR; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.MONIT_TRACE_DELAY; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.SCHEDULED_LOGGER_CORE_SIZE; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.Activiti.PETALS_SENDER_COMP_NAME; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DATABASE_SCHEMA_UPDATE; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DATABASE_TYPE; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_DRIVER; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_MAX_ACTIVE_CONNECTIONS; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_MAX_CHECKOUT_TIME; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_MAX_IDLE_CONNECTIONS; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_MAX_WAIT_TIME; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_URL_DATABASE_FILENAME; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_DRIVER; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_MAX_ACTIVE_CONNECTIONS; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_MAX_CHECKOUT_TIME; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_MAX_IDLE_CONNECTIONS; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_MAX_WAIT_TIME; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_PASSWORD; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_URL; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_USERNAME; import static org.ow2.petals.activitibpmn.ActivitiSEConstants.IntegrationOperation.ITG_OP_GETTASKS; import java.io.File; import java.net.MalformedURLException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.jbi.JBIException; import javax.xml.namespace.QName; import org.activiti.engine.ActivitiException; import org.activiti.engine.ProcessEngine; import org.activiti.engine.ProcessEngineConfiguration; import org.activiti.engine.delegate.event.ActivitiEventType; import org.activiti.engine.impl.asyncexecutor.AsyncExecutor; import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.apache.cxf.Bus; import org.apache.cxf.BusFactory; import org.apache.cxf.transport.ConduitInitiatorManager; import org.ow2.easywsdl.wsdl.api.Endpoint; import org.ow2.easywsdl.wsdl.api.WSDLException; import org.ow2.petals.activitibpmn.event.ProcessCanceledEventListener; import org.ow2.petals.activitibpmn.event.ProcessCompletedEventListener; import org.ow2.petals.activitibpmn.incoming.ActivitiService; import org.ow2.petals.activitibpmn.incoming.integration.GetTasksOperation; import org.ow2.petals.activitibpmn.incoming.integration.exception.OperationInitializationException; import org.ow2.petals.activitibpmn.outgoing.PetalsSender; import org.ow2.petals.activitibpmn.outgoing.cxf.transport.PetalsCxfTransportFactory; import org.ow2.petals.component.framework.listener.AbstractListener; import org.ow2.petals.component.framework.se.AbstractServiceEngine; import org.ow2.petals.component.framework.su.AbstractServiceUnitManager; import org.ow2.petals.component.framework.util.EndpointOperationKey; import org.ow2.petals.component.framework.util.WSDLUtilImpl; /** * The component class of the Activiti BPMN Service Engine. * @author Bertrand Escudie - Linagora */ public class ActivitiSE extends AbstractServiceEngine { /** * The Activiti BPMN Engine. */ private ProcessEngine activitiEngine; /** * A map used to get the Activiti Operation associated with (end-point Name + Operation) */ private final Map<EndpointOperationKey, ActivitiService> activitiServices = new ConcurrentHashMap<EndpointOperationKey, ActivitiService>(); /** * An executor service to log MONIT trace about end of process instances */ private ScheduledExecutorService scheduledLogger = null; /** * Delay to wait before to log some MONIT traces */ // TODO: monitTraceDelay should be hot-changed private int monitTraceDelay = DEFAULT_MONIT_TRACE_DELAY; /** * Core size of the thread pool in charge of logging delayed MONIT traces */ // TODO: scheduledLoggerCoreSize should be hot-changed private int scheduledLoggerCoreSize = DEFAULT_SCHEDULED_LOGGER_CORE_SIZE; /** * The Activiti Async Executor service */ private AsyncExecutor activitiAsyncExecutor = null; /** * Activation flag of the Activiti job executor */ private boolean enableActivitiJobExecutor = DEFAULT_ENGINE_ENABLE_JOB_EXECUTOR; /** * @return the Activiti Engine */ public ProcessEngine getProcessEngine() { return this.activitiEngine; } /** * @param eptAndOperation * the end-point Name and operation Name * @param activitiservice * the Activiti service * @return the map with the inserted elements */ public void registerActivitiService(final EndpointOperationKey eptAndOperation, final ActivitiService activitiservice) { this.activitiServices.put(eptAndOperation, activitiservice); } /** * @param eptName * the end-point name */ public void removeActivitiService(final String eptName) { final Iterator<Entry<EndpointOperationKey, ActivitiService>> itEptOperationToActivitiOperation = this.activitiServices .entrySet().iterator(); while (itEptOperationToActivitiOperation.hasNext()) { final Entry<EndpointOperationKey, ActivitiService> entry = itEptOperationToActivitiOperation.next(); if (entry.getKey().getEndpointName().equals(eptName)) { itEptOperationToActivitiOperation.remove(); } } } /** * @param logLevel */ public void logEptOperationToActivitiOperation(final Logger logger, final Level logLevel) { if (logger.isLoggable(logLevel)) { for (final Map.Entry<EndpointOperationKey, ActivitiService> entry : this.activitiServices.entrySet()) { final EndpointOperationKey key = entry.getKey(); logger.log(logLevel, "*** Endpoint Operation "); logger.log(logLevel, key.toString()); logger.log(logLevel, " entry.getValue().log(logger, logLevel); logger.log(logLevel, "******************* "); } } } /** * @param eptAndOperation * the end-point Name and operation Name * @return the Activiti Service associated with this end-point name and operation Name */ public ActivitiService getActivitiServices(final EndpointOperationKey eptAndOperation) { return this.activitiServices.get(eptAndOperation); } @Override public void doInit() throws JBIException { this.getLogger().fine("Start ActivitiSE.doInit()"); try { // JDBC Driver final String jdbcDriverConfigured = this.getComponentExtensions().get(JDBC_DRIVER); final String jdbcDriver; if (jdbcDriverConfigured == null || jdbcDriverConfigured.trim().isEmpty()) { this.getLogger().info("No JDBC Driver configured for database. Default value used."); jdbcDriver = DEFAULT_JDBC_DRIVER; } else { jdbcDriver = jdbcDriverConfigured; } // JDBC URL final String jdbcUrlConfigured = this.getComponentExtensions().get(JDBC_URL); final String jdbcUrl; if (jdbcUrlConfigured == null || jdbcUrlConfigured.trim().isEmpty()) { // $PETALS_HOME/data/repository/components/<se-bpmn>/h2-activiti.db this.getLogger().info("No JDBC URL configured for database. Default value used."); final File databaseFile = new File(this.getContext().getWorkspaceRoot(), DEFAULT_JDBC_URL_DATABASE_FILENAME); try { jdbcUrl = String.format("jdbc:h2:%s", databaseFile.toURI().toURL().toExternalForm()); } catch (final MalformedURLException e) { // This exception should not occur. It's a bug throw new JBIException("The defaul JDBC URL is invalid !!", e); } } else { jdbcUrl = jdbcUrlConfigured; } final String jdbcUsername = this.getComponentExtensions().get(JDBC_USERNAME); final String jdbcPassword = this.getComponentExtensions().get(JDBC_PASSWORD); final String jdbcMaxActiveConnectionsConfigured = this.getComponentExtensions().get( JDBC_MAX_ACTIVE_CONNECTIONS); int jdbcMaxActiveConnections; if (jdbcMaxActiveConnectionsConfigured == null || jdbcMaxActiveConnectionsConfigured.trim().isEmpty()) { this.getLogger().info("No JDBC Max Active Connections configured for database. Default value used."); jdbcMaxActiveConnections = DEFAULT_JDBC_MAX_ACTIVE_CONNECTIONS; } else { try { jdbcMaxActiveConnections = Integer.parseInt(jdbcMaxActiveConnectionsConfigured); } catch (final NumberFormatException e) { this.getLogger().warning( "Invalid value for the number of JDBC Max Active Connections. Default value used."); jdbcMaxActiveConnections = DEFAULT_JDBC_MAX_ACTIVE_CONNECTIONS; } } final String jdbcMaxIdleConnectionsConfigured = this.getComponentExtensions() .get(JDBC_MAX_IDLE_CONNECTIONS); int jdbcMaxIdleConnections; if (jdbcMaxIdleConnectionsConfigured == null || jdbcMaxIdleConnectionsConfigured.trim().isEmpty()) { this.getLogger().info("No JDBC Max Idle Connections configured for database. Default value used."); jdbcMaxIdleConnections = DEFAULT_JDBC_MAX_IDLE_CONNECTIONS; } else { try { jdbcMaxIdleConnections = Integer.parseInt(jdbcMaxIdleConnectionsConfigured); } catch (final NumberFormatException e) { this.getLogger().warning( "Invalid value for the number of JDBC Max Idle Connections. Default value used."); jdbcMaxIdleConnections = DEFAULT_JDBC_MAX_IDLE_CONNECTIONS; } } final String jdbcMaxCheckoutTimeConfigured = this.getComponentExtensions().get(JDBC_MAX_CHECKOUT_TIME); int jdbcMaxCheckoutTime; if (jdbcMaxCheckoutTimeConfigured == null || jdbcMaxCheckoutTimeConfigured.trim().isEmpty()) { this.getLogger().info("No JDBC Max Checkout Time configured for database. Default value used."); jdbcMaxCheckoutTime = DEFAULT_JDBC_MAX_CHECKOUT_TIME; } else { try { jdbcMaxCheckoutTime = Integer.parseInt(jdbcMaxCheckoutTimeConfigured); } catch (final NumberFormatException e) { this.getLogger().warning( "Invalid value for the number of JDBC Max Checkout Time. Default value used."); jdbcMaxCheckoutTime = DEFAULT_JDBC_MAX_CHECKOUT_TIME; } } final String jdbcMaxWaitTimeConfigured = this.getComponentExtensions().get(JDBC_MAX_WAIT_TIME); int jdbcMaxWaitTime; if (jdbcMaxWaitTimeConfigured == null || jdbcMaxWaitTimeConfigured.trim().isEmpty()) { this.getLogger().info("No JDBC Max Wait Time configured for database. Default value used."); jdbcMaxWaitTime = DEFAULT_JDBC_MAX_WAIT_TIME; } else { try { jdbcMaxWaitTime = Integer.parseInt(jdbcMaxWaitTimeConfigured); } catch (final NumberFormatException e) { this.getLogger().warning("Invalid value for the number of JDBC Max Wait Time. Default value used."); jdbcMaxWaitTime = DEFAULT_JDBC_MAX_WAIT_TIME; } } /* DATABASE_TYPE Possible values: {h2, mysql, oracle, postgres, mssql, db2}. */ final String databaseType = this.getComponentExtensions().get(DATABASE_TYPE); /* DATABASE_SCHEMA_UPDATE Possible values: {false, true, create-drop } */ final String databaseSchemaUpdate = this.getComponentExtensions().get(DATABASE_SCHEMA_UPDATE); this.getLogger().config("DB configuration:"); this.getLogger().config(" - " + JDBC_DRIVER + " = " + jdbcDriver); this.getLogger().config(" - " + JDBC_URL + " = " + jdbcUrl); this.getLogger().config(" - " + JDBC_USERNAME + " = " + jdbcUsername); this.getLogger().config(" - " + JDBC_PASSWORD + " = " + jdbcPassword); this.getLogger().config(" - " + JDBC_MAX_ACTIVE_CONNECTIONS + " = " + jdbcMaxActiveConnections); this.getLogger().config(" - " + JDBC_MAX_IDLE_CONNECTIONS + " = " + jdbcMaxIdleConnections); this.getLogger().config(" - " + JDBC_MAX_CHECKOUT_TIME + " = " + jdbcMaxCheckoutTime); this.getLogger().config(" - " + JDBC_MAX_WAIT_TIME + " = " + jdbcMaxWaitTime); this.getLogger().config(" - " + DATABASE_TYPE + " = " + databaseType); this.getLogger().config(" - " + DATABASE_SCHEMA_UPDATE + " = " + databaseSchemaUpdate); // Caution: // - only the value "false", ignoring case and spaces will disable the job executor, // - only the value "true", ignoring case and spaces will enable the job executor, // - otherwise, the default value is used. final String enableActivitiJobExecutorConfigured = this.getComponentExtensions().get( ENGINE_ENABLE_JOB_EXECUTOR); if (enableActivitiJobExecutorConfigured == null || enableActivitiJobExecutorConfigured.trim().isEmpty()) { this.getLogger().info( "The activation of the Activiti job executor is not configured. Default value used."); this.enableActivitiJobExecutor = DEFAULT_ENGINE_ENABLE_JOB_EXECUTOR; } else { this.enableActivitiJobExecutor = enableActivitiJobExecutorConfigured.trim().equalsIgnoreCase("false") ? false : (enableActivitiJobExecutorConfigured.trim().equalsIgnoreCase("true") ? true : DEFAULT_ENGINE_ENABLE_JOB_EXECUTOR); } this.getLogger().config("Activiti engine configuration:"); this.getLogger().config(" - " + ENGINE_ENABLE_JOB_EXECUTOR + " = " + this.enableActivitiJobExecutor); final String monitTraceDelayConfigured = this.getComponentExtensions().get(MONIT_TRACE_DELAY); if (monitTraceDelayConfigured == null || monitTraceDelayConfigured.trim().isEmpty()) { this.getLogger().info("No MONIT trace delay configured. Default value used."); this.monitTraceDelay = DEFAULT_MONIT_TRACE_DELAY; } else { try { this.monitTraceDelay = Integer.parseInt(monitTraceDelayConfigured); } catch (final NumberFormatException e) { this.getLogger().warning("Invalid value for the MONIT trace delay. Default value used."); this.monitTraceDelay = DEFAULT_MONIT_TRACE_DELAY; } } final String scheduledLoggerCoreSizeConfigured = this.getComponentExtensions().get( SCHEDULED_LOGGER_CORE_SIZE); if (scheduledLoggerCoreSizeConfigured == null || scheduledLoggerCoreSizeConfigured.trim().isEmpty()) { this.getLogger() .info("No core size of the thread pool in charge of logging MONIT traces is configured. Default value used."); this.scheduledLoggerCoreSize = DEFAULT_SCHEDULED_LOGGER_CORE_SIZE; } else { try { this.scheduledLoggerCoreSize = Integer.parseInt(scheduledLoggerCoreSizeConfigured); } catch (final NumberFormatException e) { this.getLogger() .warning( "Invalid value for the core size of the thread pool in charge of logging MONIT traces. Default value used."); this.scheduledLoggerCoreSize = DEFAULT_SCHEDULED_LOGGER_CORE_SIZE; } } this.getLogger().config("Other configuration parameters:"); this.getLogger().config(" - " + MONIT_TRACE_DELAY + " = " + this.monitTraceDelay); this.getLogger().config(" - " + SCHEDULED_LOGGER_CORE_SIZE + " = " + this.scheduledLoggerCoreSize); /* TODO Test Activiti database connection configuration */ /* TODO Test the Database Schema Version * What about databaseSchemaUpdate values "true" and "create-drop" */ /* TODO Set the non set value with default value */ /* Create an Activiti ProcessEngine with database configuration */ final ProcessEngineConfiguration pec = ProcessEngineConfiguration .createStandaloneProcessEngineConfiguration(); pec.setJdbcDriver(jdbcDriver); pec.setJdbcUrl(jdbcUrl); pec.setJdbcUsername(jdbcUsername).setJdbcPassword(jdbcPassword); pec.setJdbcMaxActiveConnections(jdbcMaxActiveConnections); pec.setJdbcMaxIdleConnections(jdbcMaxIdleConnections); pec.setJdbcMaxCheckoutTime(jdbcMaxCheckoutTime); pec.setJdbcMaxWaitTime(jdbcMaxWaitTime); pec.setDatabaseSchemaUpdate(databaseSchemaUpdate); pec.setJobExecutorActivate(false); // We register the Petals transport into Apache CXF this.registerCxfPetalsTransport(); // As recommended by Activiti team, we prefer the Async Job Executor pec.setJobExecutorActivate(false); // The Async job is enabled ... pec.setAsyncExecutorEnabled(this.enableActivitiJobExecutor); // ... but must be started when starting the SE pec.setAsyncExecutorActivate(false); this.activitiEngine = pec.buildProcessEngine(); this.activitiAsyncExecutor = this.enableActivitiJobExecutor ? pec.getAsyncExecutor() : null; // Caution: Beans of the configuration are initialized when building the process engine if (pec instanceof ProcessEngineConfigurationImpl) { // We add to the BPMN engine the bean in charge of sending Petals message exchange final AbstractListener petalsSender = new PetalsSender(); petalsSender.init(this); ((ProcessEngineConfigurationImpl) pec).getBeans().put(PETALS_SENDER_COMP_NAME, petalsSender); } else { this.getLogger().warning("The implementation of the process engine configuration is not the expected one ! No Petals services can be invoked !"); } // Register integration operation final List<Endpoint> integrationEndpoints = WSDLUtilImpl.getEndpointList(this.getNativeWsdl() .getDescription()); if (integrationEndpoints.size() > 1) { throw new JBIException("Unexpected endpoint number supporting integration services"); } else if (integrationEndpoints.size() == 1) { try { final Endpoint endpoint = integrationEndpoints.get(0); final String integrationEndpointName = endpoint.getName(); final QName integrationInterfaceName = endpoint.getService().getInterface().getQName(); this.activitiServices .put(new EndpointOperationKey(integrationEndpointName, integrationInterfaceName, ITG_OP_GETTASKS), new GetTasksOperation(this.activitiEngine.getTaskService(), this.activitiEngine .getRepositoryService(), this.getLogger())); } catch (final OperationInitializationException | WSDLException e) { this.getLogger().log(Level.WARNING, "Integration operations are not completly initialized", e); } } else { this.getLogger().warning("No endpoint exists to execute integration operations"); } } catch( final ActivitiException e ) { throw new JBIException( "An error occurred while creating the Activiti BPMN Engine.", e ); } finally { this.getLogger().fine("End ActivitiSE.doInit()"); } } @Override public void doStart() throws JBIException { this.getLogger().fine("Start ActivitiSE.doStart()"); this.scheduledLogger = Executors.newScheduledThreadPool(this.scheduledLoggerCoreSize, new ScheduledLoggerThreadFactory(ActivitiSE.this.getContext().getComponentName())); this.activitiEngine.getRuntimeService().addEventListener( new ProcessCompletedEventListener(this.scheduledLogger, this.monitTraceDelay, this.activitiEngine.getHistoryService(), this.getLogger()), ActivitiEventType.PROCESS_COMPLETED); this.activitiEngine.getRuntimeService().addEventListener( new ProcessCanceledEventListener(this.scheduledLogger, this.monitTraceDelay, this.activitiEngine.getHistoryService(), this.getLogger()), ActivitiEventType.PROCESS_CANCELLED); try { // Startup Activiti engine against running states of the SE: // - Activiti Engine must be started when the SE is in state 'STOPPED' to be able to deploy process // definitions // - In state 'STOPPED', the SE will not process incoming requests, so no process instance creation and no // user task completion will occur // - To avoid the executions of activities trigerred by timer or other events, the Activiti job executor // must be stopped when the SE is in state 'STOPPED' if (this.enableActivitiJobExecutor) { if (this.activitiAsyncExecutor != null) { if (this.activitiAsyncExecutor.isActive()) { this.getLogger().warning("Activiti Job Executor already started !!"); } else { this.activitiAsyncExecutor.start(); } } else { this.getLogger().warning("No Activiti Job Executor exists !!"); } } else { this.getLogger().info("Activiti Job Executor not started because it is not activated."); } // TODO: Add JMX operation to start/stop the Activiti job executor when the component is started // TODO: Add JMX operation to disable/enable the Activiti job executor when the component is running } catch( final ActivitiException e ) { throw new JBIException( "An error occurred while starting the Activiti BPMN Engine.", e ); } finally { this.getLogger().fine("End ActivitiSE.doStart()"); } } @Override public void doStop() throws JBIException { this.getLogger().fine("Start ActivitiSE.doStop()"); try { // Stop the Activiti Job Executor */ if (this.enableActivitiJobExecutor) { if (this.activitiAsyncExecutor != null) { if (this.activitiAsyncExecutor.isActive()) { this.activitiAsyncExecutor.shutdown(); } else { this.getLogger().warning("Activiti Job Executor not started !!"); } } else { this.getLogger().warning("No Activiti Job Executor exists !!"); } } else { this.getLogger().info("Activiti Job Executor not stopped because it is not activated."); } } catch (final ActivitiException e) { throw new JBIException("An error occurred while stopping the Activiti BPMN Engine.", e); } finally { this.getLogger().fine("End ActivitiSE.doStop()"); } try { this.scheduledLogger.shutdown(); // TODO: The timeout should be configurable this.scheduledLogger.awaitTermination(5000, TimeUnit.MILLISECONDS); } catch (final InterruptedException e) { this.getLogger().log(Level.WARNING, "The termination of the scheduled logger was interrupted", e); } } @Override public void doShutdown() throws JBIException { this.getLogger().fine("Start ActivitiSE.doShutdown()"); try { this.activitiEngine.close(); } catch( final ActivitiException e ) { throw new JBIException( "An error occurred while shutdowning the Activiti BPMN Engine.", e ); } finally { this.getLogger().fine("End ActivitiSE.doShutdown()"); } } @Override protected AbstractServiceUnitManager createServiceUnitManager() { return new ActivitiSuManager(this); } private void registerCxfPetalsTransport() { final Bus bus = BusFactory.getThreadDefaultBus(); final PetalsCxfTransportFactory cxfPetalsTransport = new PetalsCxfTransportFactory(); final ConduitInitiatorManager extension = bus.getExtension(ConduitInitiatorManager.class); extension.registerConduitInitiator(PetalsCxfTransportFactory.TRANSPORT_ID, cxfPetalsTransport); // TODO: Set a timeout at CXF client level (it should be the same than the tiemout at NMR level) // TODO: Add unit tests about timeout } }
package org.realityforge.dbdiff; import java.io.Writer; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public final class DatabaseDumper { // This lists the allowable postgres table types and should be updated for sql server private static final Collection<String> ALLOWABLE_TABLE_TYPES = Arrays.asList( "INDEX", "SEQUENCE", "TABLE", "VIEW", "TYPE" ); private static final String TABLE_TYPE = "table_type"; private static final String TABLE_NAME = "table_name"; private static final List<String> ALLOWABLE_TABLE_ATTRIBUTES = Arrays.asList( TABLE_TYPE, TABLE_NAME ); private static final String COLUMN_NAME = "column_name"; private static final List<String> ALLOWABLE_COLUMN_ATTRIBUTES = Arrays.asList( COLUMN_NAME, "COLUMN_DEF", "ORDINAL_POSITION", "SOURCE_DATA_TYPE", "SQL_DATA_TYPE", "NUM_PREC_RADIX", "COLUMN_SIZE", "TYPE_NAME", "IS_AUTOINCREMENT", "DECIMAL_DIGITS", "DATA_TYPE", "BUFFER_LENGTH", "CHAR_OCTET_LENGTH", "IS_NULLABLE", "NULLABLE", "SQL_DATETIME_SUB", "REMARKS", "SCOPE_CATLOG", "SCOPE_SCHEMA", "SCOPE_TABLE" ); private static final String FK_NAME = "fk_name"; private static final List<String> ALLOWABLE_FOREIGN_KEY_ATTRIBUTES = Arrays.asList( FK_NAME, "PKTABLE_NAME", "PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM", "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ", "UPDATE_RULE", "DELETE_RULE", "PK_NAME", "DEFERRABILITY" ); private static final String PK_NAME = "pk_name"; private static final List<String> ALLOWABLE_PRIMARY_KEY_ATTRIBUTES = Arrays.asList( PK_NAME, "COLUMN_NAME", "KEY_SEQ" ); private static final List<String> ALLOWABLE_TABLE_PRIV_ATTRIBUTES = Arrays.asList( "GRANTOR", "GRANTEE", "PRIVILEGE", "IS_GRANTABLE" ); private static final List<String> ALLOWABLE_COLUMN_PRIV_ATTRIBUTES = Arrays.asList( "GRANTOR", "GRANTEE", "PRIVILEGE", "IS_GRANTABLE" ); private final Connection _connection; private final List<String> _schemas; public DatabaseDumper( final Connection connection, final String[] schemas ) { _connection = connection; _schemas = Arrays.asList( schemas ); } public void dump( final Writer w ) throws Exception { final DatabaseMetaData metaData = _connection.getMetaData(); final List<String> schemaSet = getSchema( metaData ); for ( final String schema : _schemas ) { if ( schemaSet.contains( schema ) ) { emitSchema( w, metaData, schema ); } else { w.write( "Missing Schema: " + schema + "\n" ); } } } private void emitSchema( final Writer w, final DatabaseMetaData metaData, final String schema ) throws Exception { w.write( "Schema: " + schema + "\n" ); for ( final LinkedHashMap table : getTablesForSchema( metaData, schema ) ) { final String tableName = (String) table.get( TABLE_NAME ); final String tableType = (String) table.get( TABLE_TYPE ); w.write( "\t" + tableType + ": " + tableName + "\n" ); for ( final LinkedHashMap<String, Object> priv : getTablePrivileges( metaData, schema, tableName ) ) { w.write( "\t\tPRIV : " + compact( priv ) + "\n" ); } for ( final LinkedHashMap<String, Object> pk : getPrimaryKeys( metaData, schema, tableName ) ) { final String pkName = (String) pk.get( PK_NAME ); pk.remove( PK_NAME ); w.write( "\t\tPK : " + pkName + ": " + compact( pk ) + "\n" ); } for ( final LinkedHashMap<String, Object> column : getColumns( metaData, schema, tableName ) ) { final String columnName = (String) column.get( COLUMN_NAME ); column.remove( COLUMN_NAME ); w.write( "\t\tCOLUMN : " + columnName + ": " + compact( column ) + "\n" ); final List<LinkedHashMap<String, Object>> privileges = getColumnPrivileges( metaData, schema, tableName, columnName ); for ( final LinkedHashMap<String, Object> priv : privileges ) { w.write( "\t\t\tPRIV : " + compact( priv ) + "\n" ); } } for ( final LinkedHashMap<String, Object> fk : getImportedKeys( metaData, schema, tableName ) ) { final String fkName = (String) fk.get( FK_NAME ); fk.remove( FK_NAME ); w.write( "\t\tFK : " + fkName + ": " + compact( fk ) + "\n" ); } } //metaData.getProcedures( ) //metaData.getProcedureColumns( ) //metaData.getAttributes( ) //metaData.getColumnPrivileges //metaData.getIndexInfo } private LinkedHashMap compact( final LinkedHashMap<String, Object> column ) { final ArrayList<String> keys = new ArrayList<String>(); keys.addAll( column.keySet() ); for ( final String key : keys ) { if ( null == column.get( key ) ) { column.remove( key ); } } return column; } private List<LinkedHashMap<String, Object>> getTablePrivileges( final DatabaseMetaData metaData, final String schema, final String tablename ) throws Exception { final ResultSet columnResultSet = metaData.getTablePrivileges( null, schema, tablename ); return extractFromRow( columnResultSet, ALLOWABLE_TABLE_PRIV_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getColumnPrivileges( final DatabaseMetaData metaData, final String schema, final String tableName, final String columnName ) throws Exception { final ResultSet columnResultSet = metaData.getColumnPrivileges( null, schema, tableName, columnName ); return extractFromRow( columnResultSet, ALLOWABLE_COLUMN_PRIV_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getPrimaryKeys( final DatabaseMetaData metaData, final String schema, final String tablename ) throws Exception { final ResultSet columnResultSet = metaData.getPrimaryKeys( null, schema, tablename ); return extractFromRow( columnResultSet, ALLOWABLE_PRIMARY_KEY_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getImportedKeys( final DatabaseMetaData metaData, final String schema, final String tablename ) throws Exception { final ResultSet columnResultSet = metaData.getImportedKeys( null, schema, tablename ); return extractFromRow( columnResultSet, ALLOWABLE_FOREIGN_KEY_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getColumns( final DatabaseMetaData metaData, final String schema, final String tablename ) throws Exception { final ResultSet columnResultSet = metaData.getColumns( null, schema, tablename, null ); return extractFromRow( columnResultSet, ALLOWABLE_COLUMN_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getTablesForSchema( final DatabaseMetaData metaData, final String schema ) throws Exception { final List<String> tableTypes = getTableTypes( metaData ); final ResultSet tablesResultSet = metaData.getTables( null, schema, null, tableTypes.toArray( new String[ tableTypes.size() ] ) ); final List<LinkedHashMap<String, Object>> linkedHashMaps = extractFromRow( tablesResultSet, ALLOWABLE_TABLE_ATTRIBUTES ); Collections.sort( linkedHashMaps, new Comparator<LinkedHashMap<String, Object>>() { @Override public int compare( final LinkedHashMap<String, Object> lhs, final LinkedHashMap<String, Object> rhs ) { final String left = (String) lhs.get( TABLE_TYPE ) + lhs.get( TABLE_NAME ); final String right = (String) rhs.get( TABLE_TYPE ) + rhs.get( TABLE_NAME ); return left.compareTo( right ); } } ); return linkedHashMaps; } private List<String> getSchema( final DatabaseMetaData metaData ) throws Exception { return extractFromRow( metaData.getSchemas(), "table_schem" ); } private List<String> getTableTypes( final DatabaseMetaData metaData ) throws Exception { final List<String> supportedTypes = extractFromRow( metaData.getTableTypes(), TABLE_TYPE ); final Iterator<String> iterator = supportedTypes.iterator(); while ( iterator.hasNext() ) { final String type = iterator.next(); if ( !ALLOWABLE_TABLE_TYPES.contains( type ) ) { iterator.remove(); } } return supportedTypes; } private <T> List<T> extractFromRow( final ResultSet resultSet, final String key ) throws Exception { return map( resultSet, new MapHandler<T>() { @Override public T handle( final Map<String, Object> row ) { return extract( row, key ); } } ); } private List<LinkedHashMap<String, Object>> extractFromRow( final ResultSet resultSet, final List<String> keys ) throws Exception { return map( resultSet, new MapHandler<LinkedHashMap<String, Object>>() { @SuppressWarnings( "unchecked" ) @Override public LinkedHashMap<String, Object> handle( final Map<String, Object> row ) { final LinkedHashMap tuple = new LinkedHashMap(); for ( final String key : keys ) { tuple.put( key.toLowerCase(), extract( row, key ) ); } return tuple; } } ); } @SuppressWarnings( "unchecked" ) private <T> T extract( final Map<String, Object> row, final String key ) { if ( row.containsKey( key.toLowerCase() ) ) { return (T) row.get( key.toLowerCase() ); } else if ( row.containsKey( key.toUpperCase() ) ) { return (T) row.get( key.toUpperCase() ); } else { throw new IllegalStateException( "Unexpected null value for key " + key + " when accessing " + row ); } } interface RowHandler { void handle( Map<String, Object> row ); } private void each( final ResultSet resultSet, final RowHandler handler ) throws Exception { for ( final Map<String, Object> row : toList( resultSet ) ) { handler.handle( row ); } } interface MapHandler<T> { T handle( Map<String, Object> row ); } private <T> List<T> map( final ResultSet resultSet, final MapHandler<T> handler ) throws Exception { final ArrayList<T> results = new ArrayList<T>(); each( resultSet, new RowHandler() { @Override public void handle( final Map<String, Object> row ) { results.add( handler.handle( row ) ); } } ); return results; } private List<Map<String, Object>> toList( final ResultSet resultSet ) throws SQLException { final ResultSetMetaData md = resultSet.getMetaData(); final int columns = md.getColumnCount(); final ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); while ( resultSet.next() ) { final HashMap<String, Object> row = new HashMap<String, Object>(); for ( int i = 1; i <= columns; ++i ) { row.put( md.getColumnName( i ), resultSet.getObject( i ) ); } list.add( row ); } return list; } }
package org.spongepowered.api.text.title; import com.google.common.base.Objects; import com.google.common.base.Optional; import org.spongepowered.api.text.Text; import javax.annotation.Nullable; /** * Represents an immutable configuration for an in-game title. Instances of this * interface can be created through the {@link TitleBuilder} by calling * {@link Titles#builder()}. * * <p>All properties of a title are optional - if they are not set it will use * the current default values from the client.</p> */ public class Title { protected final Optional<Text> title; protected final Optional<Text> subtitle; protected final Optional<Integer> fadeIn; protected final Optional<Integer> stay; protected final Optional<Integer> fadeOut; protected final boolean clear; protected final boolean reset; Title() { this(null, null, null, null, null, false, false); } /** * Constructs a new immutable {@link Title} with the specified properties. * * @param title The main title of the title, or {@code null} for default * @param subtitle The subtitle of the title, or {@code null} for default * @param fadeIn The fade in time of the title, or {@code null} for default * @param stay The stay time of the title, or {@code null} for default * @param fadeOut The fade out time of the title, or {@code null} for * default * @param clear {@code true} if this title clears the currently displayed * one first * @param reset {@code true} if this title resets all settings to default * first */ public Title(@Nullable Text title, @Nullable Text subtitle, @Nullable Integer fadeIn, @Nullable Integer stay, @Nullable Integer fadeOut, boolean clear, boolean reset) { this.title = Optional.fromNullable(title); this.subtitle = Optional.fromNullable(subtitle); this.fadeIn = Optional.fromNullable(fadeIn); this.stay = Optional.fromNullable(stay); this.fadeOut = Optional.fromNullable(fadeOut); this.clear = clear; this.reset = reset; } /** * Returns the title of this title configuration. * * @return The {@link Text} of the title, if it was configured */ public final Optional<Text> getTitle() { return this.title; } /** * Returns the subtitle of this title configuration. * * @return The {@link Text} of the subtitle, if it was configured */ public final Optional<Text> getSubtitle() { return this.subtitle; } /** * Returns the specified time to fade in the title on the client. Once this * period of time is over, the title will stay for the amount of time from * {@link #getStay}. * * <p>The default value for Vanilla is 20 (1 second).</p> * * @return The amount of ticks (1/20 second) for the fade in effect */ public final Optional<Integer> getFadeIn() { return this.fadeIn; } /** * Returns the specified time how long the title should stay on the client. * Once this period of time is over, the title will fade out using the * duration specified from {@link #getFadeOut}. * * <p>The default value for Vanilla is 60 (3 second).</p> * * @return The amount of ticks (1/20 second) for the stay effect */ public final Optional<Integer> getStay() { return this.stay; } /** * Returns the specified time to fade out the title on the client. * * <p>The default value for Vanilla is 20 (1 second).</p> * * @return The amount of ticks (1/20 second) for the fade out effect */ public final Optional<Integer> getFadeOut() { return this.fadeOut; } /** * Returns whether this configuration is clearing the current title from the * screen. * * @return True if the current title will be removed from the client's * screen */ public final boolean isClear() { return this.clear; } /** * Returns whether this configuration is clearing the current title from the * screen and resetting the current configuration to the default values. * * <p>This is recommended when you want to make sure to display a single * title.</p> * * @return True if the current settings will be reset to the defaults */ public final boolean isReset() { return this.reset; } /** * Creates a new {@link TitleBuilder} using the configuration of this * instance. * * @return A new builder to modify this Title configuration */ public TitleBuilder builder() { return new TitleBuilder(this); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (!(o instanceof Title)) { return false; } Title that = (Title) o; return this.title.equals(that.title) && this.subtitle.equals(that.subtitle) && this.fadeIn.equals(that.fadeIn) && this.stay.equals(that.stay) && this.fadeOut.equals(that.fadeOut) && this.clear == that.clear && this.reset == that.reset; } @Override public int hashCode() { return Objects.hashCode(this.title, this.subtitle, this.fadeIn, this.stay, this.fadeOut, this.clear, this.reset); } @Override public String toString() { return Objects.toStringHelper(this) .add("title", this.title) .add("subtitle", this.subtitle) .add("fadeIn", this.fadeIn) .add("stay", this.stay) .add("fadeOut", this.fadeOut) .add("clear", this.clear) .add("reset", this.reset) .toString(); } /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ public boolean isFlowerPot() { return false; } }
package org.springframework.act; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.MethodParameter; import org.springframework.samples.mvc.data.JavaBean; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; // handlersession status.setComplete()session @SessionAttributes(types={JavaBean.class}) @Controller public class BindController { private final Log logger = LogFactory.getLog(getClass()); @InitBinder("javaBean1") // () @ModelAttribute("javaBean1") public void initBinder1(WebDataBinder binder){ logger.error("initBinder1"); binder.setValidator(new BeanValidator1()); } @InitBinder("javaBean2") public void initBinder2(WebDataBinder binder){ logger.error("initBinder2"); binder.setValidator(new BeanValidator2()); } @ModelAttribute // @ModelAttributevalue"", javaBeanList public List<JavaBean> method0() { logger.error("methodList"); JavaBean bean1 = new JavaBean("b11", "b12", "b13"); JavaBean bean2 = new JavaBean("b21", "b22", "b23"); return Arrays.asList(new JavaBean[] {bean1, bean2}); } @ModelAttribute // ModelFactoryMA,valueinitModel invokeModelAttributeMethods public JavaBean method00() { logger.error("method00"); JavaBean bean = new JavaBean("b00", "b00", "b00"); return bean; } @ModelAttribute("javaBean1") public JavaBean method01() { logger.error("method01"); JavaBean bean = new JavaBean("01", "01", "01"); return bean; } @ModelAttribute("javaBean2") public JavaBean method02() { logger.error("method02"); JavaBean bean = new JavaBean("02", "02", "02"); return bean; } // HttpSession sessionsession @RequestMapping(value="/method1", method=RequestMethod.GET) //@Valid //@ModelAttribute("jb1")value@InitBinder("jb1") public ModelAndView method1(Model model, @Valid @ModelAttribute("javaBean1") JavaBean In, HttpServletRequest request) { logger.error("method1"); // In ModelFactory:initModel->invokeModelAttributeMethods(request, mavContainer) // InvocableHandlerMethod invokeForRequest->getMethodArgumentValues(request, mavContainer, providedArgs) // @SessionAttributes //Object ob = session.getAttribute("javaBean"); //Object ob2 = session.getAttribute("haha"); JavaBean beanInS = null; HttpSession session = request.getSession(false); if(session!=null) { Object sob = session.getAttribute("javaBean"); if(sob!=null && sob instanceof JavaBean) { beanInS = (JavaBean) sob; } Object sob1 = session.getAttribute("javaBean1"); Object sob2 = session.getAttribute("javaBean2"); } // method0 javaBeanListmap Map<String, Object> map = model.asMap(); Object javaBeanList = map.get("javaBeanList"); ModelAndView mv = new ModelAndView("bind"); map.put("testAttr", "testAttrValue"); // mv.addObject("testAttr", "testAttrValue"); mv.addObject("mapSize", map.size()); // sessionjavaBean //status.setComplete(); return mv; } @RequestMapping(value="/bind", method=RequestMethod.GET) @ModelAttribute public JavaBean method2(Model model, @Valid @ModelAttribute("javaBean2") JavaBean In, HttpServletRequest request) { logger.error("bind"); //Object ob = session.getAttribute("javaBean"); //Object ob2 = session.getAttribute("haha"); JavaBean beanInS = null; HttpSession session = request.getSession(false); if(session!=null) { Object sob = session.getAttribute("javaBean"); if(sob!=null && sob instanceof JavaBean) { beanInS = (JavaBean) sob; } Object sob1 = session.getAttribute("javaBean1"); Object sob2 = session.getAttribute("javaBean2"); } Map<String, Object> map = model.asMap(); // bean Object javaBean = map.get("javaBean"); // beanIn JavaBean bean = new JavaBean("bind1", "bind2", "bind3"); //status.setComplete(); return bean; } // method3-7 DispatcherServlet @RequestMapping(value="/method3", method=RequestMethod.GET) public String method3(Model model) { // bindjsp // DispatcherServlet - Successfully completed request logger.error("method3"); model.addAttribute("testAttr", "method3 return jsp"); return "bind"; } @RequestMapping(value="/method4", method=RequestMethod.GET) // @ResponseBodybind bindjsp // DispatcherServlet - Successfully completed request public @ResponseBody String method4(Model model) { logger.error("method4"); model.addAttribute("testAttr", "method4 return responsebody"); return "bind"; } @RequestMapping(value="/method5", method=RequestMethod.GET) @ModelAttribute public @ResponseBody String method5(Model model) { // method5jsp HTTP Status 404 - /spring-mvc-showcase/WEB-INF/views/method5.jsp // DispatcherServlet - Successfully completed request logger.error("method5"); model.addAttribute("testAttr", "method5 return responsebody"); return "bind"; } @RequestMapping(value="/method6", method=RequestMethod.GET) public @ResponseBody JavaBean method6(Model model) { // @ResponseBody<JavaBean xmlns=""><param1>m6</param1><param2>m6</param2><param3>m6</param3></JavaBean> method6jsp logger.error("method6"); model.addAttribute("testAttr", "method6 return jsp"); JavaBean bean = new JavaBean("m6", "m6", "m6"); return bean; } @RequestMapping(value="/method7", method=RequestMethod.GET) @ModelAttribute public @ResponseBody JavaBean method7(Model model) { // method7jsp JstlView - Forwarding to resource [/WEB-INF/views/method7.jsp] in InternalResourceView 'method7' // HTTP Status 404 - /spring-mvc-showcase/WEB-INF/views/method7.jsp // DispatcherServlet - Successfully completed request logger.error("method7"); model.addAttribute("testAttr", "method7 return method7.jsp"); JavaBean bean = new JavaBean("m7", "m7", "m7"); return bean; } @RequestMapping(value="/goredirect") public String goredirect(Model model, RedirectAttributes ra, HttpSession session) { logger.error("goredirect"); // model model.addAttribute("testAttr", "testAttr-BindController-goredirect"); model.addAttribute("attr1", "attr1-BindController-goredirect"); // addFlashAttribute session.setAttribute("SA", "SA-BindController-goredirect"); ra.addFlashAttribute("RA", "RA-BindController-goredirect"); // model session.setAttribute("OA1", "OA1-BindController-goredirect"); ra.addFlashAttribute("OA2", "OA2-BindController-goredirect"); ra.addAttribute( "OA3", "OA3-test"); return "redirect:/bcredirect"; /* FlashMap [ attributes={ OA2=OA2-BindController-goredirect, RA=RA-BindController-goredirect }, targetRequestPath=/spring-mvc-showcase/bcredirect, targetRequestParams={ OA3=[OA3-test] } ] */ /* mavContainer.getModel(): defaultMap->redirectModel redirectModel RequestMappingHandlerAdapter: ModelAndView invokeHandlerMethod(HttpServletRequest request,HttpServletResponse response, HandlerMethod handlerMethod) invocableMethod.invokeAndHandle(webRequest, mavContainer) ServletInvocableHandlerMethod: void invokeAndHandle(ServletWebRequest webRequest,ModelAndViewContainer mavContainer, Object... providedArgs) this.returnValueHandlers.handleReturnValue(returnValue, getReturnValueType(returnValue), mavContainer, webRequest) HandlerMethodReturnValueHandlerComposite: void handleReturnValue(Object returnValue, MethodParameter returnType,ModelAndViewContainer mavContainer, NativeWebRequest webRequest) handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest) ViewNameMethodReturnValueHandler: void handleReturnValue(Object returnValue, MethodParameter returnType,ModelAndViewContainer mavContainer, NativeWebRequest webRequest) mavContainer.setViewName(viewName); viewName = "redirect:/bcredirect" mavContainer.setRedirectModelScenario(true); */ /* RequestMappingHandlerAdapter invocableMethod.invokeAndHandle(webRequest, mavContainer) ModelAndViewContainer : redirectMap: {OA3=OA3-test}, redirectMapflashAttributes: {RA=RA-BindController-goredirect, OA2=OA2-BindController-goredirect} */ } } class BeanValidator1 implements Validator{ private final Log logger = LogFactory.getLog(getClass()); @Override public boolean supports(Class<?> clazz) { return JavaBean.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { logger.error("BeanValidator1 validate"); ValidationUtils.rejectIfEmpty(errors, "param1", "param1 is empty"); } } class BeanValidator2 implements Validator{ private final Log logger = LogFactory.getLog(getClass()); @Override public boolean supports(Class<?> clazz) { return JavaBean.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { logger.error("BeanValidator2 validate"); ValidationUtils.rejectIfEmpty(errors, "param2", "param2 is empty"); } }
package org.techern.minecraft; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.techern.minecraft.igneousextras.ConfigHandler; import org.techern.minecraft.igneousextras.blocks.IgneousBlocks; import org.techern.minecraft.igneousextras.proxy.CommonProxy; import org.techern.minecraft.igneousextras.proxy.ClientProxy; /** * A {@link net.minecraftforge.fml.common.Mod} for additional igneous rock blocks * * @since 0.0.1 */ @Mod(modid = "igneous_extras", version = IgneousExtrasMod.VERSION) public class IgneousExtrasMod { /** * The version {@link String} * * @since 0.0.1 */ public static final String VERSION = "0.0.2-SNAPSHOT"; /** * The number of registered blocks * * @since 0.0.2 */ public static short REGISTERED_BLOCKS = 0; /** * The number of registered items * * @since 0.0.2 */ public static short REGISTERED_ITEMS = 0; /** * The number of registered blocks * * @since 0.0.2 */ public static short REGISTERED_RECIPES = 0; /** * The {@link Logger} for this mod * * Gets replaced in {@link IgneousExtrasMod#handlePreInitEvent(FMLPreInitializationEvent)} * * @since 0.0.1 */ public static Logger LOGGER = LogManager.getLogger(IgneousExtrasMod.class); /** * A {@link SidedProxy} of either {@link CommonProxy} or {@link ClientProxy} * * @since 0.0.1 */ @SidedProxy(clientSide = "org.techern.minecraft.igneousextras.proxy.ClientProxy", serverSide = "org.techern.minecraft.igneousextras.proxy.CommonProxy") public static CommonProxy PROXY; /** * Handles the {@link FMLPreInitializationEvent} * * @param event The {@link FMLPreInitializationEvent} * @since 0.0.1 */ @Mod.EventHandler public void handlePreInitEvent(FMLPreInitializationEvent event) { LOGGER = event.getModLog(); LOGGER.debug("Attempting to load configuration file..."); ConfigHandler.init(new Configuration(event.getSuggestedConfigurationFile())); LOGGER.info("Loaded configuration file for Igneous Extras"); } /** * Handles the {@link FMLInitializationEvent} * * @param event The {@link FMLInitializationEvent} * @since 0.0.1 */ @Mod.EventHandler public void handleInitEvent(FMLInitializationEvent event) { IgneousBlocks.registerBlocks(); } /** * Handles the {@link FMLPostInitializationEvent} * * @param event The {@link FMLPostInitializationEvent} * @since 0.0.1 */ @Mod.EventHandler public void handlePostInitEvent(FMLPostInitializationEvent event) { IgneousBlocks.registerRecipes(); if (ConfigHandler.getConfig().hasChanged()) { LOGGER.info("Igneous Extras found extra / changed configuration, and is now saving"); ConfigHandler.getConfig().save(); } LOGGER.info("IE loaded {} blocks, {} items, and {} recipes", REGISTERED_BLOCKS, REGISTERED_ITEMS, REGISTERED_RECIPES); } }
package permafrost.tundra.lang; import com.wm.app.b2b.server.ServiceException; import com.wm.data.IData; import org.xml.sax.SAXParseException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Arrays; import java.util.Collection; /** * A collection of convenience methods for working with Integration Server service exceptions. */ public final class ExceptionHelper { /** * Disallow instantiation of this class. */ private ExceptionHelper() {} /** * Throws a new ServiceException whose message is constructed from the given list of causes. * * @param causes The list of exceptions which caused this new ServiceException to be thrown. * @throws ServiceException Always throws a new ServiceException using the given list of causes. */ public static void raise(Throwable... causes) throws ServiceException { raise(getMessage(causes)); } /** * Throws a new ServiceException whose message is constructed from the given list of causes. * * @param causes The list of exceptions which caused this new ServiceException to be thrown. * @throws ServiceException Always throws a new ServiceException using the given list of causes. */ public static void raise(Collection<? extends Throwable> causes) throws ServiceException { raise(getMessage(causes)); } /** * Throws a new ServiceException whose message is constructed from the given cause. * * @param message A message describing why this new ServiceException was thrown. * @param cause The exception which caused this new ServiceException to be thrown. * @throws ServiceException Always throws a new ServiceException using the given message and cause. */ public static void raise(String message, Throwable cause) throws ServiceException { throw new BaseException(message, cause); } /** * Throws a new ServiceException whose message is constructed from the given cause, unless the cause is already a * ServiceException or is an unchecked exception, in which case it is rethrown without modification. * * @param cause The exception which caused this new ServiceException to be thrown. * @throws ServiceException The given Throwable if it is already a ServiceException or an unchecked exception, * otherwise a new ServiceException constructed with the given Throwable as its cause. */ public static void raise(Throwable cause) throws ServiceException { if (cause instanceof ServiceException) { throw (ServiceException)cause; } else if (cause instanceof RuntimeException) { throw (RuntimeException)cause; } else { throw new BaseException(cause); } } /** * Throws a new RuntimeException constructed with the given cause, unless the cause is already a * an unchecked exception, in which case it is rethrown without modification. * * @param cause The exception which caused this new unchecked exception to be thrown. */ public static void raiseUnchecked(Throwable cause) { if (cause instanceof RuntimeException) { throw (RuntimeException)cause; } else if (cause instanceof Error) { throw (Error)cause; } else { throw new RuntimeException(cause); } } /** * Throws a new ServiceException with the given message. * * @param message A message describing why this new ServiceException was thrown. * @throws ServiceException Always throws a new ServiceException using the given message. */ public static void raise(String message) throws ServiceException { throw new BaseException(message); } /** * Throws a new ServiceException with an empty message. * * @throws ServiceException Always throws a new ServiceException. */ public static void raise() throws ServiceException { throw new BaseException(); } /** * Returns a message describing the given exception. * * @param exception An exception whose message is to be retrieved. * @return A message describing the given exception. */ public static String getMessage(Throwable exception) { if (exception == null) return ""; StringBuilder builder = new StringBuilder(); builder.append(exception.getClass().getName()); builder.append(": "); builder.append(exception.getMessage()); if (exception instanceof SAXParseException) { SAXParseException parseException = (SAXParseException)exception; //builder.append(" (Line ").append("" + ex.getLineNumber()).append(", Column ").append("" + ex.getColumnNumber()).append(")"); builder.append(String.format(" (Line %d, Column %d)", parseException.getLineNumber(), parseException.getColumnNumber())); } return builder.toString(); } /** * Returns a message describing the given list of exceptions. * * @param exceptions A list of exceptions whose messages are to be retrieved. * @return A message describing all exceptions in the given list. */ public static String getMessage(Collection<? extends Throwable> exceptions) { if (exceptions == null) return ""; return getMessage(exceptions.toArray(new Throwable[0])); } /** * Returns a message describing the given list of exceptions. * * @param exceptions A list of exceptions whose messages are to be retrieved. * @return A message describing all exceptions in the given list. */ public static String getMessage(Throwable... exceptions) { return ArrayHelper.join(getMessages(exceptions), "\n"); } /** * Returns a message describing the given list of exceptions. * * @param exceptions A list of exceptions whose messages are to be retrieved. * @return A message describing all exceptions in the given list. */ public static Collection<String> getMessages(Collection<? extends Throwable> exceptions) { if (exceptions == null) return null; return Arrays.asList(getMessages(exceptions.toArray(new Throwable[0]))); } /** * Returns a message describing the given list of exceptions. * * @param exceptions A list of exceptions whose messages are to be retrieved. * @return A message describing all exceptions in the given list. */ public static String[] getMessages(Throwable... exceptions) { if (exceptions == null) return null; String[] messages = new String[exceptions.length]; for (int i = 0; i < exceptions.length; i++) { if (exceptions[i] != null) { messages[i] = String.format("[%d] %s", i, getMessage(exceptions[i])); } } return messages; } /** * Returns the call stack associated with the given exception as an IData[] document list. * * @param exception An exception to retrieve the call stack from. * @return The call stack associated with the given exception as an IData[] document list. */ public static IData[] getStackTrace(Throwable exception) { if (exception == null) return null; return StackTraceElementHelper.toIDataArray(exception.getStackTrace()); } /** * Returns the printed stack trace for the given exception as a string. * * @param exception The exception to print the stack trace for. * @return A string containing the printed stack trace for the given exception. */ public static String getStackTraceString(Throwable exception) { return getStackTraceString(exception, -1); } /** * Returns the printed stack trace for the given exception as a string. * * @param exception The exception to print the stack trace for. * @param level How many levels of the stack trace to include. * @return A string containing the printed stack trace for the given exception. */ public static String getStackTraceString(Throwable exception, int level) { if (exception == null) return null; StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); exception.printStackTrace(printWriter); printWriter.flush(); printWriter.close(); String stackTrace; if (level < 0) { stackTrace = stringWriter.toString(); } else { String[] lines = StringHelper.lines(stringWriter.toString()); StringBuilder builder = new StringBuilder(); if (lines != null) { for (int i = 0; i < level + 1; i++) { if (i < lines.length) { builder.append(lines[i]); } else { break; } } if (level < lines.length - 1) { builder.append("\t... ").append(lines.length - level - 1).append(" more\r"); } } stackTrace = builder.toString(); } return stackTrace; } }
package pitt.search.semanticvectors; import pitt.search.semanticvectors.CompoundVectorBuilder.VectorLookupSyntax; import pitt.search.semanticvectors.DocVectors.DocIndexingStrategy; import pitt.search.semanticvectors.ElementalVectorStore.ElementalGenerationMethod; import pitt.search.semanticvectors.LuceneUtils.TermWeight; import pitt.search.semanticvectors.Search.SearchType; import pitt.search.semanticvectors.TermTermVectorsFromLucene.PositionalMethod; import pitt.search.semanticvectors.VectorStoreUtils.VectorStoreFormat; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.RealVector; import pitt.search.semanticvectors.vectors.RealVector.RealBindMethod; import pitt.search.semanticvectors.vectors.VectorType; import java.lang.reflect.Field; import java.util.Arrays; import java.util.logging.Logger; /** * Imports must include the declarations of all enums used as flag values */ /** * Class for representing and parsing command line flags into a configuration * instance to be passed to other components. * * Nearly all flags are configured once when an instance is created. Exceptions * are {@link #dimension()} and {#link vectortype()}, since these can be set * when a {@code VectorStore} is opened for reading. * * @author Dominic Widdows */ public class FlagConfig { private static final Logger logger = Logger.getLogger(FlagConfig.class.getCanonicalName()); private FlagConfig() { Field[] fields = FlagConfig.class.getDeclaredFields(); for (int q = 0; q < fields.length; q++) fields[q].setAccessible(true); } public String[] remainingArgs; // Add new command line flags here. By convention, please use lower case. private int dimension = 200; /** Dimension of semantic vector space, default value 200. Can be set when a {@code VectorStore} is opened. Recommended values are in the hundreds for {@link VectorType#REAL} and {@link VectorType#COMPLEX} and in the thousands for {@link VectorType#BINARY}, since binary dimensions are single bits. */ public int dimension() { return dimension; } /** Sets the {@link #dimension()}. */ public void setDimension(int dimension) { this.dimension = dimension; this.makeFlagsCompatible(); } private VectorType vectortype = VectorType.REAL; /** Ground field for vectors: real, binary or complex. Can be set when a {@code VectorStore} is opened. * Default value {@link VectorType#REAL}, corresponding to "-vectortype real". */ public VectorType vectortype() { return vectortype; } /** Sets the {@link #vectortype()}. */ public void setVectortype(VectorType vectortype) { this.vectortype = vectortype; this.makeFlagsCompatible(); } private RealBindMethod realbindmethod = RealBindMethod.CONVOLUTION; /** The binding method used for real vectors, see {@link RealVector#BIND_METHOD}. */ public RealBindMethod realbindmethod() { return realbindmethod; } private ElementalGenerationMethod elementalmethod = ElementalGenerationMethod.CONTENTHASH; /** The method used for generating elemental vectors. */ public ElementalGenerationMethod elementalmethod() { return elementalmethod; } private double samplingthreshold = -1; //suggest 10^-3 to 10^-5 /** * Subsampling threshold for embeddings */ public double samplingthreshold() { return samplingthreshold; } public boolean subsampleinwindow = true; /** * Word2vec approach for approximating "ramped" weighting * of a sliding window by sampling the window size uniformly * such that the proximal parts of the window have a higher * probability of not being ignored */ public boolean subsampleinwindow() { return subsampleinwindow; } public int numthreads = 4; /** * Number of threads to use when processing word embeddings */ public int numthreads() { return numthreads; } public int negsamples = 5; /** * Number of negative samples */ public int negsamples() { return negsamples; } public int seedlength = 10; /** Number of nonzero entries in a sparse random vector, default value 10 except for * when {@link #vectortype()} is {@link VectorType#BINARY}, in which case default of * {@link #dimension()} / 2 is enforced by {@link #makeFlagsCompatible()}. */ public int seedlength() { return seedlength; } private int minfrequency = 0; /** Minimum frequency of a term for it to be indexed, default value 0. */ public int minfrequency() { return minfrequency; } private int maxfrequency = Integer.MAX_VALUE; /** Maximum frequency of a term for it to be indexed, default value {@link Integer#MAX_VALUE}. */ public int maxfrequency() { return maxfrequency; } private int maxnonalphabetchars = Integer.MAX_VALUE; /** Maximum number of nonalphabetic characters in a term for it to be indexed, default value {@link Integer#MAX_VALUE}. */ public int maxnonalphabetchars() { return maxnonalphabetchars; } private int mintermlength = 0; /** Minimum number of characters in a term */ public int mintermlength() { return mintermlength; } private boolean filteroutnumbers = false; /** If {@code true}, terms containing only numeric characters are filtered out during indexing, default value {@code true}. */ public boolean filteroutnumbers() { return filteroutnumbers; } private boolean bindnotreleasehack = false; /** !hack! bind instead of release when constructing queries **/ public boolean bindnotreleasehack() { return bindnotreleasehack; } private boolean hybridvectors = false; /** If {@code true}, the StringEdit Class will produce hybrid vectors where each term vector = orthographic vector + semantic vector (from -queryvectorfile), default value {@code false}. */ public boolean hybridvectors() { return hybridvectors; } private int numsearchresults = 20; /** Number of search results to return, default value 20. */ public int numsearchresults() { return numsearchresults; } private int treceval = -1; /** Output search results in trec_eval format, with query number = treceval**/ public int treceval() { return treceval;} private String jsonfile = ""; /** Output search results as graph representation of a connectivity matrix in JSON**/ public String jsonfile() { return jsonfile;} /** Pathfinder parameters - default q = (n-1), default r = + infinity**/ private int pathfinderQ = -1; public int pathfinderQ() { return pathfinderQ; } private double pathfinderR = Double.POSITIVE_INFINITY; public double pathfinderR() { return pathfinderR; } private double searchresultsminscore = -1.0; /** Search results with similarity scores below this value will not be included in search results, default value -1. */ public double searchresultsminscore() { return searchresultsminscore; } private int numclusters = 10; /** Number of clusters used in {@link ClusterResults} and {@link ClusterVectorStore}, default value 10. */ public int numclusters() { return numclusters; } private int trainingcycles = 0; /** Number of training cycles used for Reflective Random Indexing in {@link BuildIndex}. */ public int trainingcycles() { return trainingcycles; } private boolean rescaleintraining = false; /** * If true, use {@link VectorStoreRAM#createRedistributedVectorStore} to make uniform coordinate distributions * when using several {@link #trainingcycles}. */ public boolean rescaleintraining() { return rescaleintraining; } private int windowradius = 5; /** Window radius used in {@link BuildPositionalIndex}, default value 5. */ public int windowradius() { return windowradius; } private SearchType searchtype = SearchType.SUM; /** Method used for combining and searching vectors, * default value {@link SearchType#SUM} corresponding to "-searchtype sum". */ public SearchType searchtype() { return searchtype; } private boolean fieldweight = false; /** Set to true if you want document vectors built from multiple fields to emphasize terms from shorter fields, default value {@code false}. */ public boolean fieldweight() { return fieldweight; } private TermWeight termweight = TermWeight.IDF; /** Term weighting used when constructing document vectors, default value {@link TermWeight#IDF} */ public LuceneUtils.TermWeight termweight() { return termweight; } private boolean porterstemmer = false; /** Tells {@link pitt.search.lucene.IndexFilePositions} to stem terms using Porter Stemmer, default value false. */ public boolean porterstemmer() { return porterstemmer; } private boolean usetermweightsintermsearch = false; /** Tells search implementations to scale each comparison score by a term weight during search, default value false. */ public boolean usetermweightsinsearch() { return usetermweightsintermsearch; } private boolean stdev = false; /** Score search results according to number of SDs above the mean across all search vectors, default false. */ public boolean stdev() { return stdev; } private boolean expandsearchspace = false; /** Generate bound products from each pairwise element of the search space, default false. * Expands the size of the space to n-squared. */ public boolean expandsearchspace() { return expandsearchspace; } private VectorStoreFormat indexfileformat = VectorStoreFormat.LUCENE; /** Format used for serializing / deserializing vectors from disk, default lucene. */ public VectorStoreFormat indexfileformat() { return indexfileformat; } private String termvectorsfile = "termvectors"; /** File to which termvectors are written during indexing. */ public String termvectorsfile() { return termvectorsfile; } private String docvectorsfile = "docvectors"; /** File to which docvectors are written during indexing. */ public String docvectorsfile() { return docvectorsfile; } private String termtermvectorsfile = "termtermvectors"; /** File to which term-term vectors are written during positional indexing. */ public String termtermvectorsfile() { return termtermvectorsfile; } private String queryvectorfile = "termvectors"; /** Principal vector store for finding query vectors, default termvectors.bin. */ public String queryvectorfile() { return queryvectorfile; } private String searchvectorfile = ""; /** Vector store for searching. Defaults to being the same as {@link #queryvectorfile}. May be different from queryvectorfile e.g., when using terms to search for documents. */ public String searchvectorfile() { return searchvectorfile; } private String boundvectorfile = ""; /** Auxiliary vector store used when searching for boundproducts. Used only in some searchtypes. */ public String boundvectorfile() { return boundvectorfile; } private String elementalvectorfile = "elementalvectors"; /** Random elemental vectors, sometimes written out, and used (e.g.) in conjunction with permuted vector file. */ public String elementalvectorfile() { return elementalvectorfile; } private String semanticvectorfile = "semanticvectors"; /** Semantic vectors; used so far as a name in PSI. */ public String semanticvectorfile() { return semanticvectorfile; } private String elementalpredicatevectorfile = "predicatevectors"; /** * Vectors used to represent elemental predicate vectors in PSI. For compatibility reasons, * the default name "predicatevectors" is typically used for these elemental vectors. */ public String elementalpredicatevectorfile() { return elementalpredicatevectorfile; } private String semanticpredicatevectorfile = "semanticpredicatevectors"; /** * Vectors used to represent elemental predicate vectors in PSI. For compatibility reasons, * the default name "predicatevectors" is typically used for these elemental vectors. */ public String semanticpredicatevectorfile() { return semanticpredicatevectorfile; } private String permutedvectorfile = "permtermvectors"; /** "Permuted term vectors, output by -positionalmethod permutation. */ public String permutedvectorfile() { return permutedvectorfile; } private String proximityvectorfile = "proxtermvectors"; /** "Permuted term vectors, output by -positionalmethod proximity. */ public String proximityvectorfile() { return proximityvectorfile; } private String directionalvectorfile ="drxntermvectors"; /** Permuted term vectors, output by -positionalmethod directional. */ public String directionalvectorfile() { return directionalvectorfile; } private String embeddingvectorfile ="embeddingvectors"; /** Permuted term vectors, output by -positionalmethod directional. */ public String embeddingvectorfile() { return embeddingvectorfile; } private String permplustermvectorfile ="permplustermvectors"; /** "Permuted term vectors, output by -positionalmethod permutationplusbasic. */ public String permplustermvectorfile() { return permplustermvectorfile; } private PositionalMethod positionalmethod = PositionalMethod.BASIC; /** Method used for positional indexing. */ public PositionalMethod positionalmethod() { return positionalmethod; } private String stoplistfile = ""; /** Path to file containing stopwords, one word per line, no default value. */ public String stoplistfile() { return stoplistfile; } private String startlistfile = ""; /** Path to file containing startwords, to be indexed always, no default value. */ public String startlistfile() { return startlistfile; } private String luceneindexpath = ""; /** Path to a Lucene index. Must contain term position information for positional applications, * See {@link BuildPositionalIndex}. */ public String luceneindexpath() { return luceneindexpath; } private String initialtermvectors = ""; /** If set, use the vectors in this file for initialization instead of new random vectors. */ public String initialtermvectors() { return initialtermvectors; } private String initialdocumentvectors = ""; /** If set, use the vectors in this file for initialization instead of new random vectors. */ public String initialdocumentvectors() { return initialdocumentvectors; } private DocIndexingStrategy docindexing = DocIndexingStrategy.INCREMENTAL; /** Memory management method used for indexing documents. */ public DocIndexingStrategy docindexing() { return docindexing; } private VectorLookupSyntax vectorlookupsyntax = VectorLookupSyntax.EXACTMATCH; /** Method used for looking up vectors in a vector store, default value {@link VectorLookupSyntax#EXACTMATCH}. */ public VectorLookupSyntax vectorlookupsyntax() { return vectorlookupsyntax; } private boolean matchcase = false; /** If true, matching of query terms is case-sensitive; otherwise case-insensitive, default false. */ public boolean matchcase() { return matchcase; } private String batchcompareseparator = "\\|"; /** Separator for documents on a single line in batch comparison mode, default '\\|' (as a regular expression for '|'). */ public String batchcompareseparator() { return batchcompareseparator; } private boolean suppressnegatedqueries = false; /** If true, suppress checking for the query negation token which indicates subsequent terms are to be negated when comparing terms, default false. * If this is set to {@code true}, all terms are treated as positive. */ public boolean suppressnegatedqueries() { return suppressnegatedqueries; } private String[] contentsfields = {"contents"}; /** Fields to be indexed for their contents, e.g., "title,description,notes", default "contents". */ public String[] contentsfields() { return contentsfields; } /** Set contentsfields (e.g. to specify for TermFilter **/ public void setContentsfields(String[] contentsfields) { this.contentsfields = contentsfields; } private String docidfield = "path"; /** Field used by Lucene to record the identifier for each document, default "path". */ public String docidfield() { return docidfield; } /** * Parse flags from a single string. Presumes that string contains only command line flags. */ public static FlagConfig parseFlagsFromString(String header) { String[] args = header.split("\\s"); return getFlagConfig(args); } /** * Parse command line flags and create public data structures for accessing them. * @param args * @return trimmed list of arguments with command line flags consumed */ // This implementation is linear in the number of flags available // and the number of command line arguments given. This is quadratic // and so inefficient, but in practice we only have to do it once // per command so it's probably negligible. public static FlagConfig getFlagConfig(String[] args) throws IllegalArgumentException { FlagConfig flagConfig = new FlagConfig(); if (args == null || args.length == 0) { flagConfig.remainingArgs = new String[0]; return flagConfig; } int argc = 0; while (args[argc].charAt(0) == '-') { String flagName = args[argc]; // Ignore trivial flags (without raising an error). if (flagName.equals("-")) continue; // Strip off initial "-" repeatedly to get desired flag name. while (flagName.charAt(0) == '-') { flagName = flagName.substring(1, flagName.length()); } try { Field field = FlagConfig.class.getDeclaredField(flagName); // Parse String arguments. if (field.getType().getName().equals("java.lang.String")) { String flagValue; try { flagValue = args[argc + 1]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } field.set(flagConfig, flagValue); argc += 2; // Parse String[] arguments, presuming they are comma-separated. // String[] arguments do not currently support fixed Value lists. } else if (field.getType().getName().equals("[Ljava.lang.String;")) { // All string values are lowercased. String flagValue; try { flagValue = args[argc + 1].toLowerCase(); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } field.set(flagConfig, flagValue.split(",")); argc += 2; } else if (field.getType().getName().equals("int")) { // Parse int arguments. try { field.setInt(flagConfig, Integer.parseInt(args[argc + 1])); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } argc += 2; } else if (field.getType().getName().equals("double")) { // Parse double arguments. try { field.setDouble(flagConfig, Double.parseDouble(args[argc + 1])); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } argc += 2; } else if (field.getType().isEnum()) { // Parse enum arguments. try { @SuppressWarnings({ "rawtypes", "unchecked" }) Class<Enum> className = (Class<Enum>) field.getType(); try { field.set(flagConfig, Enum.valueOf(className, args[argc + 1].toUpperCase())); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format( e.getMessage() + "\nAccepted values for '-%s' are:\n%s%n", field.getName(), Arrays.asList(className.getEnumConstants()), e)); } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } argc += 2; } else if (field.getType().getName().equals("boolean")) { // Parse boolean arguments. field.setBoolean(flagConfig, true); ++argc; } else { logger.warning("No support for fields of type: " + field.getType().getName()); argc += 2; } } catch (NoSuchFieldException e) { throw new IllegalArgumentException("Command line flag not defined: " + flagName); } catch (IllegalAccessException e) { logger.warning("Must be able to access all fields publicly, including: " + flagName); e.printStackTrace(); } if (argc >= args.length) { logger.fine("Consumed all command line input while parsing flags"); flagConfig.makeFlagsCompatible(); return flagConfig; } } // Enforce constraints between flags. flagConfig.makeFlagsCompatible(); // No more command line flags to parse. Trim args[] list and return. flagConfig.remainingArgs = new String[args.length - argc]; for (int i = 0; i < args.length - argc; ++i) { flagConfig.remainingArgs[i] = args[argc + i]; } return flagConfig; } public static void mergeWriteableFlagsFromString(String source, FlagConfig target) { FlagConfig sourceConfig = FlagConfig.parseFlagsFromString(source); mergeWriteableFlags(sourceConfig, target); } /** * Sets dimension and vectortype of target to be the same as that of source. */ public static void mergeWriteableFlags(FlagConfig source, FlagConfig target) { if (target.dimension != source.dimension) { VerbatimLogger.info("Setting dimension of target config to: " + source.dimension + "\n"); target.dimension = source.dimension; } if (target.vectortype != source.vectortype) { VerbatimLogger.info("Setting vectortype of target config to: " + source.vectortype + "\n"); target.vectortype = source.vectortype; } target.makeFlagsCompatible(); } /** * Checks some interaction between flags, and fixes them up to make them compatible. * * <br/> * In practice, this means: * <ul><li>If {@link #vectortype()} is {@code binary}, {@link #dimension()} is a multiple of 64, * or is increased to be become a multiple of 64. {@link #seedlength()} is set to be half this * number.</li> * <li>Setting {@link #searchvectorfile()} to {@link #queryvectorfile()} unless explicitly set otherwise.</li> * <li>Setting {@link RealVector#setBindType} if directed (this is something of a hack).</li> * </ul> */ private void makeFlagsCompatible() { if (vectortype == VectorType.BINARY) { // Impose "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks. if (dimension % 64 != 0) { dimension = (1 + (dimension / 64)) * 64; logger.fine("For performance reasons, dimensions for binary vectors must be a mutliple " + "of 64. Flags.dimension set to: " + dimension + "."); } // Impose "balanced binary vectors" constraint, to facilitate reasonable voting. if (seedlength != dimension / 2) { seedlength = dimension / 2; logger.fine("Binary vectors must be generated with a balanced number of zeros and ones." + " FlagConfig.seedlength set to: " + seedlength + "."); } } if (searchvectorfile.isEmpty()) searchvectorfile = queryvectorfile; // This is a potentially dangerous pattern! An alternative would be to make this setting // part of each real vector, as with complex Modes. But they aren't so nice either. // Let's avoid getting too committed to either approach and refactor at will. // dwiddows, 2013-09-27. if (vectortype == VectorType.REAL && realbindmethod == RealVector.RealBindMethod.PERMUTATION) { RealVector.setBindType(RealVector.RealBindMethod.PERMUTATION); } } //utility method to allow control of this option without //reconfiguring a FlagConfig public void setExpandsearchspace(boolean b) { // TODO Auto-generated method stub this.expandsearchspace = b; } }
package playlistpug.controllers; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import playlistpug.models.AudioData; import playlistpug.models.PlaylistCreator; import playlistpug.models.Song; @Controller public class HomeController { public HomeController(){} @Autowired private PlaylistCreator playlistCreator; public void setPlaylistCreator(PlaylistCreator playlistCreator){ this.playlistCreator = playlistCreator; } //to test song partial (WILL REMOVE LATER) @RequestMapping("/song") public ModelAndView getSong(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { return new ModelAndView("song", "model", new Song("songname", new AudioData(120), "/songpath", "lyrics")); } //test to show all multiple songs @RequestMapping("/home") public ModelAndView getHome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { return new ModelAndView("home", "allSongs", playlistCreator.getSongs()); } //user makes request to star @RequestMapping("/playlist") public ModelAndView getPlaylist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long songid = Long.parseLong(request.getParameter("")); return new ModelAndView("playlist"); } }
package ru.lanwen.verbalregex; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.valueOf; import static ru.lanwen.verbalregex.VerbalExpression.regex; public class VerbalExpression { private final Pattern pattern; public static class Builder { private StringBuilder prefixes = new StringBuilder(); private StringBuilder source = new StringBuilder(); private StringBuilder suffixes = new StringBuilder(); private int modifiers = Pattern.MULTILINE; /** * Package private. Use {@link #regex()} to build a new one * * @since 1.2 */ Builder() { } /** * Escapes any non-word char with two backslashes * used by any method, except {@link #add(String)} * * @param pValue - the string for char escaping * @return sanitized string value */ private String sanitize(final String pValue) { return pValue.replaceAll("[\\W]", "\\\\$0"); } /** * Counts occurrences of some substring in whole string * Same as org.apache.commons.lang3.StringUtils#countMatches(String, java.lang.String) * by effect. Used to count braces for {@link #or(String)} method * * @param where - where to find * @param what - what needs to count matches * @return 0 if nothing found, count of occurrences instead */ private int countOccurrencesOf(String where, String what) { return (where.length() - where.replace(what, "").length()) / what.length(); } public VerbalExpression build() { Pattern pattern = Pattern.compile(new StringBuilder(prefixes) .append(source).append(suffixes).toString(), modifiers); return new VerbalExpression(pattern); } /** * Append literal expression * Everything added to the expression should go trough this method * (keep in mind when creating your own methods). * All existing methods already use this, so for basic usage, you can just ignore this method. * <p/> * Example: * regex().add("\n.*").build() // produce exact "\n.*" regexp * * @param pValue - literal expression, not sanitized * @return this builder */ public Builder add(final String pValue) { this.source.append(pValue); return this; } /** * Append a regex from builder and wrap it with unnamed group (?: ... ) * * @param regex - VerbalExpression.Builder, that not changed * @return this builder * @since 1.2 */ public Builder add(final Builder regex) { return this.group().add(regex.build().toString()).endGr(); } /** * Enable or disable the expression to start at the beginning of the line * * @param pEnable - enables or disables the line starting * @return this builder */ public Builder startOfLine(final boolean pEnable) { this.prefixes.append(pEnable ? "^" : ""); if (!pEnable) { this.prefixes = new StringBuilder(this.prefixes.toString().replace("^", "")); } return this; } /** * Mark the expression to start at the beginning of the line * Same as {@link #startOfLine(boolean)} with true arg * * @return this builder */ public Builder startOfLine() { return startOfLine(true); } /** * Enable or disable the expression to end at the last character of the line * * @param pEnable - enables or disables the line ending * @return this builder */ public Builder endOfLine(final boolean pEnable) { this.suffixes.append(pEnable ? "$" : ""); if (!pEnable) { this.suffixes = new StringBuilder(this.suffixes.toString().replace("$", "")); } return this; } /** * Mark the expression to end at the last character of the line * Same as {@link #endOfLine(boolean)} with true arg * * @return this builder */ public Builder endOfLine() { return endOfLine(true); } /** * Add a string to the expression * * @param pValue - the string to be looked for (sanitized) * @return this builder */ public Builder then(final String pValue) { return this.add("(?:" + sanitize(pValue) + ")"); } /** * Add a string to the expression * Syntax sugar for {@link #then(String)} - use it in case: * regex().find("string") // when it goes first * * @param value - the string to be looked for (sanitized) * @return this builder */ public Builder find(final String value) { return this.then(value); } public Builder maybe(final String pValue) { return this.then(pValue).add("?"); } /** * Add a regex to the expression that might appear once (or not) * Example: * The following matches all names that have a prefix or not. * VerbalExpression.Builder namePrefix = regex().oneOf("Mr.", "Ms."); * VerbalExpression name = regex() * .maybe(namePrefix) * .space() * .zeroOrMore() * .word() * .oneOrMore() * .build(); * regex.test("Mr. Bond/") //true * regex.test("James") //true * * @param pValue - the string to be looked for * @return this builder */ public Builder maybe(final Builder regex) { return this.group().add(regex.build().toString()).endGr().add("?"); } /** * Add expression that matches anything (includes empty string) * * @return this builder */ public Builder anything() { return this.add("(?:.*)"); } /** * Add expression that matches anything, but not passed argument * * @param pValue - the string not to match * @return this builder */ public Builder anythingButNot(final String pValue) { return this.add("(?:[^" + sanitize(pValue) + "]*)"); } /** * Add expression that matches something that might appear once (or more) * * @return this builder */ public Builder something() { return this.add("(?:.+)"); } public Builder somethingButNot(final String pValue) { return this.add("(?:[^" + sanitize(pValue) + "]+)"); } /** * Add universal line break expression * * @return this builder */ public Builder lineBreak() { return this.add("(?:\\n|(\\r\\n))"); } /** * Shortcut for {@link #lineBreak()} * * @return this builder */ public Builder br() { return this.lineBreak(); } /** * Add expression to match a tab character ('\u0009') * * @return this builder */ public Builder tab() { return this.add("(?:\\t)"); } /** * Add word, same as [a-zA-Z_0-9]+ * * @return this builder */ public Builder word() { return this.add("(?:\\w+)"); } /** * Add word character, same as [a-zA-Z_0-9] * * @return this builder */ public Builder wordChar() { return this.add("(?:\\w)"); } /** * Add non-word character: [^\w] * * @return this builder */ public Builder nonWordChar() { return this.add("(?:\\W)"); } /** * Add non-digit: [^0-9] * * @return this builder */ public Builder nonDigit() { return this.add("(?:\\D)"); } /** * Add same as [0-9] * * @return this builder */ public Builder digit() { return this.add("(?:\\d)"); } /** * Add whitespace character, same as [ \t\n\x0B\f\r] * * @return this builder */ public Builder space() { return this.add("(?:\\s)"); } /** * Add non-whitespace character: [^\s] * * @return this builder */ public Builder nonSpace() { return this.add("(?:\\S)"); } public Builder anyOf(final String pValue) { this.add("[" + sanitize(pValue) + "]"); return this; } /** * Shortcut to {@link #anyOf(String)} * * @param value - CharSequence every char from can be matched * @return this builder */ public Builder any(final String value) { return this.anyOf(value); } /** * Add expression to match a range (or multiply ranges) * Usage: .range(from, to [, from, to ... ]) * Example: The following matches a hexadecimal number: * regex().range( "0", "9", "a", "f") // produce [0-9a-f] * * @param pArgs - pairs for range * @return this builder */ public Builder range(final String... pArgs) { StringBuilder value = new StringBuilder("["); for (int firstInPairPosition = 1; firstInPairPosition < pArgs.length; firstInPairPosition += 2) { String from = sanitize(pArgs[firstInPairPosition - 1]); String to = sanitize(pArgs[firstInPairPosition]); value.append(from).append("-").append(to); } value.append("]"); return this.add(value.toString()); } public Builder addModifier(final char pModifier) { switch (pModifier) { case 'd': modifiers |= Pattern.UNIX_LINES; break; case 'i': modifiers |= Pattern.CASE_INSENSITIVE; break; case 'x': modifiers |= Pattern.COMMENTS; break; case 'm': modifiers |= Pattern.MULTILINE; break; case 's': modifiers |= Pattern.DOTALL; break; case 'u': modifiers |= Pattern.UNICODE_CASE; break; case 'U': modifiers |= Pattern.UNICODE_CHARACTER_CLASS; break; default: break; } return this; } public Builder removeModifier(final char pModifier) { switch (pModifier) { case 'd': modifiers ^= Pattern.UNIX_LINES; break; case 'i': modifiers ^= Pattern.CASE_INSENSITIVE; break; case 'x': modifiers ^= Pattern.COMMENTS; break; case 'm': modifiers ^= Pattern.MULTILINE; break; case 's': modifiers ^= Pattern.DOTALL; break; case 'u': modifiers ^= Pattern.UNICODE_CASE; break; case 'U': modifiers ^= Pattern.UNICODE_CHARACTER_CLASS; break; default: break; } return this; } public Builder withAnyCase(final boolean pEnable) { if (pEnable) { this.addModifier('i'); } else { this.removeModifier('i'); } return this; } /** * Turn ON matching with ignoring case * Example: * // matches "a" * // matches "A" * regex().find("a").withAnyCase() * * @return this builder */ public Builder withAnyCase() { return withAnyCase(true); } public Builder searchOneLine(final boolean pEnable) { if (pEnable) { this.removeModifier('m'); } else { this.addModifier('m'); } return this; } /** * Convenient method to show that string usage count is exact count, range count or simply one or more * Usage: * regex().multiply("abc") // Produce (?:abc)+ * regex().multiply("abc", null) // Produce (?:abc)+ * regex().multiply("abc", (int)from) // Produce (?:abc){from} * regex().multiply("abc", (int)from, (int)to) // Produce (?:abc){from, to} * regex().multiply("abc", (int)from, (int)to, (int)...) // Produce (?:abc)+ * * @param pValue - the string to be looked for * @param count - (optional) if passed one or two numbers, it used to show count or range count * @return this builder * @see #oneOrMore() * @see #then(String) * @see #zeroOrMore() */ public Builder multiple(final String pValue, final int... count) { if (count == null) { return this.then(pValue).oneOrMore(); } switch (count.length) { case 1: return this.then(pValue).count(count[0]); case 2: return this.then(pValue).count(count[0], count[1]); default: return this.then(pValue).oneOrMore(); } } /** * Adds "+" char to regexp * Same effect as {@link #atLeast(int)} with "1" argument * Also, used by {@link #multiple(String, int...)} when second argument is null, or have length more than 2 * * @return this builder * @since 1.2 */ public Builder oneOrMore() { return this.add("+"); } /** * Adds "*" char to regexp, means zero or more times repeated * Same effect as {@link #atLeast(int)} with "0" argument * * @return this builder * @since 1.2 */ public Builder zeroOrMore() { return this.add("*"); } /** * Add count of previous group * for example: * .find("w").count(3) // produce - (?:w){3} * * @param count - number of occurrences of previous group in expression * @return this Builder */ public Builder count(final int count) { this.source.append("{").append(count).append("}"); return this; } /** * Produce range count * for example: * .find("w").count(1, 3) // produce (?:w){1,3} * * @param from - minimal number of occurrences * @param to - max number of occurrences * @return this Builder * @see #count(int) */ public Builder count(final int from, final int to) { this.source.append("{").append(from).append(",").append(to).append("}"); return this; } /** * Produce range count with only minimal number of occurrences * for example: * .find("w").atLeast(1) // produce (?:w){1,} * * @param from - minimal number of occurrences * @return this Builder * @see #count(int) * @see #oneOrMore() * @see #zeroOrMore() * @since 1.2 */ public Builder atLeast(final int from) { return this.add("{").add(valueOf(from)).add(",}"); } /** * Add a alternative expression to be matched * * Issue #32 * * @param pValue - the string to be looked for * @return this builder */ public Builder or(final String pValue) { this.prefixes.append("(?:"); int opened = countOccurrencesOf(this.prefixes.toString(), "("); int closed = countOccurrencesOf(this.suffixes.toString(), ")"); if (opened >= closed) { this.suffixes = new StringBuilder(")" + this.suffixes.toString()); } this.add(")|(?:"); if (pValue != null) { this.then(pValue); } return this; } /** * Adds an alternative expression to be matched * based on an array of values * * @param pValues - the strings to be looked for * @return this builder * @since 1.3 */ public Builder oneOf(final String... pValues) { if(pValues != null && pValues.length > 0) { this.add("(?:"); for(int i = 0; i < pValues.length; i++) { String value = pValues[i]; this.add("(?:"); this.add(value); this.add(")"); if(i < pValues.length - 1) { this.add("|"); } } this.add(")"); } return this; } /** * Adds capture - open brace to current position and closed to suffixes * * @return this builder */ public Builder capture() { this.suffixes.append(")"); return this.add("("); } /** * Shortcut for {@link #capture()} * * @return this builder * @since 1.2 */ public Builder capt() { return this.capture(); } /** * Same as {@link #capture()}, but don't save result * May be used to set count of duplicated captures, without creating a new saved capture * Example: * // Without group() - count(2) applies only to second capture * regex().group() * .capt().range("0", "1").endCapt().tab() * .capt().digit().count(5).endCapt() * .endGr().count(2); * * @return this builder * @since 1.2 */ public Builder group() { this.suffixes.append(")"); return this.add("(?:"); } /** * Close brace for previous capture and remove last closed brace from suffixes * Can be used to continue build regex after capture or to add multiply captures * * @return this builder */ public Builder endCapture() { if (this.suffixes.indexOf(")") != -1) { this.suffixes.setLength(suffixes.length() - 1); return this.add(")"); } else { throw new IllegalStateException("Can't end capture (group) when it not started"); } } /** * Shortcut for {@link #endCapture()} * * @return this builder * @since 1.2 */ public Builder endCapt() { return this.endCapture(); } /** * Closes current unnamed and unmatching group * Shortcut for {@link #endCapture()} * Use it with {@link #group()} for prettify code * Example: * regex().group().maybe("word").count(2).endGr() * * @return this builder * @since 1.2 */ public Builder endGr() { return this.endCapture(); } } /** * Use builder {@link #regex()} (or {@link #regex(ru.lanwen.verbalregex.VerbalExpression.Builder)}) * to create new instance of VerbalExpression * * @param pattern - {@link java.util.regex.Pattern} that constructed by builder */ private VerbalExpression(final Pattern pattern) { this.pattern = pattern; } /** * Test that full string matches regular expression * * @param pToTest - string to check match * @return true if matches exact string, false otherwise */ public boolean testExact(final String pToTest) { boolean ret = false; if (pToTest != null) { ret = pattern.matcher(pToTest).matches(); } return ret; } /** * Test that full string contains regex * * @param pToTest - string to check match * @return true if string contains regex, false otherwise */ public boolean test(final String pToTest) { boolean ret = false; if (pToTest != null) { ret = pattern.matcher(pToTest).find(); } return ret; } /** * Extract full string that matches regex * Same as {@link #getText(String, int)} for 0 group * * @param toTest - string to extract from * @return group 0, extracted from text */ public String getText(final String toTest) { return getText(toTest, 0); } /** * Extract exact group from string * * @param toTest - string to extract from * @param group - group to extract * @return extracted group * @since 1.1 */ public String getText(final String toTest, final int group) { Matcher m = pattern.matcher(toTest); StringBuilder result = new StringBuilder(); while (m.find()) { result.append(m.group(group)); } return result.toString(); } @Override public String toString() { return pattern.pattern(); } /** * Creates new instance of VerbalExpression builder from cloned builder * * @param pBuilder - instance to clone * @return new VerbalExpression.Builder copied from passed * @since 1.1 */ public static Builder regex(final Builder pBuilder) { Builder builder = new Builder(); builder.prefixes = new StringBuilder(pBuilder.prefixes); builder.source = new StringBuilder(pBuilder.source); builder.suffixes = new StringBuilder(pBuilder.suffixes); builder.modifiers = pBuilder.modifiers; return builder; } /** * Creates new instance of VerbalExpression builder * * @return new VerbalExpression.Builder * @since 1.1 */ public static Builder regex() { return new Builder(); } }
package se.su.it.svc; import org.eclipse.jetty.security.IdentityService; import org.eclipse.jetty.security.LoginService; import org.eclipse.jetty.security.SpnegoUserPrincipal; import org.eclipse.jetty.server.UserIdentity; import org.eclipse.jetty.util.B64Code; import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.ietf.jgss.*; import javax.security.auth.Subject; /** * Handle Negotiate requests for mechs SPNEGO & Krb5, based on org.eclipse.jetty.security.SpnegoLoginService */ public final class SpnegoAndKrb5LoginService extends AbstractLifeCycle implements LoginService { private static final Logger LOG = Log.getLogger(SpnegoAndKrb5LoginService.class); public static final String OID_MECH_KRB5 = "1.2.840.113554.1.2.2"; public static final String OID_MECH_SPNEGO = "1.3.6.1.5.5.2"; private String name; private IdentityService service; private GSSContext gssContext; public SpnegoAndKrb5LoginService( String name, String targetName ) throws IllegalStateException, GSSException { this.name = name; gssContext = setupContext(targetName); if (gssContext == null) { throw new IllegalStateException("Failed to establish GSSContext"); } } public final String getName() { return name; } /** * Login a user using GSSAPI through SPNEGO or KRB5 mechs. * * @param username will not be used, credentials contains all that's necessary. * @param credentials a auth token String. Expect ClassCastException for anything else. * @return a UserIdentity if we succeed or null if we don't. */ public final UserIdentity login(String username, Object credentials) { byte[] authToken = B64Code.decode((String)credentials); try { while (!gssContext.isEstablished()) { authToken = gssContext.acceptSecContext(authToken,0,authToken.length); } String clientName = gssContext.getSrcName().toString(); String role = clientName.substring(clientName.indexOf('@') + 1); LOG.debug("GSSContext: established a security context"); LOG.debug("Client Principal is: " + gssContext.getSrcName()); LOG.debug("Server Principal is: " + gssContext.getTargName()); LOG.debug("Client Default Role: " + role); SpnegoUserPrincipal user = new SpnegoUserPrincipal(clientName, authToken); Subject subject = new Subject(); subject.getPrincipals().add(user); return service.newUserIdentity(subject,user, new String[]{role}); } catch (GSSException gsse) { // Can't throw exception forward due to interface implementation LOG.warn("Failed while validating credentials: " + gsse.getMessage()); } return null; } /** * Validate a user identity. * * @param user the UserIdentity to validate. * @return always false * @see LoginService#validate(org.eclipse.jetty.server.UserIdentity) */ public final boolean validate(UserIdentity user) { return false; // A previously created user identity is never valid. } /** * @see org.eclipse.jetty.security.LoginService#getIdentityService() () */ public final IdentityService getIdentityService() { return service; } /** * @see LoginService#setIdentityService(org.eclipse.jetty.security.IdentityService) */ public final void setIdentityService(IdentityService service) { this.service = service; } /** * Not implemented, not needed */ public final void logout(UserIdentity user) { // No need to implement. } /** * Setup & return a GSSContext. * * @param targetName the target name (server principal) to use * @return a GSSContext. * @throws GSSException if something goes wrong with the setup of the context. */ private static GSSContext setupContext(String targetName) throws GSSException { Oid[] mechs = { new Oid(OID_MECH_KRB5), // Krb5 new Oid(OID_MECH_SPNEGO) // Spnego }; GSSManager manager = GSSManager.getInstance(); GSSName gssName = manager.createName(targetName, null); GSSCredential serverCreds = manager.createCredential(gssName, GSSCredential.INDEFINITE_LIFETIME, mechs, GSSCredential.ACCEPT_ONLY); return manager.createContext(serverCreds); } }
//@@author A0114395E package seedu.address.logic.parser; import java.util.List; import com.joestelmach.natty.DateGroup; public class NattyParser { private static NattyParser instance = null; private static String emptyValue = "-"; // Exists only to defeat instantiation. protected NattyParser() { } // Returns the singleton instance public static NattyParser getInstance() { if (instance == null) { instance = new NattyParser(); } return instance; } /** * Parses, analyses and converts 'rich text' into a timestamp * * @param String - e.g. 'Tomorrow' * @return String - Timestamp */ public String parseNLPDate(String argsString) { if (argsString.trim().equals(emptyValue)) { return emptyValue; } com.joestelmach.natty.Parser nParser = new com.joestelmach.natty.Parser(); List<DateGroup> groups = nParser.parse(argsString); String output = ""; for (DateGroup group : groups) { output = group.getDates().get(0).toString().replace("CST", ""); } return output; } }
//@@author A0139925U package seedu.tache.logic.commands; import java.util.Date; import java.util.List; import java.util.Optional; import seedu.tache.commons.core.EventsCenter; import seedu.tache.commons.core.Messages; import seedu.tache.commons.events.ui.JumpToListRequestEvent; import seedu.tache.commons.exceptions.IllegalValueException; import seedu.tache.commons.util.CollectionUtil; import seedu.tache.logic.commands.exceptions.CommandException; import seedu.tache.model.recurstate.RecurState.RecurInterval; import seedu.tache.model.tag.UniqueTagList; import seedu.tache.model.task.DateTime; import seedu.tache.model.task.Name; import seedu.tache.model.task.ReadOnlyTask; import seedu.tache.model.task.Task; import seedu.tache.model.task.UniqueTaskList; import seedu.tache.model.task.UniqueTaskList.DuplicateTaskException; /** * Edits the details of an existing task in the task manager. */ public class EditCommand extends Command implements Undoable { public static final String COMMAND_WORD = "edit"; public static final String SHORT_COMMAND_WORD = "e"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits the details of the task identified " + "by the index number used in the last tasks listing. " + "Existing values will be overwritten by the input values.\n" + "Parameters: INDEX (must be a positive integer) change <parameter1> to <new_value1> and " + "<parameter2> to <new_value2>...\n" + "Example: " + COMMAND_WORD + " 1 change startdate to 10 nov and change starttime to 3.30pm"; public static final String MESSAGE_EDIT_TASK_SUCCESS = "Edited Task: \n%1$s"; public static final String MESSAGE_NOT_EDITED = "No valid parameter detected to edit."; public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the task manager."; public static final String MESSAGE_INVALID_DATE_RANGE = "Start date can not be before end date"; public static final String MESSAGE_PART_OF_RECURRING_TASK = "This task is part of a recurring task and cannot be edited."; public static final String MESSAGE_REQUIRE_BOTH_START_END = "Recurring tasks requires both start date and end date"; public static final String SPECIAL_CASE_TIME_STRING = "23:59:59"; private final int filteredTaskListIndex; private final EditTaskDescriptor editTaskDescriptor; private boolean commandSuccess; private ReadOnlyTask taskToEdit; private ReadOnlyTask originalTask; /** * @param filteredTaskListIndex the index of the task in the filtered task list to edit * @param editTaskDescriptor details to edit the task with */ public EditCommand(int filteredTaskListIndex, EditTaskDescriptor editTaskDescriptor) { assert filteredTaskListIndex > 0; assert editTaskDescriptor != null; // converts filteredTaskListIndex from one-based to zero-based. this.filteredTaskListIndex = filteredTaskListIndex - 1; this.editTaskDescriptor = new EditTaskDescriptor(editTaskDescriptor); commandSuccess = false; } @Override public CommandResult execute() throws CommandException { List<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); if (filteredTaskListIndex >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } taskToEdit = lastShownList.get(filteredTaskListIndex); cloneOriginalTask(taskToEdit); Task editedTask; try { checkPartOfRecurringTask(taskToEdit); editedTask = createEditedTask(taskToEdit, editTaskDescriptor); try { model.updateTask(taskToEdit, editedTask); } catch (UniqueTaskList.DuplicateTaskException dpe) { throw new CommandException(MESSAGE_DUPLICATE_TASK); } //model.updateCurrentFilteredList(); commandSuccess = true; undoHistory.push(this); EventsCenter.getInstance().post(new JumpToListRequestEvent(model.getFilteredTaskListIndex(taskToEdit))); return new CommandResult(String.format(MESSAGE_EDIT_TASK_SUCCESS, taskToEdit)); } catch (IllegalValueException e) { return new IncorrectCommand(e.getMessage()).execute(); } } private static Task createEditedTask(ReadOnlyTask taskToEdit, EditTaskDescriptor editTaskDescriptor) throws IllegalValueException { assert taskToEdit != null; Name updatedName = editTaskDescriptor.getName().orElseGet(taskToEdit::getName); Optional<DateTime> updatedStartDateTime; Optional<DateTime> updatedEndDateTime; if (taskToEdit.getStartDateTime().isPresent()) { updatedStartDateTime = Optional.of(new DateTime(taskToEdit.getStartDateTime().get())); } else { updatedStartDateTime = Optional.empty(); } if (taskToEdit.getEndDateTime().isPresent()) { updatedEndDateTime = Optional.of(new DateTime(taskToEdit.getEndDateTime().get())); } else { updatedEndDateTime = Optional.empty(); } if (editTaskDescriptor.getStartDate().isPresent()) { if (updatedStartDateTime.isPresent()) { updatedStartDateTime.get().setDateOnly(editTaskDescriptor.getStartDate().get()); } else { updatedStartDateTime = Optional.of(new DateTime(editTaskDescriptor.getStartDate().get())); updatedStartDateTime.get().setDefaultTime(); } } if (editTaskDescriptor.getEndDate().isPresent()) { if (updatedEndDateTime.isPresent()) { updatedEndDateTime.get().setDateOnly(editTaskDescriptor.getEndDate().get()); } else { updatedEndDateTime = Optional.of(new DateTime(editTaskDescriptor.getEndDate().get())); updatedEndDateTime.get().setDefaultTime(); } } if (editTaskDescriptor.getStartTime().isPresent()) { if (updatedStartDateTime.isPresent()) { updatedStartDateTime.get().setTimeOnly(editTaskDescriptor.getStartTime().get()); } else { updatedStartDateTime = Optional.of(new DateTime(editTaskDescriptor.getStartTime().get())); } } if (editTaskDescriptor.getEndTime().isPresent()) { if (updatedEndDateTime.isPresent()) { updatedEndDateTime.get().setTimeOnly(editTaskDescriptor.getEndTime().get()); } else { updatedEndDateTime = Optional.of(new DateTime(editTaskDescriptor.getEndTime().get())); } } UniqueTagList updatedTags = editTaskDescriptor.getTags().orElseGet(taskToEdit::getTags); RecurInterval updatedRecurInterval = taskToEdit.getRecurState().getRecurInterval(); if (editTaskDescriptor.getRecurringInterval().isPresent()) { if (updatedStartDateTime.isPresent() && updatedEndDateTime.isPresent()) { updatedRecurInterval = editTaskDescriptor.getRecurringInterval().get(); } else { throw new IllegalValueException(MESSAGE_REQUIRE_BOTH_START_END); } } updatedEndDateTime = checkFloatingToNonFloatingCase(editTaskDescriptor, updatedStartDateTime, updatedEndDateTime); checkValidDateRange(updatedStartDateTime, updatedEndDateTime); checkSpecialCase(editTaskDescriptor, updatedEndDateTime); return new Task(updatedName, updatedStartDateTime, updatedEndDateTime, updatedTags, true, updatedRecurInterval, taskToEdit.getRecurState().getRecurCompletedList()); } private static Optional<DateTime> checkFloatingToNonFloatingCase(EditTaskDescriptor editTaskDescriptor, Optional<DateTime> updatedStartDateTime, Optional<DateTime> updatedEndDateTime) throws IllegalValueException { if (!updatedEndDateTime.isPresent() && !editTaskDescriptor.getEndDate().isPresent()) { if (updatedStartDateTime.isPresent()) { //Floating Task to Non-Floating, do not allow start date only Optional<DateTime> temp = Optional.of(updatedStartDateTime.get()); return temp; } } return updatedEndDateTime; } private static void checkValidDateRange(Optional<DateTime> updatedStartDateTime, Optional<DateTime> updatedEndDateTime) throws IllegalValueException { if (updatedStartDateTime.isPresent() && updatedEndDateTime.isPresent()) { if (updatedStartDateTime.get().compareTo(updatedEndDateTime.get()) == 1) { throw new IllegalValueException(MESSAGE_INVALID_DATE_RANGE); } } } private static void checkSpecialCase(EditTaskDescriptor editTaskDescriptor, Optional<DateTime> updatedEndDateTime) throws IllegalValueException { //Special case End Date -> Today will result in a default timing of 2359 instead of 0000 if (editTaskDescriptor.getEndDate().isPresent() && updatedEndDateTime.isPresent() && !editTaskDescriptor.getEndTime().isPresent()) { if ((new DateTime(editTaskDescriptor.getEndDate().get()).isToday()) && updatedEndDateTime.get().getDate().before(new Date())) { updatedEndDateTime.get().setTimeOnly(SPECIAL_CASE_TIME_STRING); } } } /** * Stores the details to edit the task with. Each non-empty field value will replace the * corresponding field value of the task. */ public static class EditTaskDescriptor { private Optional<Name> name = Optional.empty(); private Optional<String> startDate = Optional.empty(); private Optional<String> endDate = Optional.empty(); private Optional<String> startTime = Optional.empty(); private Optional<String> endTime = Optional.empty(); private Optional<UniqueTagList> tags = Optional.empty(); private Optional<RecurInterval> interval = Optional.empty(); private Optional<Boolean> recurringStatus = Optional.empty(); public EditTaskDescriptor() {} public EditTaskDescriptor(EditTaskDescriptor toCopy) { this.name = toCopy.getName(); this.startDate = toCopy.getStartDate(); this.endDate = toCopy.getEndDate(); this.startTime = toCopy.getStartTime(); this.endTime = toCopy.getEndTime(); this.tags = toCopy.getTags(); this.interval = toCopy.getRecurringInterval(); this.recurringStatus = toCopy.getRecurringStatus(); } /** * Returns true if at least one field is edited. */ public boolean isAnyFieldEdited() { return CollectionUtil.isAnyPresent(this.name, this.startDate, this.endDate, this.startTime, this.endTime, this.tags, this.interval, this.recurringStatus); } public void setName(Optional<Name> name) { assert name != null; this.name = name; } public Optional<Name> getName() { return name; } public void setStartDate(Optional<String> date) { assert date != null; this.startDate = date; } public Optional<String> getStartDate() { return startDate; } public void setEndDate(Optional<String> date) { assert date != null; this.endDate = date; } public Optional<String> getEndDate() { return endDate; } public void setStartTime(Optional<String> startTime) { assert startTime != null; this.startTime = startTime; } public Optional<String> getStartTime() { return startTime; } public void setEndTime(Optional<String> endTime) { assert endTime != null; this.endTime = endTime; } public Optional<String> getEndTime() { return endTime; } public void setTags(Optional<UniqueTagList> tags) { assert tags != null; this.tags = tags; } public Optional<UniqueTagList> getTags() { return tags; } public void setRecurringInterval(Optional<RecurInterval> interval) { assert interval != null; this.interval = interval; } public Optional<RecurInterval> getRecurringInterval() { return interval; } public void setRecurringStatus(Optional<Boolean> recurringStatus) { assert recurringStatus != null; this.recurringStatus = recurringStatus; } public Optional<Boolean> getRecurringStatus() { return recurringStatus; } } private void cloneOriginalTask(ReadOnlyTask taskToEdit) { //Workaround as Java could not deep copy taskToEdit for some fields DateTime workAroundStartDateTime = null; DateTime workAroundEndDateTime = null; try { if (taskToEdit.getStartDateTime().isPresent()) { workAroundStartDateTime = new DateTime(taskToEdit.getStartDateTime().get().getAmericanDateTime()); } if (taskToEdit.getEndDateTime().isPresent()) { workAroundEndDateTime = new DateTime(taskToEdit.getEndDateTime().get().getAmericanDateTime()); } } catch (IllegalValueException e1) { e1.printStackTrace(); } originalTask = new Task(taskToEdit.getName(), Optional.ofNullable(workAroundStartDateTime), Optional.ofNullable(workAroundEndDateTime), taskToEdit.getTags(), taskToEdit.getActiveStatus(), taskToEdit.getRecurState().getRecurInterval(), taskToEdit.getRecurState().getRecurCompletedList()); } private void checkPartOfRecurringTask(ReadOnlyTask taskToEdit) throws IllegalValueException { if (taskToEdit.getRecurState().isGhostRecurring()) { throw new IllegalValueException(MESSAGE_PART_OF_RECURRING_TASK); } } //@@author A0150120H @Override public boolean isUndoable() { return commandSuccess; } @Override public String undo() throws CommandException { try { model.updateTask(taskToEdit, originalTask); model.updateFilteredListToShowAll(); EventsCenter.getInstance().post(new JumpToListRequestEvent(model.getFilteredTaskListIndex(taskToEdit))); return String.format(MESSAGE_EDIT_TASK_SUCCESS, taskToEdit); } catch (DuplicateTaskException e) { throw new CommandException(MESSAGE_DUPLICATE_TASK); } } //@@author }
package seedu.taskboss.model.category; import seedu.taskboss.commons.exceptions.IllegalValueException; /** * Represents a Category in TaskBoss. * Guarantees: immutable; name is valid as declared in {@link #isValidCategoryName(String)} */ public class Category { private static final String EMPTY_STRING = ""; public static final String MESSAGE_CATEGORY_CONSTRAINTS = "Categories names should be alphanumeric"; public static final String CATEGORY_VALIDATION_REGEX = "\\p{Alnum}+"; public final String categoryName; public static Category done = new Category("Done", EMPTY_STRING); public Category(String name) throws IllegalValueException { assert name != null; String trimmedName = name.trim(); if (!isValidCategoryName(trimmedName)) { throw new IllegalValueException(MESSAGE_CATEGORY_CONSTRAINTS); } this.categoryName = formatName(trimmedName); } private Category(String name, String toDifferentiaiteBetweenConstructors) { assert toDifferentiaiteBetweenConstructors.equals(EMPTY_STRING); this.categoryName = name; } /** * Returns true if a given string is a valid category name. */ public static boolean isValidCategoryName(String test) { return test.matches(CATEGORY_VALIDATION_REGEX); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Category // instanceof handles nulls && this.categoryName.equals(((Category) other).categoryName)); // state check } @Override public int hashCode() { return categoryName.hashCode(); } /** * Format state as text for viewing. */ public String toString() { return '[' + categoryName + ']'; } //@@author A0147990R private String formatName(String name) { if (name.length() <= 1) { return name.toUpperCase(); } else { String first = name.substring(0, 1).toUpperCase(); String rest = name.substring(1).toLowerCase(); return first + rest; } } }
package spring.service.impl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.springframework.stereotype.Service; import spring.dto.CarDTO; import spring.service.EdmundsService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @Service("edmundsService") public class EdmundsServiceImpl implements EdmundsService { public String getCarInfo(String vin) { String url = "https://api.edmunds.com/api/vehicle/v2/vins/" + vin + "?fmt=json&api_key=ymg7mstwnse27aar9259tn7q"; try { String json = makeHttpRequest(url); if (json != null) { CarDTO car = new CarDTO(); car = tranformJSONRespone(json); car = getReviews(car); car = getAverageCustomerRating(car); if (car != null) { json = convertToJSON(car); } } return json; } catch (Exception e) { } return null; } private CarDTO tranformJSONRespone(String json) throws Exception { CarDTO car = new CarDTO(); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(json); if (jsonObject != null) { JSONObject makes = (JSONObject) jsonObject.get("make"); if (makes != null) { car.setMake((String) makes.get("name")); } JSONObject models = (JSONObject) jsonObject.get("model"); if (models != null) { car.setModel((String) models.get("name")); } JSONArray years = (JSONArray) jsonObject.get("years"); if (years != null && years.get(0) != null) { JSONObject year = (JSONObject) years.get(0); if (year != null) { car.setYear((Long) year.get("year")); } } JSONObject mpg = (JSONObject) jsonObject.get("MPG"); if (mpg != null) { car.setCityMpg((String) mpg.get("city")); car.setHighwayMpg((String) mpg.get("highway")); } JSONObject engine = (JSONObject) jsonObject.get("engine"); if (engine != null) { car.setEngineFuelType((String) engine.get("type")); } } return car; } private String convertToJSON(CarDTO dto) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); String jsonInString = mapper.writeValueAsString(dto); return jsonInString; } private CarDTO getReviews(CarDTO dto) { try { String editorialUrl = "https://api.edmunds.com/v1/content/editorreviews?make=" + dto.getMake() + "&model=" + dto.getModel() + "&year=" + dto.getYear() + "&fmt=json&api_key=ymg7mstwnse27aar9259tn7q"; String json = makeHttpRequest(editorialUrl); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(json); if (jsonObject != null) { JSONObject editorial = (JSONObject) jsonObject.get("editorial"); if (editorial != null) { dto.setEditorReview((String) editorial.get("edmundsSays")); } } } catch (Exception e) { } return dto; } private CarDTO getAverageCustomerRating(CarDTO dto) { try { String customerReviewUrl = "https://api.edmunds.com/api/vehiclereviews/v2/" + dto.getMake().toLowerCase() + "/" + dto.getModel().toLowerCase() + "/" + dto.getYear() + "?fmt=json&api_key=ymg7mstwnse27aar9259tn7q"; String json = makeHttpRequest(customerReviewUrl); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(json); if (jsonObject != null) { String averageRating = (String) jsonObject.get("averageRating"); dto.setAverageConsumerRating(averageRating); } } catch (Exception e) { } return dto; } private String makeHttpRequest(String url) { String json = null; try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); if (response != null) { json = response.body().string(); } } catch (Exception e) { } return json; } }
package su.iota.backend.models.game; import com.google.gson.annotations.Expose; import org.jetbrains.annotations.NotNull; public class Coordinate { @Expose private final int offX; @Expose private final int offY; public static final int BASE_X = Field.FIELD_DIMENSION / 2; public static final int BASE_Y = Field.FIELD_DIMENSION / 2; public Coordinate(int offX, int offY) { this.offX = offX; this.offY = offY; } public static Coordinate fromRaw(int x, int y) { return new Coordinate(x - BASE_X, y - BASE_Y); } public int getOffX() { return offX; } public int getOffY() { return offY; } public int getX() { return BASE_X + offX; } public int getY() { return BASE_Y + offY; } @NotNull public Coordinate plus(@NotNull Coordinate other) { return new Coordinate(offX + other.offX, offY + other.offY); } @NotNull public Coordinate minus(@NotNull Coordinate other) { return new Coordinate(offX - other.offX, offY - other.offY); } @SuppressWarnings("MagicNumber") public boolean isInRange() { final int x = getX(); final int y = getY(); boolean isOk = true; //noinspection ConstantConditions isOk = isOk && (x > 0 && x < Field.FIELD_DIMENSION - 1); isOk = isOk && (y > 0 && y < Field.FIELD_DIMENSION - 1); return isOk; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final Coordinate other = (Coordinate) obj; return offX == other.offX && offY == other.offY; } @Override public int hashCode() { int result = offX; result = 31 * result + offY; return result; } @NotNull @Override public String toString() { return "Coordinate{" + "offX=" + offX + ", offY=" + offY + '}'; } }
package tech.aroma.data.sql.serializers; import tech.sirwellington.alchemy.annotations.access.Internal; import tech.sirwellington.alchemy.annotations.access.NonInstantiable; /** * Contains the internal structure of the SQL Tables * used to serialize Aroma objects. * * @author SirWellington */ @Internal @NonInstantiable final class Tables { @NonInstantiable static final class Applications { static final String APP_ID = "app_id"; static final String APP_NAME = "app_name"; static final String APP_DESCRIPTION = "app_description"; static final String ORG_ID = "organization_id"; static final String OWNERS = "owners"; static final String PROGRAMMING_LANGUAGE = "programming_language"; static final String TIER = "tier"; static final String TIME_PROVISIONED = "time_provisioned"; static final String TIME_LAST_UPDATED = "time_last_updated"; static final String TIME_OF_TOKEN_EXPIRATION = "time_of_token_expiration"; static final String ICON_MEDIA_ID = "app_icon_media_id"; } @NonInstantiable static final class Messages { static final String TABLE_NAME = "Messages"; static final String TABLE_NAME_TOTALS_BY_APP = "Messages_Totals_By_App"; static final String TABLE_NAME_TOTALS_BY_TITLE = "Messages_Totals_By_Title"; static final String MESSAGE_ID = "message_id"; static final String TITLE = "title"; static final String BODY = "body"; static final String PRIORITY = "priority"; static final String TIME_CREATED = "time_created"; static final String TIME_RECEIVED = "time_received"; static final String HOSTNAME = "hostname"; static final String IP_ADDRESS = "ip_address"; static final String DEVICE_NAME = "device_name"; static final String APP_ID = Applications.APP_ID; static final String APP_NAME = Applications.APP_NAME; static final String TOTAL_MESSAGES = "total_messages"; static final String REQUEST_TIME = "request_time"; } @NonInstantiable static class Organizations { static final String TABLE_NAME = "Organizations"; static final String TABLE_NAME_MEMBERS = "Organizations_Members"; static final String ORG_ID = "organization_id"; static final String ORG_NAME = "organization_name"; static final String OWNERS = "owners"; static final String ICON_LINK = "icon_link"; static final String INDUSTRY = "industry"; static final String EMAIL = "contact_email"; static final String GITHUB_PROFILE = "github_profile"; static final String STOCK_NAME = "stock_name"; static final String TIER = "tier"; static final String DESCRIPTION = "description"; static final String WEBSITE = "website"; } @NonInstantiable static class Tokens { static final String TABLE_NAME = "Tokens"; static final String TOKEN_ID = "token_id"; static final String OWNER_ID = "owner_id"; static final String OWNER_NAME = "owner_name"; static final String TIME_OF_EXPIRATION = "time_of_expiration"; static final String TIME_OF_CREATION = "time_of_creation"; static final String ORG_ID = Organizations.ORG_ID; static final String TOKEN_TYPE = "token_type"; static final String TOKEN_STATUS = "token_status"; } }
package ua.yyunikov.algorithms.util; import java.util.Arrays; /** * Utilities for performing different kind of operations with arrays. */ public interface ArrayUtils { /** * Swaps two elements in the array. * * @param array array with element * @param pos1 index of first element * @param pos2 index of second element */ static void swap(final int[] array, final int pos1, final int pos2) { final int temp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = temp; } /** * Splits array into two smaller arrays. If the array length is odd then the right part (0 index) will always be bigger. * Example: array 2, 1, 3, 5, 4 will be splitted into 2, 1 and 3, 5, 4, * * @param array array to split * @return two arrays as a split result, 0 index - left part (equal by length or bigger then right part), 1 index - right part. */ static int[][] split(final int[] array) { final int[] part1 = Arrays.copyOfRange(array, 0, array.length / 2); final int[] part2 = Arrays.copyOfRange(array, array.length / 2, array.length); final int[][] result = new int[2][]; result[0] = part1; result[1] = part2; return result; } }
package uk.ac.edukapp.servlets; import java.io.IOException; import java.sql.Timestamp; import java.util.UUID; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import uk.ac.edukapp.model.Accountinfo; import uk.ac.edukapp.model.LtiProvider; import uk.ac.edukapp.model.Useraccount; import uk.ac.edukapp.util.MD5Util; /** * Servlet implementation class RegisterServlet */ public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Log log; /** * @see HttpServlet#HttpServlet() */ public RegisterServlet() { super(); log = LogFactory.getLog(RegisterServlet.class); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get parameters String username = null; String email = null; String password = null; String realname = null; username = request.getParameter("username"); email = request.getParameter("email"); password = request.getParameter("password"); realname = request.getParameter("name"); // TO-DO add salt // need to store it in db -> need to alter table/entity // String salt = null; EntityManagerFactory factory = Persistence .createEntityManagerFactory("edukapp"); EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Useraccount ua = new Useraccount(); ua.setUsername(username); ua.setEmail(email); UUID token = UUID.randomUUID(); String salt = token.toString(); String hashedPassword = MD5Util.md5Hex(salt + password); ua.setPassword(hashedPassword); ua.setSalt(salt); em.persist(ua); try { log.info("ua id:"+ua.getId()); Accountinfo ai = new Accountinfo(); ai.setId(ua.getId()); ai.setRealname(realname); java.util.Date date = new java.util.Date(); Timestamp now = new Timestamp(date.getTime()); ai.setJoined(now); em.persist(ai); } catch (Exception e) { log.info("got an exception"); e.printStackTrace(); } // Create an LTI Provider for this account LtiProvider ltiProvider = new LtiProvider(ua); em.persist(ltiProvider); em.getTransaction().commit(); em.close(); factory.close(); doForward(request, response, "/index.jsp"); } private void doForward(HttpServletRequest request, HttpServletResponse response, String jsp) throws ServletException, IOException { RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher(jsp); dispatcher.forward(request, response); } }
package uk.co.jemos.podam.api; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import net.jcip.annotations.Immutable; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.jemos.podam.common.AttributeStrategy; import uk.co.jemos.podam.common.ConstructorAdaptiveComparator; import uk.co.jemos.podam.common.PodamBooleanValue; import uk.co.jemos.podam.common.PodamByteValue; import uk.co.jemos.podam.common.PodamCharValue; import uk.co.jemos.podam.common.PodamCollection; import uk.co.jemos.podam.common.PodamConstants; import uk.co.jemos.podam.common.PodamConstructor; import uk.co.jemos.podam.common.PodamDoubleValue; import uk.co.jemos.podam.common.PodamFloatValue; import uk.co.jemos.podam.common.PodamIntValue; import uk.co.jemos.podam.common.PodamLongValue; import uk.co.jemos.podam.common.PodamShortValue; import uk.co.jemos.podam.common.PodamStrategyValue; import uk.co.jemos.podam.common.PodamStringValue; import uk.co.jemos.podam.exceptions.PodamMockeryException; /** * The PODAM factory implementation * * @author mtedone * * @since 1.0.0 * */ @ThreadSafe @Immutable public class PodamFactoryImpl implements PodamFactory { private static final String RESOLVING_COLLECTION_EXCEPTION_STR = "An exception occurred while resolving the collection"; private static final String MAP_CREATION_EXCEPTION_STR = "An exception occurred while creating a Map object"; private static final String UNCHECKED_STR = "unchecked"; private static final String THE_ANNOTATION_VALUE_STR = "The annotation value: "; private static final Type[] NO_TYPES = new Type[0]; /** Application logger */ private static final Logger LOG = LoggerFactory .getLogger(PodamFactoryImpl.class.getName()); /** * External factory to delegate production this factory cannot handle * <p> * The default is {@link LoggingExternalFactory}. * </p> */ private final PodamFactory externalFactory; /** * The strategy to use to fill data. * <p> * The default is {@link RandomDataProviderStrategy}. * </p> */ private final DataProviderStrategy strategy; /** * A map to keep one object for each class. If memoization is enabled, the * factory will use this table to avoid creating objects of the same class * multiple times. */ private Map<Class<?>, Object> memoizationTable = new HashMap<Class<?>, Object>(); /** * Default constructor. */ public PodamFactoryImpl() { this(LoggingExternalFactory.getInstance(), RandomDataProviderStrategy.getInstance()); } /** * Constructor with non-default strategy * * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(DataProviderStrategy strategy) { this(LoggingExternalFactory.getInstance(), strategy); } /** * Constructor with non-default external factory * * @param externalFactory * External factory to delegate production this factory cannot * handle */ public PodamFactoryImpl(PodamFactory externalFactory) { this(externalFactory, RandomDataProviderStrategy.getInstance()); } /** * Full constructor. * * @param externalFactory * External factory to delegate production this factory cannot * handle * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(PodamFactory externalFactory, DataProviderStrategy strategy) { this.externalFactory = externalFactory; this.strategy = strategy; } /** * {@inheritDoc} */ @Override public <T> T manufacturePojo(Class<T> pojoClass) { return this.manufacturePojo(pojoClass, NO_TYPES); } /** * {@inheritDoc} */ @Override public <T> T manufacturePojoWithFullData(Class<T> pojoClass, Type... genericTypeArgs) { AbstractRandomDataProviderStrategy sortingStrategy; if (getStrategy() instanceof AbstractRandomDataProviderStrategy) { sortingStrategy = (AbstractRandomDataProviderStrategy) getStrategy(); } else { throw new IllegalStateException("manufacturePojoWithFullData can" + " only be used with strategies derived from" + " AbstractRandomDataProviderStrategy"); } ConstructorAdaptiveComparator constructorComparator; if (sortingStrategy.getConstructorComparator() instanceof ConstructorAdaptiveComparator) { constructorComparator = (ConstructorAdaptiveComparator) sortingStrategy.getConstructorComparator(); } else { throw new IllegalStateException("manufacturePojoWithFullData can" + " only be used with constructor comparators derived from" + " ConstructorAdaptiveComparator"); } constructorComparator.addHeavyClass(pojoClass); T retValue = this.manufacturePojo(pojoClass, genericTypeArgs); constructorComparator.removeHeavyClass(pojoClass); return retValue; } /** * {@inheritDoc} */ @Override public <T> T manufacturePojo(Class<T> pojoClass, Type... genericTypeArgs) { Map<Class<?>, Integer> pojos = new HashMap<Class<?>, Integer>(); pojos.put(pojoClass, 0); try { return this.manufacturePojoInternal(pojoClass, pojos, genericTypeArgs); } catch (InstantiationException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (InvocationTargetException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(e.getMessage(), e); } } /** * {@inheritDoc} */ @Override public DataProviderStrategy getStrategy() { return strategy; } private Type[] fillTypeArgMap(final Map<String, Type> typeArgsMap, final Class<?> pojoClass, final Type[] genericTypeArgs) { TypeVariable<?>[] array = pojoClass.getTypeParameters(); List<TypeVariable<?>> typeParameters = new ArrayList<TypeVariable<?>>(Arrays.asList(array)); Iterator<TypeVariable<?>> iterator = typeParameters.iterator(); /* Removing types, which are already in typeArgsMap */ while (iterator.hasNext()) { if (typeArgsMap.containsKey(iterator.next().getName())) { iterator.remove(); } } if (typeParameters.size() > genericTypeArgs.length) { String msg = pojoClass.getCanonicalName() + " is missing generic type arguments, expected " + typeParameters + " found " + Arrays.toString(genericTypeArgs); throw new IllegalStateException(msg); } int i; for (i = 0; i < typeParameters.size(); i++) { typeArgsMap.put(typeParameters.get(i).getName(), genericTypeArgs[i]); } Type[] genericTypeArgsExtra; if (typeParameters.size() < genericTypeArgs.length) { genericTypeArgsExtra = Arrays.copyOfRange(genericTypeArgs, i, genericTypeArgs.length); } else { genericTypeArgsExtra = null; } /* Adding types, which were specified during inheritance */ Class<?> clazz = pojoClass; while (clazz != null) { Type superType = clazz.getGenericSuperclass(); clazz = clazz.getSuperclass(); if (superType instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) superType; Type[] actualParamTypes = paramType.getActualTypeArguments(); TypeVariable<?>[] paramTypes = clazz.getTypeParameters(); for (i = 0; i < actualParamTypes.length && i < paramTypes.length; i++) { if (actualParamTypes[i] instanceof Class) { typeArgsMap.put(paramTypes[i].getName(), actualParamTypes[i]); } } } } return genericTypeArgsExtra; } private Object instantiatePojoWithoutConstructors( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); // If no publicly accessible constructors are available, // the best we can do is to find a constructor (e.g. // getInstance()) Method[] declaredMethods = pojoClass.getDeclaredMethods(); strategy.sort(declaredMethods); // A candidate factory method is a method which returns the // Class type // The parameters to pass to the method invocation Object[] parameterValues = null; Object[] noParams = new Object[] {}; for (Method candidateConstructor : declaredMethods) { if (!Modifier.isStatic(candidateConstructor.getModifiers()) || !candidateConstructor.getReturnType().equals(pojoClass) || retValue != null) { continue; } parameterValues = new Object[candidateConstructor .getParameterTypes().length]; Class<?>[] parameterTypes = candidateConstructor.getParameterTypes(); if (parameterTypes.length == 0) { parameterValues = noParams; } else { // This is a factory method with arguments Annotation[][] parameterAnnotations = candidateConstructor .getParameterAnnotations(); int idx = 0; for (Class<?> parameterType : parameterTypes) { List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); Type genericType = candidateConstructor.getGenericParameterTypes()[idx]; parameterValues[idx] = manufactureParameterValue(parameterType, genericType, annotations, typeArgsMap, pojos, genericTypeArgsExtra == null ? NO_TYPES : genericTypeArgsExtra); idx++; } } try { retValue = candidateConstructor.invoke(pojoClass, parameterValues); LOG.debug("Could create an instance using " + candidateConstructor); } catch (Exception t) { LOG.debug( "PODAM could not create an instance for constructor: " + candidateConstructor + ". Will try another one...", t); } } if (retValue == null) { retValue = externalFactory.manufacturePojo(pojoClass, genericTypeArgs); } if (retValue == null) { LOG.warn("For class {} PODAM could not possibly create" + " a value. It will be returned as null.", pojoClass); } return retValue; } /** * It resolves generic parameter type * * * @param paramType * The generic parameter type * @param typeArgsMap * A map of resolved types * @param methodGenericTypeArgs * Return value posible generic types of the generic parameter * type * @return value for class representing the generic parameter type */ private Class<?> resolveGenericParameter(Type paramType, Map<String, Type> typeArgsMap, AtomicReference<Type[]> methodGenericTypeArgs) { Class<?> parameterType = null; methodGenericTypeArgs.set(NO_TYPES); if (paramType instanceof TypeVariable<?>) { final TypeVariable<?> typeVariable = (TypeVariable<?>) paramType; final Type type = typeArgsMap.get(typeVariable.getName()); if (type != null) { parameterType = resolveGenericParameter(type, typeArgsMap, methodGenericTypeArgs); } } else if (paramType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) paramType; parameterType = (Class<?>) pType.getRawType(); methodGenericTypeArgs.set(pType.getActualTypeArguments()); } else if (paramType instanceof WildcardType) { WildcardType wType = (WildcardType) paramType; Type[] bounds = wType.getLowerBounds(); String msg; if (bounds != null && bounds.length > 0) { msg = "Lower bounds:"; } else { bounds = wType.getUpperBounds(); msg = "Upper bounds:"; } if (bounds != null && bounds.length > 0) { LOG.debug(msg + Arrays.toString(bounds)); parameterType = resolveGenericParameter(bounds[0], typeArgsMap, methodGenericTypeArgs); } } else if (paramType instanceof Class) { parameterType = (Class<?>) paramType; } if (parameterType == null) { LOG.warn("Unrecognized type {}. Will use Object instead", paramType); parameterType = Object.class; } return parameterType; } private Object resolvePrimitiveValue(Class<?> primitiveClass, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (primitiveClass.equals(int.class)) { if (!annotations.isEmpty()) { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } } else if (primitiveClass.equals(long.class)) { if (!annotations.isEmpty()) { retValue = getLongValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } } else if (primitiveClass.equals(float.class)) { if (!annotations.isEmpty()) { retValue = getFloatValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } } else if (primitiveClass.equals(double.class)) { if (!annotations.isEmpty()) { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } } else if (primitiveClass.equals(boolean.class)) { if (!annotations.isEmpty()) { retValue = getBooleanValueForAnnotation(annotations); } if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } } else if (primitiveClass.equals(byte.class)) { if (!annotations.isEmpty()) { retValue = getByteValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } } else if (primitiveClass.equals(short.class)) { if (!annotations.isEmpty()) { retValue = getShortValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } } else if (primitiveClass.equals(char.class)) { if (!annotations.isEmpty()) { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } } else { throw new IllegalArgumentException( String.format("%s is unsupported primitive type", primitiveClass)); } return retValue; } /** * It returns the boolean value indicated in the annotation. * * @param annotations * The collection of annotations for the annotated attribute * @return The boolean value indicated in the annotation */ private Boolean getBooleanValueForAnnotation(List<Annotation> annotations) { Boolean retValue = null; for (Annotation annotation : annotations) { if (PodamBooleanValue.class.isAssignableFrom(annotation.getClass())) { PodamBooleanValue localStrategy = (PodamBooleanValue) annotation; retValue = localStrategy.boolValue(); break; } } return retValue; } private Byte getByteValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Byte retValue = null; for (Annotation annotation : annotations) { if (PodamByteValue.class.isAssignableFrom(annotation.getClass())) { PodamByteValue intStrategy = (PodamByteValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Byte.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a byte type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { byte minValue = intStrategy.minValue(); byte maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getByteInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Short getShortValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Short retValue = null; for (Annotation annotation : annotations) { if (PodamShortValue.class.isAssignableFrom(annotation.getClass())) { PodamShortValue shortStrategy = (PodamShortValue) annotation; String numValueStr = shortStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Short.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a short type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { short minValue = shortStrategy.minValue(); short maxValue = shortStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getShortInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It creates and returns a random {@link Character} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * @return A random {@link Character} value */ private Character getCharacterValueWithinRange( List<Annotation> annotations, AttributeMetadata attributeMetadata) { Character retValue = null; for (Annotation annotation : annotations) { if (PodamCharValue.class.isAssignableFrom(annotation.getClass())) { PodamCharValue annotationStrategy = (PodamCharValue) annotation; char charValue = annotationStrategy.charValue(); if (charValue != ' ') { retValue = charValue; } else { char minValue = annotationStrategy.minValue(); char maxValue = annotationStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getCharacterInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Integer getIntegerValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Integer retValue = null; for (Annotation annotation : annotations) { if (PodamIntValue.class.isAssignableFrom(annotation.getClass())) { PodamIntValue intStrategy = (PodamIntValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Integer.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to an Integer. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { int minValue = intStrategy.minValue(); int maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getIntegerInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Float getFloatValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Float retValue = null; for (Annotation annotation : annotations) { if (PodamFloatValue.class.isAssignableFrom(annotation.getClass())) { PodamFloatValue floatStrategy = (PodamFloatValue) annotation; String numValueStr = floatStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Float.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Float. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { float minValue = floatStrategy.minValue(); float maxValue = floatStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getFloatInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It creates and returns a random {@link Double} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * * @return a random {@link Double} value */ private Double getDoubleValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Double retValue = null; for (Annotation annotation : annotations) { if (PodamDoubleValue.class.isAssignableFrom(annotation.getClass())) { PodamDoubleValue doubleStrategy = (PodamDoubleValue) annotation; String numValueStr = doubleStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Double.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Double. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { double minValue = doubleStrategy.minValue(); double maxValue = doubleStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getDoubleInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Long getLongValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Long retValue = null; for (Annotation annotation : annotations) { if (PodamLongValue.class.isAssignableFrom(annotation.getClass())) { PodamLongValue longStrategy = (PodamLongValue) annotation; String numValueStr = longStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Long.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Long. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { long minValue = longStrategy.minValue(); long maxValue = longStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getLongInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It attempts to resolve the given class as a wrapper class and if this is * the case it assigns a random value * * * @param candidateWrapperClass * The class which might be a wrapper class * @param attributeMetadata * The attribute's metadata, if any, used for customisation * @return {@code null} if this is not a wrapper class, otherwise an Object * with the value for the wrapper class */ private Object resolveWrapperValue(Class<?> candidateWrapperClass, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (candidateWrapperClass.equals(Integer.class)) { if (!annotations.isEmpty()) { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } } else if (candidateWrapperClass.equals(Long.class)) { if (!annotations.isEmpty()) { retValue = getLongValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } } else if (candidateWrapperClass.equals(Float.class)) { if (!annotations.isEmpty()) { retValue = getFloatValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } } else if (candidateWrapperClass.equals(Double.class)) { if (!annotations.isEmpty()) { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } } else if (candidateWrapperClass.equals(Boolean.class)) { if (!annotations.isEmpty()) { retValue = getBooleanValueForAnnotation(annotations); } if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } } else if (candidateWrapperClass.equals(Byte.class)) { if (!annotations.isEmpty()) { retValue = getByteValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } } else if (candidateWrapperClass.equals(Short.class)) { if (!annotations.isEmpty()) { retValue = getShortValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } } else if (candidateWrapperClass.equals(Character.class)) { if (!annotations.isEmpty()) { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } } return retValue; } @SuppressWarnings({ UNCHECKED_STR }) private <T> T instantiatePojo(Class<T> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws SecurityException { T retValue = null; Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors.length == 0 || Modifier.isAbstract(pojoClass.getModifiers())) { /* No public constructors, we will try static factory methods */ try { retValue = (T) instantiatePojoWithoutConstructors( pojoClass, pojos, genericTypeArgs); } catch (Exception e) { LOG.debug("We couldn't create an instance for pojo: " + pojoClass + " with factory methods, will " + " try non-public constructors.", e); } /* Then non-public constructors */ if (retValue == null) { constructors = pojoClass.getDeclaredConstructors(); } } if (retValue == null && constructors.length > 0) { /* We want constructor with minumum number of parameters * to speed up the creation */ strategy.sort(constructors); for (Constructor<?> constructor : constructors) { try { Object[] parameterValues = getParameterValuesForConstructor( constructor, pojoClass, pojos, genericTypeArgs); // Being a generic method we cannot be sure on the identity of // T, therefore the mismatch between the newInstance() return // value (Object) and T is acceptable, thus the SuppressWarning // annotation // Security hack if (!constructor.isAccessible()) { constructor.setAccessible(true); } retValue = (T) constructor.newInstance(parameterValues); if (retValue != null) { LOG.debug("We could create an instance with constructor: " + constructor); break; } } catch (Exception e) { LOG.debug("We couldn't create an instance for pojo: {} with" + " constructor: {}. Will try with another one.", pojoClass, constructor, e); } } } if (retValue == null) { retValue = externalFactory.manufacturePojo(pojoClass, genericTypeArgs); } return retValue; } @SuppressWarnings(UNCHECKED_STR) private <T> T manufacturePojoInternal(Class<T> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { LOG.debug("Manufacturing {} with parameters {}", pojoClass, Arrays.toString(genericTypeArgs)); T retValue = null; // reuse object from memoization table if (strategy.isMemoizationEnabled()) { T objectToReuse = (T) memoizationTable.get(pojoClass); if (objectToReuse != null) { return objectToReuse; } } if (pojoClass.isPrimitive()) { // For JDK POJOs we can't retrieve attribute name List<Annotation> annotations = new ArrayList<Annotation>(); String noName = null; return (T) resolvePrimitiveValue(pojoClass, annotations, new AttributeMetadata(noName, pojoClass, annotations, pojoClass)); } if (pojoClass.isInterface() || Modifier.isAbstract(pojoClass.getModifiers())) { Class<T> specificClass = (Class<T>) strategy .getSpecificClass(pojoClass); if (!specificClass.equals(pojoClass)) { return this.manufacturePojoInternal(specificClass, pojos, genericTypeArgs); } else { if (specificClass.isInterface()) { return externalFactory.manufacturePojo(pojoClass, genericTypeArgs); } } } try { retValue = instantiatePojo(pojoClass, pojos, genericTypeArgs); } catch (SecurityException e) { throw new PodamMockeryException( "Security exception while applying introspection.", e); } // update memoization table with new object // the reference is stored before properties are set so that recursive // properties can use it if (strategy.isMemoizationEnabled()) { memoizationTable.put(pojoClass, retValue); } /* Construction failed, no point to continue */ if (retValue == null) { return null; } if (retValue instanceof Collection && ((Collection<?>)retValue).size() == 0) { fillCollection((Collection<? super Object>)retValue, pojos, genericTypeArgs); } else if (retValue instanceof Map && ((Map<?,?>)retValue).size() == 0) { fillMap((Map<? super Object,? super Object>)retValue, pojos, genericTypeArgs); } Class<?>[] parameterTypes = null; Class<?> attributeType = null; ClassInfo classInfo = PodamUtils.getClassInfo(pojoClass, strategy.getExcludedAnnotations()); // According to JavaBeans standards, setters should have only // one argument Object setterArg = null; for (Method setter : classInfo.getClassSetters()) { List<Annotation> pojoAttributeAnnotations = retrieveFieldAnnotations( pojoClass, setter); String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); parameterTypes = setter.getParameterTypes(); if (parameterTypes.length != 1) { LOG.warn("Skipping setter with non-single arguments {}", setter); continue; } // A class which has got an attribute to itself (e.g. // recursive hierarchies) attributeType = parameterTypes[0]; // If an attribute has been annotated with // PodamAttributeStrategy, it takes the precedence over any // other strategy. Additionally we don't pass the attribute // metadata for value customisation; if user went to the extent // of specifying a PodamAttributeStrategy annotation for an // attribute they are already customising the value assigned to // that attribute. PodamStrategyValue attributeStrategyAnnotation = containsAttributeStrategyAnnotation(pojoAttributeAnnotations); if (null != attributeStrategyAnnotation) { AttributeStrategy<?> attributeStrategy = attributeStrategyAnnotation .value().newInstance(); if (LOG.isDebugEnabled()) { LOG.debug("The attribute: " + attributeName + " will be filled using the following strategy: " + attributeStrategy); } setterArg = returnAttributeDataStrategyValue(attributeType, attributeStrategy); } else { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } Type[] typeArguments = NO_TYPES; // If the parameter is a generic parameterized type resolve // the actual type arguments if (setter.getGenericParameterTypes()[0] instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) setter .getGenericParameterTypes()[0]; typeArguments = attributeParameterizedType .getActualTypeArguments(); } else if (setter.getGenericParameterTypes()[0] instanceof TypeVariable) { final TypeVariable<?> typeVariable = (TypeVariable<?>) setter .getGenericParameterTypes()[0]; Type type = typeArgsMap.get(typeVariable.getName()); if (type instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) type; typeArguments = attributeParameterizedType .getActualTypeArguments(); attributeType = (Class<?>) attributeParameterizedType .getRawType(); } else { attributeType = (Class<?>) type; } } AtomicReference<Type[]> typeGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); for (int i = 0; i < typeArguments.length; i++) { if (typeArguments[i] instanceof TypeVariable) { Class<?> resolvedType = resolveGenericParameter(typeArguments[i], typeArgsMap, typeGenericTypeArgs); if (!Collection.class.isAssignableFrom(resolvedType) && !Map.class.isAssignableFrom(resolvedType)) { typeArguments[i] = resolvedType; } } } setterArg = manufactureAttributeValue(retValue, pojos, attributeType, setter.getGenericParameterTypes()[0], pojoAttributeAnnotations, attributeName, typeArgsMap, typeArguments); if (null == setterArg) { setterArg = externalFactory.manufacturePojo(attributeType); } } if (setterArg != null) { try { setter.invoke(retValue, setterArg); } catch(IllegalAccessException e) { LOG.warn("{} is not accessible. Setting it to accessible." + " However this is a security hack and your code" + " should really adhere to JavaBeans standards.", setter.toString()); setter.setAccessible(true); setter.invoke(retValue, setterArg); } } else { LOG.warn("Couldn't find a suitable value for attribute {}[{}]" + ". It will be left to null.", pojoClass, attributeType); } } return retValue; } private Object manufactureParameterValue(Map<Class<?>, Integer> pojos, Class<?> parameterType, Type genericType, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { String attributeName = null; return manufactureAttributeValue(Object.class, pojos, parameterType, genericType, annotations, attributeName, typeArgsMap, genericTypeArgs); } private Object manufactureAttributeValue(Object pojo, Map<Class<?>, Integer> pojos, Class<?> attributeType, Type genericAttributeType, List<Annotation> annotations, String attributeName, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object attributeValue = null; Class<?> realAttributeType; if (Object.class.equals(attributeType) && attributeType != genericAttributeType) { AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); realAttributeType = resolveGenericParameter(genericAttributeType, typeArgsMap, elementGenericTypeArgs); } else { realAttributeType = attributeType; } AttributeMetadata attributeMetadata = new AttributeMetadata( attributeName, realAttributeType, annotations, pojo.getClass()); // Primitive type if (realAttributeType.isPrimitive()) { attributeValue = resolvePrimitiveValue(realAttributeType, annotations, attributeMetadata); // Wrapper type } else if (isWrapper(realAttributeType)) { attributeValue = resolveWrapperValue(realAttributeType, annotations, attributeMetadata); // String type } else if (realAttributeType.equals(String.class)) { attributeValue = resolveStringValue(annotations, attributeMetadata); } else if (realAttributeType.isArray()) { // Array type attributeValue = resolveArrayElementValue(realAttributeType, genericAttributeType, pojos, annotations, pojo, attributeName, typeArgsMap); // Otherwise it's a different type of Object (including // the Object class) } else if (Collection.class.isAssignableFrom(realAttributeType)) { attributeValue = resolveCollectionValueWhenCollectionIsPojoAttribute( pojo, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } else if (Map.class.isAssignableFrom(realAttributeType)) { attributeValue = resolveMapValueWhenMapIsPojoAttribute(pojo, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } else if (realAttributeType.isEnum()) { // Enum type int enumConstantsLength = realAttributeType.getEnumConstants().length; if (enumConstantsLength > 0) { int enumIndex = strategy.getIntegerInRange(0, enumConstantsLength, attributeMetadata) % enumConstantsLength; attributeValue = realAttributeType.getEnumConstants()[enumIndex]; } } else if (Type.class.isAssignableFrom(realAttributeType)) { Type paremeterType = null; if (genericAttributeType instanceof ParameterizedType) { ParameterizedType parametrized = (ParameterizedType) genericAttributeType; Type[] arguments = parametrized.getActualTypeArguments(); if (arguments.length > 0) { paremeterType = arguments[0]; } } else if (realAttributeType.getTypeParameters().length > 0) { paremeterType = realAttributeType.getTypeParameters()[0]; } if (paremeterType != null) { AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); attributeValue = resolveGenericParameter(paremeterType, typeArgsMap, elementGenericTypeArgs); } else { LOG.error("{} is missing generic type argument, supplied {} {}", genericAttributeType, typeArgsMap, Arrays.toString(genericTypeArgs)); } } // For any other type, we use the PODAM strategy if (attributeValue == null) { TypeVariable<?>[] typeParams = attributeType.getTypeParameters(); Type[] genericTypeArgsAll = mergeActualAndSuppliedGenericTypes( typeParams, genericTypeArgs, typeArgsMap); Integer depth = pojos.get(realAttributeType); if (depth == null) { depth = -1; } if (depth <= strategy.getMaxDepth(pojo.getClass())) { pojos.put(realAttributeType, depth + 1); attributeValue = this.manufacturePojoInternal( realAttributeType, pojos, genericTypeArgsAll); pojos.put(realAttributeType, depth); } else { LOG.warn("Loop in {} production detected.", realAttributeType); attributeValue = externalFactory.manufacturePojo( realAttributeType, genericTypeArgsAll); } } return attributeValue; } /** * Utility to merge actual types with supplied array of generic type * substitutions * * @param actualTypes * an array of types used for field or POJO declaration * @param suppliedTypes * an array of supplied types for generic type substitution * @param typeArgsMap * a map relating the generic class arguments ("<T, V>" for * example) with their actual types * @return An array of merged actual and supplied types with generic types * resolved */ private Type[] mergeActualAndSuppliedGenericTypes( TypeVariable<?>[] actualTypes, Type[] suppliedTypes, Map<String, Type> typeArgsMap) { List<Type> resolvedTypes = new ArrayList<Type>(); List<Type> substitutionTypes = new ArrayList<Type>(Arrays.asList(suppliedTypes)); for (int i = 0; i < actualTypes.length; i++) { Type type = typeArgsMap.get(actualTypes[i].getName()); if (type != null) { resolvedTypes.add(type); if (!substitutionTypes.isEmpty() && substitutionTypes.get(0).equals(type)) { substitutionTypes.remove(0); } } } Type[] resolved = resolvedTypes.toArray(new Type[resolvedTypes.size()]); Type[] supplied = substitutionTypes.toArray(new Type[substitutionTypes.size()]); return mergeTypeArrays(resolved, supplied); } private String resolveStringValue(List<Annotation> annotations, AttributeMetadata attributeMetadata) throws InstantiationException, IllegalAccessException { String retValue = null; if (annotations == null || annotations.isEmpty()) { retValue = strategy.getStringValue(attributeMetadata); } else { for (Annotation annotation : annotations) { if (!PodamStringValue.class.isAssignableFrom(annotation .getClass())) { continue; } // A specific value takes precedence over the length PodamStringValue podamAnnotation = (PodamStringValue) annotation; if (podamAnnotation.strValue() != null && podamAnnotation.strValue().length() > 0) { retValue = podamAnnotation.strValue(); } else { retValue = strategy.getStringOfLength( podamAnnotation.length(), attributeMetadata); } } if (retValue == null) { retValue = strategy.getStringValue(attributeMetadata); } } return retValue; } /** * It returns an default value for a {@link Field} matching the attribute * name or null if a field was not found. * * @param pojoClass * The class supposed to contain the field * @param attributeName * The field name * * @return an instance of {@link Field} matching the attribute name or * null if a field was not found. */ private <T> T getDefaultFieldValue(Object pojo, String attributeName) { T retValue = null; try { Field field = getField(pojo.getClass(), attributeName); if (field != null) { // It allows to invoke Field.get on private fields field.setAccessible(true); @SuppressWarnings(UNCHECKED_STR) T t = (T) field.get(pojo); retValue = t; } else { LOG.info("The field {}[{}] didn't exist.", pojo.getClass(), attributeName); } } catch (Exception e) { LOG.warn("We couldn't get default value for {}[{}]", pojo.getClass(), attributeName, e); } return retValue; } /** * It returns a {@link Field} matching the attribute name or null if a field * was not found. * * @param pojoClass * The class supposed to contain the field * @param attributeName * The field name * * @return a {@link Field} matching the attribute name or null if a field * was not found. */ private Field getField(Class<?> pojoClass, String attributeName) { Field field = null; Class<?> clazz = pojoClass; while (clazz != null) { try { field = clazz.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } } if (field == null) { LOG.warn("A field could not be found for attribute '{}[{}]'", pojoClass, attributeName); } return field; } /** * It returns a {@link PodamStrategyValue} if one was specified, or * {@code null} otherwise. * * @param annotations * The list of annotations * @return {@code true} if the list of annotations contains at least one * {@link PodamStrategyValue} annotation. */ private PodamStrategyValue containsAttributeStrategyAnnotation( List<Annotation> annotations) { PodamStrategyValue retValue = null; for (Annotation annotation : annotations) { if (PodamStrategyValue.class .isAssignableFrom(annotation.getClass())) { retValue = (PodamStrategyValue) annotation; break; } } return retValue; } /** * It returns {@code true} if this class is a wrapper class, {@code false} * otherwise * * @param candidateWrapperClass * The class to check * @return {@code true} if this class is a wrapper class, {@code false} * otherwise */ private boolean isWrapper(Class<?> candidateWrapperClass) { return candidateWrapperClass.equals(Byte.class) ? true : candidateWrapperClass.equals(Boolean.class) ? true : candidateWrapperClass.equals(Character.class) ? true : candidateWrapperClass.equals(Short.class) ? true : candidateWrapperClass .equals(Integer.class) ? true : candidateWrapperClass .equals(Long.class) ? true : candidateWrapperClass .equals(Float.class) ? true : candidateWrapperClass .equals(Double.class) ? true : false; } /** * Given the original class and the setter method, it returns all * annotations for the field or an empty collection if no custom annotations * were found on the field * * @param clazz * The class containing the annotated attribute * @param setter * The setter method * @return all annotations for the field * @throws NoSuchFieldException * If the field could not be found * @throws SecurityException * if a security exception occurred */ private List<Annotation> retrieveFieldAnnotations(Class<?> clazz, Method setter) { List<Annotation> retValue = new ArrayList<Annotation>(); // Checks if the field has got any custom annotations String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); Field setterField = getField(clazz, attributeName); if (setterField != null) { Annotation[] annotations = setterField.getAnnotations(); if (annotations != null && annotations.length != 0) { retValue = Arrays.asList(annotations); } } return retValue; } private Collection<? super Object> resolveCollectionValueWhenCollectionIsPojoAttribute( Object pojo, Map<Class<?>, Integer> pojos, Class<?> collectionType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { // This needs to be generic because collections can be of any type Collection<? super Object> retValue = null; if (null != pojo && null != attributeName) { retValue = getDefaultFieldValue(pojo, attributeName); } retValue = resolveCollectionType(collectionType, retValue); if (null == retValue) { return null; } try { Class<?> typeClass = null; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("The collection attribute: " + attributeName + " does not have a type. We will assume Object for you"); // Support for non-generified collections typeClass = Object.class; } else { Type actualTypeArgument = genericTypeArgs[0]; typeClass = resolveGenericParameter(actualTypeArgument, typeArgsMap, elementGenericTypeArgs); } fillCollection(pojos, annotations, retValue, typeClass, elementGenericTypeArgs.get()); } catch (SecurityException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalArgumentException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InstantiationException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } return retValue; } private void fillCollection(Collection<? super Object> collection, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Class<?> collectionClass = collection.getClass(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, collectionClass, genericTypeArgs); Annotation[] annotations = collection.getClass().getAnnotations(); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); Type[] typeParams = collectionClass.getTypeParameters(); while (typeParams.length < 1) { Type type = collectionClass.getGenericSuperclass(); collectionClass = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); typeParams = elementGenericTypeArgs.get(); } Class<?> elementTypeClass = resolveGenericParameter(typeParams[0], typeArgsMap, elementGenericTypeArgs); Type[] elementGenericArgs = mergeTypeArrays(elementGenericTypeArgs.get(), genericTypeArgsExtra); fillCollection(pojos, Arrays.asList(annotations), collection, elementTypeClass, elementGenericArgs); } private void fillCollection(Map<Class<?>, Integer> pojos, List<Annotation> annotations, Collection<? super Object> collection, Class<?> collectionElementType, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements; if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); elementStrategy = collectionAnnotation.collectionElementStrategy() .newInstance(); } else { nbrElements = strategy .getNumberOfCollectionElements(collectionElementType); } try { if (collection.size() > nbrElements) { collection.clear(); } for (int i = collection.size(); i < nbrElements; i++) { // The default Object element; if (null != elementStrategy && ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass()) && Object.class.equals(collectionElementType)) { LOG.debug("Element strategy is ObjectStrategy and collection element is of type Object: using the ObjectStrategy strategy"); element = elementStrategy.getValue(); } else if (null != elementStrategy && !ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass())) { LOG.debug("Collection elements will be filled using the following strategy: " + elementStrategy); element = returnAttributeDataStrategyValue( collectionElementType, elementStrategy); } else { Map<String, Type> nullTypeArgsMap = new HashMap<String, Type>(); element = manufactureParameterValue(pojos, collectionElementType, collectionElementType, annotations, nullTypeArgsMap, genericTypeArgs); } collection.add(element); } } catch (UnsupportedOperationException e) { LOG.warn("Cannot fill immutable collection {}", collection.getClass()); } } private Map<? super Object, ? super Object> resolveMapValueWhenMapIsPojoAttribute( Object pojo, Map<Class<?>, Integer> pojos, Class<?> attributeType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { Map<? super Object, ? super Object> retValue = null; if (null != pojo && null != attributeName) { retValue = getDefaultFieldValue(pojo, attributeName); } retValue = resolveMapType(attributeType, retValue); if (null == retValue) { return null; } try { Class<?> keyClass = null; Class<?> elementClass = null; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("Map attribute: " + attributeName + " is non-generic. We will assume a Map<Object, Object> for you."); keyClass = Object.class; elementClass = Object.class; } else { // Expected only key, value type if (genericTypeArgs.length != 2) { throw new IllegalStateException( "In a Map only key value generic type are expected."); } Type[] actualTypeArguments = genericTypeArgs; keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter(actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } MapArguments mapArguments = new MapArguments(); mapArguments.setPojos(pojos); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(retValue); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments .setElementGenericTypeArgs(elementGenericTypeArgs.get()); fillMap(mapArguments); } catch (InstantiationException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (SecurityException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } return retValue; } private void fillMap(Map<? super Object, ? super Object> map, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Class<?> pojoClass = map.getClass(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); Class<?> mapClass = pojoClass; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); Type[] typeParams = mapClass.getTypeParameters(); while (typeParams.length < 2) { Type type = mapClass.getGenericSuperclass(); mapClass = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); typeParams = elementGenericTypeArgs.get(); } AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); Class<?> keyClass = resolveGenericParameter(typeParams[0], typeArgsMap, keyGenericTypeArgs); Class<?> elementClass = resolveGenericParameter(typeParams[1], typeArgsMap, elementGenericTypeArgs); Type[] keyGenericArgs = mergeTypeArrays(keyGenericTypeArgs.get(), genericTypeArgsExtra); Type[] elementGenericArgs = mergeTypeArrays(elementGenericTypeArgs.get(), genericTypeArgsExtra); MapArguments mapArguments = new MapArguments(); mapArguments.setPojos(pojos); mapArguments.setAnnotations(Arrays.asList(pojoClass.getAnnotations())); mapArguments.setMapToBeFilled(map); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericArgs); mapArguments.setElementGenericTypeArgs(elementGenericArgs); fillMap(mapArguments); } private void fillMap(MapArguments mapArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> keyStrategy = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : mapArguments.getAnnotations()) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements; if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); keyStrategy = collectionAnnotation.mapKeyStrategy().newInstance(); elementStrategy = collectionAnnotation.mapElementStrategy() .newInstance(); } else { nbrElements = strategy.getNumberOfCollectionElements(mapArguments .getElementClass()); } Map<? super Object, ? super Object> map = mapArguments.getMapToBeFilled(); try { if (map.size() > nbrElements) { map.clear(); } for (int i = map.size(); i < nbrElements; i++) { Object keyValue = null; Object elementValue = null; @SuppressWarnings(UNCHECKED_STR) Class<? extends Map<?, ?>> mapType = (Class<? extends Map<?, ?>>) mapArguments.getMapToBeFilled().getClass(); MapKeyOrElementsArguments valueArguments = new MapKeyOrElementsArguments(); valueArguments.setPojoClass(mapType); valueArguments.setPojos(mapArguments.getPojos()); valueArguments.setAnnotations(mapArguments.getAnnotations()); valueArguments.setKeyOrValueType(mapArguments.getKeyClass()); valueArguments.setElementStrategy(keyStrategy); valueArguments.setGenericTypeArgs(mapArguments .getKeyGenericTypeArgs()); keyValue = getMapKeyOrElementValue(valueArguments); valueArguments = new MapKeyOrElementsArguments(); valueArguments.setPojoClass(mapType); valueArguments.setPojos(mapArguments.getPojos()); valueArguments.setAnnotations(mapArguments.getAnnotations()); valueArguments.setKeyOrValueType(mapArguments.getElementClass()); valueArguments.setElementStrategy(elementStrategy); valueArguments.setGenericTypeArgs(mapArguments .getElementGenericTypeArgs()); elementValue = getMapKeyOrElementValue(valueArguments); /* ConcurrentHashMap doesn't allow null values */ if (elementValue != null || !(map instanceof ConcurrentHashMap)) { map.put(keyValue, elementValue); } } } catch (UnsupportedOperationException e) { LOG.warn("Cannot fill immutable map {}", map.getClass()); } } private Object getMapKeyOrElementValue( MapKeyOrElementsArguments keyOrElementsArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; if (null != keyOrElementsArguments.getElementStrategy() && ObjectStrategy.class.isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass()) && Object.class.equals(keyOrElementsArguments .getKeyOrValueType())) { LOG.debug("Element strategy is ObjectStrategy and Map key or value type is of type Object: using the ObjectStrategy strategy"); retValue = keyOrElementsArguments.getElementStrategy().getValue(); } else if (null != keyOrElementsArguments.getElementStrategy() && !ObjectStrategy.class .isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass())) { LOG.debug("Map key or value will be filled using the following strategy: " + keyOrElementsArguments.getElementStrategy()); retValue = returnAttributeDataStrategyValue( keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getElementStrategy()); } else { Map<String, Type> nullTypeArgsMap = new HashMap<String, Type>(); retValue = manufactureParameterValue( keyOrElementsArguments.getPojos(), keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getAnnotations(), nullTypeArgsMap, keyOrElementsArguments.getGenericTypeArgs()); } return retValue; } private Object resolveArrayElementValue(Class<?> attributeType, Type genericType, Map<Class<?>, Integer> pojos, List<Annotation> annotations, Object pojo, String attributeName, Map<String, Type> typeArgsMap) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> componentType = null; AtomicReference<Type[]> genericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericType instanceof GenericArrayType) { Type genericComponentType = ((GenericArrayType) genericType).getGenericComponentType(); if (genericComponentType instanceof TypeVariable) { TypeVariable<?> componentTypeVariable = (TypeVariable<?>) genericComponentType; final Type resolvedType = typeArgsMap.get(componentTypeVariable.getName()); componentType = resolveGenericParameter(resolvedType, typeArgsMap, genericTypeArgs); } } if (componentType == null) { componentType = attributeType.getComponentType(); } // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements; if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); elementStrategy = collectionAnnotation.collectionElementStrategy() .newInstance(); } else { nbrElements = strategy.getNumberOfCollectionElements(attributeType); } Object arrayElement = null; Object array = Array.newInstance(componentType, nbrElements); for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && ObjectStrategy.class .isAssignableFrom(collectionAnnotation .collectionElementStrategy()) && Object.class.equals(componentType)) { LOG.debug("Element strategy is ObjectStrategy and array element is of type Object: using the ObjectStrategy strategy"); arrayElement = elementStrategy.getValue(); } else if (null != elementStrategy && !ObjectStrategy.class .isAssignableFrom(collectionAnnotation .collectionElementStrategy())) { LOG.debug("Array elements will be filled using the following strategy: " + elementStrategy); arrayElement = returnAttributeDataStrategyValue(componentType, elementStrategy); } else { arrayElement = manufactureAttributeValue(pojo, pojos, componentType, genericType, annotations, attributeName, typeArgsMap, genericTypeArgs.get()); } Array.set(array, i, arrayElement); } return array; } /** * Given a collection type it returns an instance * <p> * <ul> * <li>The default type for a {@link List} is an {@link ArrayList}</li> * <li>The default type for a {@link Queue} is a {@link LinkedList}</li> * <li>The default type for a {@link Set} is a {@link HashSet}</li> * </ul> * * </p> * * @param collectionType * The collection type * * @param defaultValue * Default value for the collection, can be null * @return an instance of the collection type or null */ private Collection<? super Object> resolveCollectionType( Class<?> collectionType, Collection<? super Object> defaultValue) { Collection<? super Object> retValue = null; // Default list and set are ArrayList and HashSet. If users // wants a particular collection flavour they have to initialise // the collection if (null != defaultValue && (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) { /* Default collection, which is not immutable */ retValue = defaultValue; } else { if (Queue.class.isAssignableFrom(collectionType)) { if (collectionType.isAssignableFrom(LinkedList.class)) { retValue = new LinkedList<Object>(); } } else if (Set.class.isAssignableFrom(collectionType)) { if (collectionType.isAssignableFrom(HashSet.class)) { retValue = new HashSet<Object>(); } } else { if (collectionType.isAssignableFrom(ArrayList.class)) { retValue = new ArrayList<Object>(); } } if (null != retValue && null != defaultValue) { retValue.addAll(defaultValue); } } return retValue; } /** * It manufactures and returns a default instance for each map type * * <p> * The default implementation for a {@link ConcurrentMap} is * {@link ConcurrentHashMap} * </p> * * <p> * The default implementation for a {@link SortedMap} is a {@link TreeMap} * </p> * * <p> * The default Map is none of the above was recognised is a {@link HashMap} * </p> * * @param mapType * The attribute type implementing Map * @param defaultValue * Default value for map * @return A default instance for each map type or null * */ private Map<? super Object, ? super Object> resolveMapType( Class<?> mapType, Map<? super Object, ? super Object> defaultValue) { Map<? super Object, ? super Object> retValue = null; if (null != defaultValue && (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) { /* Default map, which is not immutable */ retValue = defaultValue; } else { if (SortedMap.class.isAssignableFrom(mapType)) { if (mapType.isAssignableFrom(TreeMap.class)) { retValue = new TreeMap<Object, Object>(); } } else if (ConcurrentMap.class.isAssignableFrom(mapType)) { if (mapType.isAssignableFrom(ConcurrentHashMap.class)) { retValue = new ConcurrentHashMap<Object, Object>(); } } else { if (mapType.isAssignableFrom(HashMap.class)) { retValue = new HashMap<Object, Object>(); } } } return retValue; } private Object[] getParameterValuesForConstructor( Constructor<?> constructor, Class<?> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); final Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); Annotation[][] parameterAnnotations = constructor .getParameterAnnotations(); Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] parameterValues = new Object[parameterTypes.length]; int idx = 0; for (Class<?> parameterType : parameterTypes) { List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); Type genericType = constructor.getGenericParameterTypes()[idx]; parameterValues[idx] = manufactureParameterValue(parameterType, genericType, annotations, typeArgsMap, pojos, genericTypeArgsExtra == null ? NO_TYPES : genericTypeArgsExtra); idx++; } return parameterValues; } private Object manufactureParameterValue(Class<?> parameterType, Type genericType, List<Annotation> annotations, final Map<String, Type> typeArgsMap, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object parameterValue = null; if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> defaultValue = null; Collection<? super Object> collection = resolveCollectionType( parameterType, defaultValue); if (collection != null) { Class<?> collectionElementType; AtomicReference<Type[]> collectionGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) genericType; Type actualTypeArgument = pType.getActualTypeArguments()[0]; collectionElementType = resolveGenericParameter( actualTypeArgument, typeArgsMap, collectionGenericTypeArgs); } else { LOG.warn("Collection parameter {} type is non-generic." + "We will assume a Collection<Object> for you.", genericType); collectionElementType = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( collectionGenericTypeArgs.get(), genericTypeArgs); fillCollection(pojos, annotations, collection, collectionElementType, genericTypeArgsAll); parameterValue = collection; } } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> defaultValue = null; Map<? super Object, ? super Object> map = resolveMapType(parameterType, defaultValue); if (map != null) { Class<?> keyClass; Class<?> elementClass; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) genericType; Type[] actualTypeArguments = pType.getActualTypeArguments(); keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter( actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } else { LOG.warn("Map parameter {} type is non-generic." + "We will assume a Map<Object,Object> for you.", genericType); keyClass = Object.class; elementClass = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( elementGenericTypeArgs.get(), genericTypeArgs); MapArguments mapArguments = new MapArguments(); mapArguments.setPojos(pojos); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(map); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments.setElementGenericTypeArgs(genericTypeArgsAll); fillMap(mapArguments); parameterValue = map; } } if (parameterValue == null) { Map<String, Type> typeArgsMapForParam; if (genericType instanceof ParameterizedType) { typeArgsMapForParam = new HashMap<String, Type>(typeArgsMap); ParameterizedType parametrizedType = (ParameterizedType) genericType; TypeVariable<?>[] argumentTypes = parameterType.getTypeParameters(); Type[] argumentGenericTypes = parametrizedType.getActualTypeArguments(); for (int k = 0; k < argumentTypes.length; k++) { if (argumentGenericTypes[k] instanceof Class) { Class<?> genericParam = (Class<?>) argumentGenericTypes[k]; typeArgsMapForParam.put(argumentTypes[k].getName(), genericParam); } } } else { typeArgsMapForParam = typeArgsMap; } parameterValue = manufactureParameterValue(pojos, parameterType, genericType, annotations, typeArgsMapForParam, genericTypeArgs); } return parameterValue; } /** * Utility method to merge two arrays * * @param original * The main array * @param extra * The additional array, optionally may be null * @return A merged array of original and extra arrays */ private Type[] mergeTypeArrays(Type[] original, Type[] extra) { Type[] merged; if (extra != null) { merged = new Type[original.length + extra.length]; System.arraycopy(original, 0, merged, 0, original.length); System.arraycopy(extra, 0, merged, original.length, extra.length); } else { merged = original; } return merged; } private Object returnAttributeDataStrategyValue(Class<?> attributeType, AttributeStrategy<?> attributeStrategy) throws InstantiationException, IllegalAccessException { Object retValue = null; Method attributeStrategyMethod = null; try { attributeStrategyMethod = attributeStrategy.getClass().getMethod( PodamConstants.PODAM_ATTRIBUTE_STRATEGY_METHOD_NAME, new Class<?>[] {}); if (!attributeType.isAssignableFrom(attributeStrategyMethod .getReturnType())) { String errMsg = "The type of the Podam Attribute Strategy is not " + attributeType.getName() + " but " + attributeStrategyMethod.getReturnType().getName() + ". An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } retValue = attributeStrategy.getValue(); } catch (SecurityException e) { throw new IllegalStateException( "A security issue occurred while retrieving the Podam Attribute Strategy details", e); } catch (NoSuchMethodException e) { throw new IllegalStateException( "It seems the Podam Attribute Annotation is of the wrong type", e); } return retValue; } }
package wtf.pants.stamp.mapping; import lombok.Getter; import wtf.pants.stamp.mapping.exceptions.ClassMapNotFoundException; import wtf.pants.stamp.mapping.obj.ClassMap; import wtf.pants.stamp.mapping.obj.MethodObj; import java.util.*; /** * @author Spacks */ public class ClassCollector { @Getter private final List<ClassMap> classes; public ClassCollector() { this.classes = new ArrayList<>(); } /** * Adds a class to the collector * * @param classMap ClassMap instance */ public void addClass(ClassMap classMap) { this.classes.add(classMap); } /** * Looks for a ClassMap from all the mapped classes * * @param className Class name you're looking for * @return Returns ClassMap * @throws ClassMapNotFoundException Exception thrown if className was not found */ public ClassMap getClassMap(String className) throws ClassMapNotFoundException { final Optional<ClassMap> classMap = classes.stream().filter(c -> c.getClassName().equals(className)).findFirst(); if (classMap.isPresent()) { return classMap.get(); } else { throw new ClassMapNotFoundException(); } } /** * If it has one, this will get the class' parent class * * @param classMap Mapped class * @return Returns parent ClassMap * @throws ClassMapNotFoundException Throws ClassMapNotFoundException if the parent is not mapped */ public ClassMap getParent(ClassMap classMap) throws ClassMapNotFoundException { final String parentClassName = classMap.getParent(); Optional<ClassMap> optional = classes.stream() .filter(clazz -> parentClassName.equals(clazz.getClassName())) .findAny(); if (optional.isPresent()) return optional.get(); else throw new ClassMapNotFoundException(classMap.getParent()); } /** * Tries to get the class' overridden methods by comparing the child's methods to the parent's * * @param parentClass Parent class to compare to * @param childClass Child class to compare to * @return Returns a list of the overridden methods */ public Map<MethodObj, MethodObj> getOverriddenMethods(ClassMap parentClass, ClassMap childClass) { final Map<MethodObj, MethodObj> methods = new HashMap<>(); parentClass.getMethods().stream() .filter(MethodObj::isSafeMethod) .forEach(parentMethod -> { for (MethodObj childMethod : childClass.getMethods()) { if (childMethod.isSafeMethod() && childMethod.getMethod().equals(parentMethod.getMethod())) { methods.put(parentMethod, childMethod); break; } } }); return methods; } }
package net.maizegenetics.pal.distance; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.util.BitSet; import net.maizegenetics.util.BitUtil; import net.maizegenetics.util.ProgressListener; /** * This class calculates an identity by state matrix. It is scaled so only * non-missing comparison are used. It conducts bit level calculations of IBS for genotypes. * Only the two most common alleles are used in the distance calculations. * <p> * Please note that when heterozygous genotypes are used, Het to Het distance is 0.5 NOT 0.0. The default * along the identity diagonal is 0 (isTrueIBS = false), but changing isTrueIBS = true will calculate * the identity. * <p> * The distance estimates become wildly inaccuate when two few sites are used to calculate * distance. The minSiteComp parameter can be used to control the minimum number of sites * used for a calculation. If there are insufficient sites in the estimate, then Double.NaN * is returned. * * @author Ed Buckler * @version 1.0 */ public class IBSDistanceMatrix extends DistanceMatrix { private ProgressListener myListener = null; private int numSeqs; private Alignment theTBA = null; /** * Holds the average numbers of sites in the comparisons */ private double avgTotalSites; private int minSitesComp = 0; private boolean isTrueIBS = false; /** * Compute observed distances for all taxa. Missing sites are ignored. * * @param theAlignment Alignment used to computed distances */ public IBSDistanceMatrix(Alignment theAlignment) { this(theAlignment, 0, null); } /** * Compute observed distances for all taxa. Missing sites are ignored. * * @param theAlignment Alignment used to computed distances * @param listener Listener to track progress in calculations */ public IBSDistanceMatrix(Alignment theAlignment, ProgressListener listener) { this(theAlignment, 0, listener); } /** * Compute observed distances for all taxa. Missing sites are ignored. * * @param theAlignment Alignment used to computed distances * @param minSiteComp Minimum number of sites needed to estimate distance * @param listener Listener to track progress in calculations */ public IBSDistanceMatrix(Alignment theAlignment, int minSiteComp, ProgressListener listener) { this(theAlignment, minSiteComp, false, listener); } /** * Compute observed distances for all taxa. Missing sites are ignored. * * @param theAlignment Alignment used to computed distances * @param minSiteComp Minimum number of sites needed to estimate distance * @param trueIBS estimate diagonal distance based IBS (default = false, i=i=0.0) * @param listener Listener to track progress in calculations */ public IBSDistanceMatrix(Alignment theAlignment, int minSiteComp, boolean trueIBS, ProgressListener listener) { super(); this.minSitesComp = minSiteComp; isTrueIBS = trueIBS; myListener = listener; numSeqs = theAlignment.getSequenceCount(); theTBA = theAlignment; // this should have an option to only use the 2 or 3 most common alleles setIdGroup(theAlignment.getTaxaList()); computeHetBitDistances(); } /** * This is a cleanest, fastest and most accurate way to calculate distance. */ private void computeHetBitDistances() { avgTotalSites = 0; int count = 0; double[][] distance = new double[numSeqs][numSeqs]; for (int i = 0; i < numSeqs; i++) { long[] iMj = theTBA.getAllelePresenceForAllSites(i, 0).getBits(); long[] iMn = theTBA.getAllelePresenceForAllSites(i, 1).getBits(); for (int j = i; j < numSeqs; j++) { if (j == i && !isTrueIBS) { distance[i][i] = 0; } else { long[] jMj = theTBA.getAllelePresenceForAllSites(j, 0).getBits(); long[] jMn = theTBA.getAllelePresenceForAllSites(j, 1).getBits(); double[] result=computeHetBitDistances(iMj, iMn, jMj, jMn, minSitesComp); distance[i][j] = distance[j][i] = result[0]; avgTotalSites += result[1]; //this assumes not hets count++; } } fireProgress((int) (((double) (i + 1) / (double) numSeqs) * 100.0)); } setDistances(distance); avgTotalSites /= (double) count; } /** * Compute distance for a pair of taxa. * @param theTBA input alignment * @param taxon1 index of taxon 1 * @param taxon2 index of taxon 2 * @return array of {distance, number of sites used in comparison} */ public static double[] computeHetBitDistances(Alignment theTBA, int taxon1, int taxon2) { return computeHetBitDistances(theTBA, taxon1, taxon2, 0, false); } /** * Compute distance for a pair of taxa. * @param theTBA input alignment * @param taxon1 index of taxon 1 * @param taxon2 index of taxon 2 * @param minSitesCompared Minimum number of sites needed to estimate distance * @param isTrueIBS estimate diagonal distance based IBS (default = false, i=i=0.0) * * @return array of {distance, number of sites used in comparison} */ public static double[] computeHetBitDistances(Alignment theTBA, int taxon1, int taxon2, int minSitesCompared, boolean isTrueIBS) { // if(theTBA.isTBitFriendly()==false) theTBA = AlignmentUtils.optimizeForTaxa(theTBA); long[] iMj = theTBA.getAllelePresenceForAllSites(taxon1, 0).getBits(); long[] iMn = theTBA.getAllelePresenceForAllSites(taxon1, 1).getBits(); long[] jMj = theTBA.getAllelePresenceForAllSites(taxon2, 0).getBits(); long[] jMn = theTBA.getAllelePresenceForAllSites(taxon2, 1).getBits(); return computeHetBitDistances(iMj, iMn, jMj, jMn, minSitesCompared, 0, iMj.length-1); } /** * Compute distance for a pair of taxa. Optimized for calculations sites within a certain * range of underlying word (64 sites chunks) in the TBit array * @param theTBA input alignment * @param taxon1 index of taxon 1 * @param taxon2 index of taxon 2 * @param minSitesCompared Minimum number of sites needed to estimate distance * @param startWord starting word for calculating distance site=(startWord*64) * @param endWord ending word for calculating distance inclusive site=(endWord*64+63) * @param maskBadSet Optional mask for sites (those set to 1 are kept) * * @return array of {distance, number of sites used in comparison} */ public static double[] computeHetBitDistances(Alignment theTBA, int taxon1, int taxon2, int minSitesCompared, int startWord, int endWord, BitSet maskBadSet) { // if(theTBA.isTBitFriendly()==false) theTBA = AlignmentUtils.optimizeForTaxa(theTBA); long[] iMj = theTBA.getAllelePresenceForAllSites(taxon1, 0).getBits(); long[] iMn = theTBA.getAllelePresenceForAllSites(taxon1, 1).getBits(); if(maskBadSet!=null) { long[] maskBad=maskBadSet.getBits(); for (int i = 0; i < iMj.length; i++) {iMj[i]=iMj[i]& maskBad[i];} for (int i = 0; i < iMn.length; i++) {iMn[i]=iMn[i]& maskBad[i];} } long[] jMj = theTBA.getAllelePresenceForAllSites(taxon2, 0).getBits(); long[] jMn = theTBA.getAllelePresenceForAllSites(taxon2, 1).getBits(); return computeHetBitDistances(iMj, iMn, jMj, jMn, minSitesCompared, 0, iMj.length-1); } /** * Calculation of distance using the bit vector of major and minor alleles. * @param iMj Vector of major alleles for taxon i * @param iMn Vector of minor alleles for taxon i * @param jMj Vector of major alleles for taxon j * @param jMn Vector of minor alleles for taxon j * @param minSitesCompared Minimum number of sites needed to estimate distance * @return array of {distance, number of sites used in comparison} */ public static double[] computeHetBitDistances(long[] iMj, long[] iMn, long[] jMj, long[] jMn, int minSitesCompared) { return computeHetBitDistances(iMj, iMn, jMj, jMn, minSitesCompared, 0, iMj.length-1); } /** * Calculation of distance using the bit vector of major and minor alleles. * @param iMj Vector of major alleles for taxon i * @param iMn Vector of minor alleles for taxon i * @param jMj Vector of major alleles for taxon j * @param jMn Vector of minor alleles for taxon j * @param minSitesCompared Minimum number of sites needed to estimate distance * @param endWord ending word for calculating distance inclusive site=(endWord*64+63) * @return array of {distance, number of sites used in comparison} */ public static double[] computeHetBitDistances(long[] iMj, long[] iMn, long[] jMj, long[] jMn, int minSitesCompared, int startWord, int endWord) { int sameCnt = 0, diffCnt = 0, hetCnt = 0; for (int x = startWord; x <= endWord; x++) { long same = (iMj[x] & jMj[x]) | (iMn[x] & jMn[x]); long diff = (iMj[x] & jMn[x]) | (iMn[x] & jMj[x]); long hets = same & diff; sameCnt += BitUtil.pop(same); diffCnt += BitUtil.pop(diff); hetCnt += BitUtil.pop(hets); } int sites = sameCnt + diffCnt - hetCnt; double identity = ((double) (sameCnt) - (double)(0.5*hetCnt)) / (double) (sites); double dist = 1 - identity; if (sites > minSitesCompared) { return new double[] {dist,(double)sites}; } else { return new double[] {Double.NaN,(double)sites}; } } /* * Average number of sites used in calculating the distance matrix */ public double getAverageTotalSites() { return avgTotalSites; } public String toString(int d) { double[][] distance = this.getDistances(); /*Return a string representation of this matrix with 'd' displayed digits*/ String newln = System.getProperty("line.separator"); String outPut = new String(); String num = new String(); int i, j; java.text.NumberFormat nf = new java.text.DecimalFormat(); nf.setMaximumFractionDigits(5); for (i = 0; i < distance.length; i++) { for (j = 0; j < distance[i].length; j++) { //Numeric x = new Numeric(distance[i][j]); num = nf.format(d); //num = x.toString(d); //ed change that screws up formatting //num=""+this.element[i][j]; outPut = outPut + num + (char) 9; } outPut = outPut + newln; } return outPut; } @Override public String toString() { return this.toString(6); } protected void fireProgress(int percent) { if (myListener != null) { myListener.progress(percent, null); } } /* * Returns whether true IBS is calculated for the diagonal */ public boolean isTrueIBS() { return isTrueIBS; } }
package net.sf.jaer.eventprocessing.filter; import net.sf.jaer.chip.*; import net.sf.jaer.event.*; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import java.util.Observable; import java.util.Observer; import java.util.Arrays; import java.util.Random; @Description("Filters out uncorrelated background activity") @DevelopmentStatus(DevelopmentStatus.Status.Stable) public class AerCorrFilter extends EventFilter2D implements Observer { final int MAX_Ileak = 1000000, MIN_Ileak = 1; final int DEFAULT_TIMESTAMP = Integer.MIN_VALUE; private int iLeak = getInt("iLeak", 100); private int subsampleBy = getInt("subsampleBy", 0); private float[][] vCap; // private float Vth = 0.6; int[][] lastTimesMap; private float[][] cap; private float[][] vRs; private float[][] iLeakRealpA; private int ts = 0; // used to reset filter private int sx; private int sy; private Random r; private float iLeakCOV = getFloat("iLeakCOV", 0.04f); public AerCorrFilter(AEChip chip) { super(chip); chip.addObserver(this); initFilter(); setPropertyTooltip("Ileak", "Set Leaking current for variable dT in picoamps"); setPropertyTooltip("subsampleBy", "Past events are spatially subsampled (address right shifted) by this many bits"); setPropertyTooltip("iLeakCOV", "The leak rates vary by this coefficient of variation (1-sigma) per correlation cell detector"); } @Override synchronized public EventPacket filterPacket(EventPacket in) { if (lastTimesMap == null) { allocateMaps(chip); } for (Object eIn : in) { if (eIn == null) { break; } BasicEvent e = (BasicEvent) eIn; if (e.isSpecial()) { continue; // skip IMU, etc } short x = (short) (e.x >>> subsampleBy), y = (short) (e.y >>> subsampleBy); ts = e.timestamp; int lastT = lastTimesMap[x][y]; int deltaT = (ts - lastT); if(deltaT<0) { // log.warning("negative deltaT"); // resetFilter(); continue; } float deltaV = ((iLeakRealpA[x][y] / cap[x][y]) * deltaT * 1e-6f); vCap[x][y] -= deltaV; ///&& lastT != DEFAULT_TIMESTAMP) if (!(vCap[x][y] > 0.6f && lastT != DEFAULT_TIMESTAMP)) { e.setFilteredOut(true); } else { //System.out.println(e.x+" "+e.y); } vCap[x][y] = vRs[x][y]; lastTimesMap[x][y] = ts; } return in; } @Override public synchronized final void resetFilter() { initFilter(); } @Override public void update(Observable o, Object arg) { if (arg != null && (arg == AEChip.EVENT_SIZEX || arg == AEChip.EVENT_SIZEY)) { resetFilter(); } } @Override public final void initFilter() { r = new Random(); allocateMaps(chip); sx = chip.getSizeX() - 1; sy = chip.getSizeY() - 1; } synchronized private void allocateMaps(AEChip chip) { if (chip != null && chip.getNumCells() > 0) { lastTimesMap = new int[chip.getSizeX()][chip.getSizeY()]; for (int[] arrayRow : lastTimesMap) { Arrays.fill(arrayRow, DEFAULT_TIMESTAMP); } vCap = new float[chip.getSizeX()][chip.getSizeY()]; cap = new float[chip.getSizeX()][chip.getSizeY()]; // Initialize two dimensional array, by first getting the rows and then setting their values. for (float[] arrayRow : cap) { for (int i = 0; i < arrayRow.length; i++) { arrayRow[i] = 165e-15f * ((float) r.nextGaussian() * 0.03f + 1f); //arrayRow[i] = 165e-15; } } /* Vth = new float[chip.getSizeX()][chip.getSizeY()]; // Initialize two dimensional array, by first getting the rows and then setting their values. for (float[] arrayRow : Vth) { for (int i = 0; i < arrayRow.length; i++) { arrayRow[i] = 1.2; } }*/ vRs = new float[chip.getSizeX()][chip.getSizeY()]; // Initialize two dimensional array, by first getting the rows and then setting their values. for (float[] arrayRow : vRs) { for (int i = 0; i < arrayRow.length; i++) { arrayRow[i] = (float) (r.nextGaussian() * 0.005f + 1.197f); //arrayRow[i] = 1.2; } } iLeakRealpA = new float[chip.getSizeX()][chip.getSizeY()]; // Initialize two dimensional array, by first getting the rows and then setting their values. for (float[] arrayRow : iLeakRealpA) { for (int i = 0; i < arrayRow.length; i++) { //arrayRow[i] = (float)(getIleak())*1e-13; arrayRow[i] = (float) (iLeak * (r.nextGaussian() * iLeakCOV + 1f)) * 1e-12f;//should have different sigma and u for different iLeak values } } } } public Object getFilterState() { return lastTimesMap; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="getter-setter for --SubsampleBy--"> public int getSubsampleBy() { return subsampleBy; } /** * Sets the number of bits to subsample by when storing events into the map * of past events. Increasing this value will increase the number of events * that pass through and will also allow passing events from small sources * that do not stimulate every pixel. * * @param subsampleBy the number of bits, 0 means no subsampling, 1 means * cut event time map resolution by a factor of two in x and in y */ public void setSubsampleBy(int subsampleBy) { if (subsampleBy < 0) { subsampleBy = 0; } else if (subsampleBy > 4) { subsampleBy = 4; } this.subsampleBy = subsampleBy; putInt("subsampleBy", subsampleBy); } // </editor-fold> /** * @return the iLeak */ public int getIleak() { return (int) iLeak; } public int getMinIleak() { return (int) MIN_Ileak; } public int getMaxIleak() { return (int) MAX_Ileak; } /** * @param Ileak the iLeak to set */ public void setIleak(int Ileak) { this.iLeak = Ileak; putInt("iLeak", this.iLeak); allocateMaps(chip); } /** * @return the iLeakCOV */ public float getiLeakCOV() { return iLeakCOV; } /** * @param iLeakCOV the iLeakCOV to set */ public void setiLeakCOV(float iLeakCOV) { this.iLeakCOV = iLeakCOV; putFloat("iLeakCOV", iLeakCOV); allocateMaps(chip); } }
package net.sf.mzmine.methods.alignment.join; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.logging.Logger; import javax.swing.JMenuItem; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import net.sf.mzmine.data.AlignmentResult; import net.sf.mzmine.data.PeakList; import net.sf.mzmine.io.OpenedRawDataFile; import net.sf.mzmine.main.MZmineCore; import net.sf.mzmine.main.MZmineModule; import net.sf.mzmine.methods.Method; import net.sf.mzmine.methods.MethodParameters; import net.sf.mzmine.project.MZmineProject; import net.sf.mzmine.taskcontrol.Task; import net.sf.mzmine.taskcontrol.TaskController; import net.sf.mzmine.taskcontrol.TaskListener; import net.sf.mzmine.userinterface.Desktop; import net.sf.mzmine.userinterface.Desktop.MZmineMenu; public class JoinAligner implements Method, TaskListener, ListSelectionListener, ActionListener { private Logger logger = Logger.getLogger(this.getClass().getName()); private TaskController taskController; private Desktop desktop; private JMenuItem myMenuItem; public String toString() { return new String("Join Aligner"); } /** * @see net.sf.mzmine.methods.Method#askParameters() */ public MethodParameters askParameters() { MZmineProject currentProject = MZmineProject.getCurrentProject(); JoinAlignerParameters currentParameters = (JoinAlignerParameters) currentProject.getParameters(this); if (currentParameters == null) currentParameters = new JoinAlignerParameters(); JoinAlignerParameterSetupDialog jaPSD = new JoinAlignerParameterSetupDialog(desktop.getMainFrame(), new String("Please give parameter values"), currentParameters); jaPSD.setVisible(true); // Check if user pressed cancel if (jaPSD.getExitCode()==-1) { return null; } currentParameters = jaPSD.getParameters(); return currentParameters; } /** * @see net.sf.mzmine.methods.Method#runMethod(net.sf.mzmine.methods.MethodParameters, net.sf.mzmine.io.OpenedRawDataFile[], net.sf.mzmine.methods.alignment.AlignmentResult[]) */ public void runMethod(MethodParameters parameters, OpenedRawDataFile[] dataFiles, AlignmentResult[] alignmentResults) { logger.info("Running join aligner on " + dataFiles.length + " peak lists."); Task alignmentTask = new JoinAlignerTask(dataFiles, (JoinAlignerParameters) parameters); taskController.addTask(alignmentTask, this); } /** * @see net.sf.mzmine.main.MZmineModule#initModule(net.sf.mzmine.main.MZmineCore) */ public void initModule(MZmineCore core) { this.taskController = core.getTaskController(); this.desktop = core.getDesktop(); myMenuItem = desktop.addMenuItem(MZmineMenu.ALIGNMENT, "Peak list aligner", this, null, KeyEvent.VK_A, false, false); desktop.addSelectionListener(this); } /** * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { MethodParameters parameters = askParameters(); if (parameters == null) return; OpenedRawDataFile[] dataFiles = desktop.getSelectedDataFiles(); runMethod(parameters, dataFiles, null); } /** * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent) */ public void valueChanged(ListSelectionEvent e) { //myMenuItem.setEnabled(desktop.isDataFileSelected()); OpenedRawDataFile[] dataFiles = desktop.getSelectedDataFiles(); boolean allOk = true; for (OpenedRawDataFile file : dataFiles) { if (!file.getCurrentFile().hasData(PeakList.class)) { allOk = false; } } myMenuItem.setEnabled(allOk); } public void taskStarted(Task task) { // do nothing } public void taskFinished(Task task) { if (task.getStatus() == Task.TaskStatus.FINISHED) { Object[] results = (Object[]) task.getResult(); AlignmentResult alignmentResult = (AlignmentResult)results[0]; JoinAlignerParameters parameters = (JoinAlignerParameters)results[1]; MZmineProject.getCurrentProject().addAlignmentResult(alignmentResult); } else if (task.getStatus() == Task.TaskStatus.ERROR) { /* Task encountered an error */ String msg = "Error while aligning peak lists: " + task.getErrorMessage(); logger.severe(msg); desktop.displayErrorMessage(msg); } } }
package openblocks.common.tileentity.tank; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.liquids.ILiquidTank; import net.minecraftforge.liquids.ITankContainer; import net.minecraftforge.liquids.LiquidContainerRegistry; import net.minecraftforge.liquids.LiquidDictionary; import net.minecraftforge.liquids.LiquidStack; import net.minecraftforge.liquids.LiquidTank; import openblocks.OpenBlocks; import openblocks.sync.ISyncableObject; import openblocks.sync.SyncableDirection; import openblocks.sync.SyncableFlags; import openblocks.sync.SyncableInt; import openblocks.sync.SyncableShort; import openblocks.sync.SyncableTank; import openblocks.utils.BlockUtils; import openblocks.utils.ItemUtils; public class TileEntityTank extends TileEntityTankBase implements ITankContainer { /** * The tank holding the liquid */ private LiquidTank tank = new LiquidTank(LiquidContainerRegistry.BUCKET_VOLUME * OpenBlocks.Config.bucketsPerTank); /** * The Id of the liquid in the tank */ private SyncableInt liquidId = new SyncableInt(); /** * The meta of the liquid metadata in the tank */ private SyncableInt liquidMeta = new SyncableInt(); /** * The level of the liquid that is rendered on the client */ private SyncableShort liquidRenderAmount = new SyncableShort(); /** * Keys of things what get synced */ public enum Keys { liquidId, liquidMeta, renderLevel } public TileEntityTank() { syncMap.put(Keys.liquidId, liquidId); syncMap.put(Keys.liquidMeta, liquidMeta); syncMap.put(Keys.renderLevel, liquidRenderAmount); } public boolean containsValidLiquid() { return liquidId.getValue() != 0 && tank.getLiquidName() != null; } //TODO: if renderLevel < waterLevel + renderChangeAmount then renderLevel += renderChangeAmount elseif renderLevel > waterLevel - renderChangeAmount then renderLevel -= renderChangeAmount else renderLevel = waterLevel end public void updateEntity() { super.updateEntity(); if (!worldObj.isRemote) { HashSet<TileEntityTank> except = new HashSet<TileEntityTank>(); except.add(this); // if we have a liquid if (tank.getLiquid() != null) { // try to fill up the tank below with as much liquid as possible TileEntityTank below = getTankInDirection(ForgeDirection.DOWN); if (below != null) { if (below.getSpace() > 0) { LiquidStack myLiquid = tank.getLiquid().copy(); if (below.canReceiveLiquid(myLiquid)) { int toFill = Math.min(below.getSpace(), myLiquid.amount); myLiquid.amount = toFill; below.fill(myLiquid, true, except); tank.drain(toFill, true); } } } } // now fill up the horizontal tanks, start with the least full ArrayList<TileEntityTank> horizontals = getHorizontalTanksOrdererdBySpace(except); for (TileEntityTank horizontal : horizontals) { LiquidStack liquid = tank.getLiquid(); if (horizontal.canReceiveLiquid(liquid)) { int difference = getAmount() - horizontal.getAmount(); if (difference > 1) { int halfDifference = difference / 2; LiquidStack liquidCopy = liquid.copy(); liquidCopy.amount = Math.min(500, halfDifference); int filled = horizontal.fill(liquidCopy, true, except); tank.drain(filled, true); } } } syncMap.sync(worldObj, this, xCoord + 0.5, yCoord + 0.5, zCoord + 0.5); } } public boolean canReceiveLiquid(LiquidStack liquid) { if (!tank.containsValidLiquid()) { return true; } if (liquid == null) { return true; } LiquidStack otherLiquid = tank.getLiquid(); if (otherLiquid != null) { return otherLiquid.isLiquidEqual(liquid); } return true; } public LiquidTank getInternalTank() { return tank; } public int getSpace() { return tank.getCapacity() - tank.getLiquid().amount; } public int getAmount() { return tank.getLiquid().amount; } public int fill(LiquidStack resource, boolean doFill, HashSet<TileEntityTank> except) { TileEntityTank below = getTankInDirection(ForgeDirection.DOWN); int filled = 0; if (except == null ) { except = new HashSet<TileEntityTank>(); } int startAmount = resource.amount; if (except.contains(this)) { return 0; } except.add(this); // fill the tank below as much as possible if (below != null && below.getSpace() > 0) { filled = below.fill(resource, doFill, except); resource.amount -= filled; } // fill myself up if (resource.amount > 0){ filled = tank.fill(resource, doFill); resource.amount -= filled; } // ok we cant, so lets fill the tank above if (resource.amount > 0) { TileEntityTank above = getTankInDirection(ForgeDirection.UP); if (above != null) { filled = above.fill(resource, doFill, except); resource.amount -= filled; } } // finally, distribute any remaining to the sides if (resource.amount > 0 && canReceiveLiquid(resource)) { ArrayList<TileEntityTank> horizontals = getHorizontalTanksOrdererdBySpace(except); if (horizontals.size() > 0) { int amountPerSide = resource.amount / horizontals.size(); for (TileEntityTank sideTank : horizontals) { LiquidStack copy = resource.copy(); copy.amount = amountPerSide; filled = sideTank.fill(copy, doFill, except); resource.amount -= filled; } } } return startAmount - resource.amount; } /** * TODO */ public LiquidStack drain(int amount, boolean doDrain) { return tank.drain(amount, doDrain); } @Override public void onSynced(List<ISyncableObject> changes) { } @Override public void onBlockBroken() { //invalidate(); } @Override public void onBlockPlacedBy(EntityPlayer player, ForgeDirection side, ItemStack stack, float hitX, float hitY, float hitZ) { if (stack.hasTagCompound() && stack.getTagCompound().hasKey("tank")){ NBTTagCompound tankTag = stack.getTagCompound().getCompoundTag("tank"); tank.readFromNBT(tankTag); } } @Override public void writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); NBTTagCompound tankTag = new NBTTagCompound(); if(containsValidLiquid()){ tank.getLiquid().writeToNBT(tankTag); } tag.setTag("tank", tankTag); } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); if(tag.hasKey("tank")) { NBTTagCompound tankTag = tag.getCompoundTag("tank"); LiquidStack liquid = LiquidStack.loadLiquidStackFromNBT(tankTag); if(liquid != null) { tank.setLiquid(liquid); } } } @Override public int fill(ForgeDirection from, LiquidStack resource, boolean doFill) { int filled = fill(resource, doFill, null); if (doFill && filled > 0) { if (resource != null) { liquidId.setValue(resource.itemID); liquidMeta.setValue(resource.itemMeta); } } return filled; } @Override public int fill(int tankIndex, LiquidStack resource, boolean doFill) { return fill(ForgeDirection.UNKNOWN, resource, doFill); } @Override public LiquidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { return drain(maxDrain, doDrain); } @Override public LiquidStack drain(int tankIndex, int maxDrain, boolean doDrain) { return drain(maxDrain, doDrain); } @Override public ILiquidTank[] getTanks(ForgeDirection direction) { return new ILiquidTank[] { tank }; } @Override public ILiquidTank getTank(ForgeDirection direction, LiquidStack type) { return tank; } public int countDownwardsTanks() { int count = 1; TileEntityTank below = getTankInDirection(ForgeDirection.DOWN); if (below != null){ count += below.countDownwardsTanks(); } return count; } @Override public boolean onBlockActivated(EntityPlayer player, int side, float hitX, float hitY, float hitZ) { ForgeDirection direction = BlockUtils.sideToDirection(side); ItemStack current = player.inventory.getCurrentItem(); if (current != null) { LiquidStack liquid = LiquidContainerRegistry.getLiquidForFilledItem(current); // Handle filled containers if (liquid != null) { int qty = fill(direction, liquid, true); if (qty != 0 && !player.capabilities.isCreativeMode) { player.inventory.setInventorySlotContents(player.inventory.currentItem, ItemUtils.consumeItem(current)); } return true; } else { LiquidStack available = tank.getLiquid(); if (available != null) { ItemStack filled = LiquidContainerRegistry.fillLiquidContainer(available, current); liquid = LiquidContainerRegistry.getLiquidForFilledItem(filled); if (liquid != null) { if (!player.capabilities.isCreativeMode) { if (current.stackSize > 1) { if (!player.inventory.addItemStackToInventory(filled)) return false; else { player.inventory.setInventorySlotContents(player.inventory.currentItem, ItemUtils.consumeItem(current)); } } else { player.inventory.setInventorySlotContents(player.inventory.currentItem, ItemUtils.consumeItem(current)); player.inventory.setInventorySlotContents(player.inventory.currentItem, filled); } } drain(ForgeDirection.UNKNOWN, liquid.amount, true); return true; } } } } return false; } }
package org.apache.xerces.validators.common; import org.apache.xerces.framework.XMLAttrList; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.framework.XMLDocumentHandler; import org.apache.xerces.framework.XMLDocumentScanner; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.readers.DefaultEntityHandler; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.utils.ChunkyCharArray; import org.apache.xerces.utils.Hash2intTable; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.apache.xerces.utils.XMLMessages; import org.apache.xerces.utils.ImplementationMessages; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.EntityResolver; import org.xml.sax.Locator; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.validators.dtd.DTDGrammar; import org.apache.xerces.validators.schema.EquivClassComparator; import org.apache.xerces.validators.schema.SchemaGrammar; import org.apache.xerces.validators.schema.SchemaMessageProvider; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.TraverseSchema; import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.validators.datatype.StateMessageDatatype; import org.apache.xerces.validators.datatype.IDREFDatatypeValidator; import org.apache.xerces.validators.datatype.IDDatatypeValidator; import org.apache.xerces.validators.datatype.ENTITYDatatypeValidator; /** * This class is the super all-in-one validator used by the parser. * * @version $Id$ */ public final class XMLValidator implements DefaultEntityHandler.EventHandler, XMLEntityHandler.CharDataHandler, XMLDocumentScanner.EventHandler, NamespacesScope.NamespacesHandler { // Constants // debugging private static final boolean PRINT_EXCEPTION_STACK_TRACE = false; private static final boolean DEBUG_PRINT_ATTRIBUTES = false; private static final boolean DEBUG_PRINT_CONTENT = false; private static final boolean DEBUG_SCHEMA_VALIDATION = false; private static final boolean DEBUG_ELEMENT_CHILDREN = false; // Chunk size constants private static final int CHUNK_SHIFT = 8; // 2^8 = 256 private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT); private static final int CHUNK_MASK = CHUNK_SIZE - 1; private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k private Hashtable fIdDefs = null; private StateMessageDatatype fStoreIDRef = new StateMessageDatatype() { private Hashtable fIdDefs; public Object getDatatypeObject(){ return(Object) fIdDefs; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_STORE; } public void setDatatypeObject( Object data ){ fIdDefs = (Hashtable) data; } }; private StateMessageDatatype fResetIDRef = new StateMessageDatatype() { public Object getDatatypeObject(){ Hashtable t = null; return(Object) t; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_CLEAR; } public void setDatatypeObject( Object data ){ } }; private StateMessageDatatype fValidateIDRef = new StateMessageDatatype() { public Object getDatatypeObject(){ Hashtable t = null; return(Object) t; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_VALIDATE; } public void setDatatypeObject( Object data ){ } }; private StateMessageDatatype fValidateENTITYMsg = new StateMessageDatatype() { private Object packagedMessage = null; public Object getDatatypeObject(){ return packagedMessage; } public int getDatatypeState(){ return ENTITYDatatypeValidator.ENTITY_INITIALIZE;//No state } public void setDatatypeObject( Object data ){ packagedMessage = data;// Set Entity Handler } }; // Data // REVISIT: The data should be regrouped and re-organized so that // it's easier to find a meaningful field. // debugging // private static boolean DEBUG = false; // other // attribute validators private AttributeValidator fAttValidatorCDATA = null; //private AttributeValidator fAttValidatorENTITY = new AttValidatorENTITY(); //private AttributeValidator fAttValidatorENTITIES = new AttValidatorENTITIES(); private AttributeValidator fAttValidatorNMTOKEN = new AttValidatorNMTOKEN(); private AttributeValidator fAttValidatorNMTOKENS = new AttValidatorNMTOKENS(); private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION(); private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION(); private AttributeValidator fAttValidatorDATATYPE = null; // Package access for use by AttributeValidator classes. StringPool fStringPool = null; boolean fValidating = false; boolean fInElementContent = false; int fStandaloneReader = -1; // settings private boolean fValidationEnabled = false; private boolean fDynamicValidation = false; private boolean fSchemaValidation = true; private boolean fValidationEnabledByDynamic = false; private boolean fDynamicDisabledByValidation = false; private boolean fWarningOnDuplicateAttDef = false; private boolean fWarningOnUndeclaredElements = false; private boolean fLoadDTDGrammar = true; // declarations private int fDeclaration[]; private XMLErrorReporter fErrorReporter = null; private DefaultEntityHandler fEntityHandler = null; private QName fCurrentElement = new QName(); private ContentLeafNameTypeVector[] fContentLeafStack = new ContentLeafNameTypeVector[8]; private int[] fValidationFlagStack = new int[8]; private int[] fScopeStack = new int[8]; private int[] fGrammarNameSpaceIndexStack = new int[8]; private int[] fElementEntityStack = new int[8]; private int[] fElementIndexStack = new int[8]; private int[] fContentSpecTypeStack = new int[8]; private static final int sizeQNameParts = 8; private QName[] fElementQNamePartsStack = new QName[sizeQNameParts]; private QName[] fElementChildren = new QName[32]; private int fElementChildrenLength = 0; private int[] fElementChildrenOffsetStack = new int[32]; private int fElementDepth = -1; private boolean fNamespacesEnabled = false; private NamespacesScope fNamespacesScope = null; private int fNamespacesPrefix = -1; private QName fRootElement = new QName(); private int fAttrListHandle = -1; private int fCurrentElementEntity = -1; private int fCurrentElementIndex = -1; private int fCurrentContentSpecType = -1; private boolean fSeenDoctypeDecl = false; private final int TOP_LEVEL_SCOPE = -1; private int fCurrentScope = TOP_LEVEL_SCOPE; private int fCurrentSchemaURI = -1; private int fEmptyURI = - 1; private int fXsiPrefix = - 1; private int fXsiURI = -2; private int fXsiTypeAttValue = -1; private DatatypeValidator fXsiTypeValidator = null; private Grammar fGrammar = null; private int fGrammarNameSpaceIndex = -1; private GrammarResolver fGrammarResolver = null; // state and stuff private boolean fScanningDTD = false; private XMLDocumentScanner fDocumentScanner = null; private boolean fCalledStartDocument = false; private XMLDocumentHandler fDocumentHandler = null; private XMLDocumentHandler.DTDHandler fDTDHandler = null; private boolean fSeenRootElement = false; private XMLAttrList fAttrList = null; private int fXMLLang = -1; private LocatorImpl fAttrNameLocator = null; private boolean fCheckedForSchema = false; private boolean fDeclsAreExternal = false; private StringPool.CharArrayRange fCurrentElementCharArrayRange = null; private char[] fCharRefData = null; private boolean fSendCharDataAsCharArray = false; private boolean fBufferDatatype = false; private StringBuffer fDatatypeBuffer = new StringBuffer(); private QName fTempQName = new QName(); private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl(); private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl(); private XMLElementDecl fTempElementDecl = new XMLElementDecl(); private boolean fGrammarIsDTDGrammar = false; private boolean fGrammarIsSchemaGrammar = false; private boolean fNeedValidationOff = false; // symbols private int fEMPTYSymbol = -1; private int fANYSymbol = -1; private int fMIXEDSymbol = -1; private int fCHILDRENSymbol = -1; private int fCDATASymbol = -1; private int fIDSymbol = -1; private int fIDREFSymbol = -1; private int fIDREFSSymbol = -1; private int fENTITYSymbol = -1; private int fENTITIESSymbol = -1; private int fNMTOKENSymbol = -1; private int fNMTOKENSSymbol = -1; private int fNOTATIONSymbol = -1; private int fENUMERATIONSymbol = -1; private int fREQUIREDSymbol = -1; private int fFIXEDSymbol = -1; private int fDATATYPESymbol = -1; private int fEpsilonIndex = -1; //Datatype Registry private DatatypeValidatorFactoryImpl fDataTypeReg = DatatypeValidatorFactoryImpl.getDatatypeRegistry(); private DatatypeValidator fValID = this.fDataTypeReg.getDatatypeValidator("ID" ); private DatatypeValidator fValIDRef = this.fDataTypeReg.getDatatypeValidator("IDREF" ); private DatatypeValidator fValIDRefs = this.fDataTypeReg.getDatatypeValidator("IDREFS" ); private DatatypeValidator fValENTITY = this.fDataTypeReg.getDatatypeValidator("ENTITY" ); private DatatypeValidator fValENTITIES = this.fDataTypeReg.getDatatypeValidator("ENTITIES" ); // Constructors /** Constructs an XML validator. */ public XMLValidator(StringPool stringPool, XMLErrorReporter errorReporter, DefaultEntityHandler entityHandler, XMLDocumentScanner documentScanner) { // keep references fStringPool = stringPool; fErrorReporter = errorReporter; fEntityHandler = entityHandler; fDocumentScanner = documentScanner; fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); // initialize fAttrList = new XMLAttrList(fStringPool); entityHandler.setEventHandler(this); entityHandler.setCharDataHandler(this); fDocumentScanner.setEventHandler(this); for (int i = 0; i < sizeQNameParts; i++) { fElementQNamePartsStack[i] = new QName(); } init(); } // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner) public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; } // Public methods // initialization /** Set char data processing preference and handlers. */ public void initHandlers(boolean sendCharDataAsCharArray, XMLDocumentHandler docHandler, XMLDocumentHandler.DTDHandler dtdHandler) { fSendCharDataAsCharArray = sendCharDataAsCharArray; fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray); fDocumentHandler = docHandler; fDTDHandler = dtdHandler; } // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler) /** Reset or copy. */ public void resetOrCopy(StringPool stringPool) throws Exception { fAttrList = new XMLAttrList(stringPool); resetCommon(stringPool); } /** Reset. */ public void reset(StringPool stringPool) throws Exception { fAttrList.reset(stringPool); resetCommon(stringPool); } // settings /** * Turning on validation/dynamic turns on validation if it is off, and * this is remembered. Turning off validation DISABLES validation/dynamic * if it is on. Turning off validation/dynamic DOES NOT turn off * validation if it was explicitly turned on, only if it was turned on * BECAUSE OF the call to turn validation/dynamic on. Turning on * validation will REENABLE and turn validation/dynamic back on if it * was disabled by a call that turned off validation while * validation/dynamic was enabled. */ public void setValidationEnabled(boolean flag) throws Exception { fValidationEnabled = flag; fValidationEnabledByDynamic = false; if (fValidationEnabled) { if (fDynamicDisabledByValidation) { fDynamicValidation = true; fDynamicDisabledByValidation = false; } } else if (fDynamicValidation) { fDynamicValidation = false; fDynamicDisabledByValidation = true; } fValidating = fValidationEnabled; } /** Returns true if validation is enabled. */ public boolean getValidationEnabled() { return fValidationEnabled; } /** Sets whether Schema support is on/off. */ public void setSchemaValidationEnabled(boolean flag) { fSchemaValidation = flag; } /** Returns true if Schema support is on. */ public boolean getSchemaValidationEnabled() { return fSchemaValidation; } /** Sets whether validation is dynamic. */ public void setDynamicValidationEnabled(boolean flag) throws Exception { fDynamicValidation = flag; fDynamicDisabledByValidation = false; if (!fDynamicValidation) { if (fValidationEnabledByDynamic) { fValidationEnabled = false; fValidationEnabledByDynamic = false; } } else if (!fValidationEnabled) { fValidationEnabled = true; fValidationEnabledByDynamic = true; } fValidating = fValidationEnabled; } /** Returns true if validation is dynamic. */ public boolean getDynamicValidationEnabled() { return fDynamicValidation; } /** Sets fLoadDTDGrammar when validation is off **/ public void setLoadDTDGrammar(boolean loadDG){ if (fValidating) { fLoadDTDGrammar = true; } else{ fLoadDTDGrammar = loadDG; } } /** Returns fLoadDTDGrammar **/ public boolean getLoadDTDGrammar() { return fLoadDTDGrammar; } /** Sets whether namespaces are enabled. */ public void setNamespacesEnabled(boolean flag) { fNamespacesEnabled = flag; } /** Returns true if namespaces are enabled. */ public boolean getNamespacesEnabled() { return fNamespacesEnabled; } /** Sets whether duplicate attribute definitions signal a warning. */ public void setWarningOnDuplicateAttDef(boolean flag) { fWarningOnDuplicateAttDef = flag; } /** Returns true if duplicate attribute definitions signal a warning. */ public boolean getWarningOnDuplicateAttDef() { return fWarningOnDuplicateAttDef; } /** Sets whether undeclared elements signal a warning. */ public void setWarningOnUndeclaredElements(boolean flag) { fWarningOnUndeclaredElements = flag; } /** Returns true if undeclared elements signal a warning. */ public boolean getWarningOnUndeclaredElements() { return fWarningOnUndeclaredElements; } // DefaultEntityHandler.EventHandler methods /** Start entity reference. */ public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.startEntityReference(entityName, entityType, entityContext); } /** End entity reference. */ public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.endEntityReference(entityName, entityType, entityContext); } /** Send end of input notification. */ public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception { fDocumentScanner.endOfInput(entityName, moreToFollow); /** Send reader change notifications. */ /** External entity standalone check. */ /** Return true if validating. */ /** Process characters. */ /** Process characters. */ /** Process whitespace. */ /** Process whitespace. */ /** Scans element type. */ /** Scans expected element type. */ /** Scans attribute name. */ /** Call start document. */ /** Call end document. */ /** Call XML declaration. */ /** Call text declaration. */ /** * Signal the scanning of an element name in a start element tag. * * @param element Element name scanned. */ public void element(QName element) throws Exception { fAttrListHandle = -1; } /** * Signal the scanning of an attribute associated to the previous * start element tag. * * @param element Element name scanned. * @param attrName Attribute name scanned. * @param attrValue The string pool index of the attribute value. */ public boolean attribute(QName element, QName attrName, int attrValue) throws Exception { if (fAttrListHandle == -1) { fAttrListHandle = fAttrList.startAttrList(); } // if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element. // specified: true, search : true return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1; } /** Call start element. */ public void callStartElement(QName element) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart)); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) add default attrs (FIXED and NOT_FIXED) if (!fSeenRootElement) { fSeenRootElement = true; rootElementSpecified(element); fStringPool.resetShuffleCount(); } if (fGrammar != null && fGrammarIsDTDGrammar) { fAttrListHandle = addDTDDefaultAttributes(element, fAttrList, fAttrListHandle, fValidating, fStandaloneReader != -1); } fCheckedForSchema = true; if (fNamespacesEnabled) { bindNamespacesToElementAndAttributes(element, fAttrList); } validateElementAndAttributes(element, fAttrList); if (fAttrListHandle != -1) { fAttrList.endAttrList(); } fDocumentHandler.startElement(element, fAttrList, fAttrListHandle); fAttrListHandle = -1; //before we increment the element depth, add this element's QName to its enclosing element 's children list fElementDepth++; //if (fElementDepth >= 0) { if (fValidating) { // push current length onto stack if (fElementChildrenOffsetStack.length < fElementDepth) { int newarray[] = new int[fElementChildrenOffsetStack.length * 2]; System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length); fElementChildrenOffsetStack = newarray; } fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength; // add this element to children if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildrenLength * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.setValues(element); fElementChildrenLength++; if (DEBUG_ELEMENT_CHILDREN) { printChildren(); printStack(); } } // One more level of depth //fElementDepth++; ensureStackCapacity(fElementDepth); fCurrentElement.setValues(element); fCurrentElementEntity = fEntityHandler.getReaderId(); fElementQNamePartsStack[fElementDepth].setValues(fCurrentElement); fElementEntityStack[fElementDepth] = fCurrentElementEntity; fElementIndexStack[fElementDepth] = fCurrentElementIndex; fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType; if (fNeedValidationOff) { fValidating = false; fNeedValidationOff = false; } if (fValidating && fGrammarIsSchemaGrammar) { pushContentLeafStack(); } fValidationFlagStack[fElementDepth] = fValidating ? 0 : -1; fScopeStack[fElementDepth] = fCurrentScope; fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex; } // callStartElement(QName) private void pushContentLeafStack() throws Exception { int contentType = getContentSpecType(fCurrentElementIndex); if ( contentType == XMLElementDecl.TYPE_CHILDREN) { XMLContentModel cm = getElementContentModel(fCurrentElementIndex); ContentLeafNameTypeVector cv = cm.getContentLeafNameTypeVector(); if (cm != null) { fContentLeafStack[fElementDepth] = cv; } } } private void ensureStackCapacity ( int newElementDepth) { if (newElementDepth == fElementQNamePartsStack.length ) { int[] newStack = new int[newElementDepth * 2]; System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth); fScopeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth); fGrammarNameSpaceIndexStack = newStack; QName[] newStackOfQueue = new QName[newElementDepth * 2]; System.arraycopy(this.fElementQNamePartsStack, 0, newStackOfQueue, 0, newElementDepth ); fElementQNamePartsStack = newStackOfQueue; QName qname = fElementQNamePartsStack[newElementDepth]; if (qname == null) { for (int i = newElementDepth; i < fElementQNamePartsStack.length; i++) { fElementQNamePartsStack[i] = new QName(); } } newStack = new int[newElementDepth * 2]; System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth); fElementEntityStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth); fElementIndexStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth); fContentSpecTypeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fValidationFlagStack, 0, newStack, 0, newElementDepth); fValidationFlagStack = newStack; ContentLeafNameTypeVector[] newStackV = new ContentLeafNameTypeVector[newElementDepth * 2]; System.arraycopy(fContentLeafStack, 0, newStackV, 0, newElementDepth); fContentLeafStack = newStackV; } } /** Call end element. */ public void callEndElement(int readerId) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n"); int prefixIndex = fCurrentElement.prefix; int elementType = fCurrentElement.rawname; if (fCurrentElementEntity != readerId) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH, XMLMessages.P78_NOT_WELLFORMED, new Object[] { fStringPool.toString(elementType) }, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } fElementDepth if (fValidating) { int elementIndex = fCurrentElementIndex; if (elementIndex != -1 && fCurrentContentSpecType != -1) { QName children[] = fElementChildren; int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1; int childrenLength = fElementChildrenLength - childrenOffset; if (DEBUG_ELEMENT_CHILDREN) { System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')'); System.out.print("offset: "); System.out.print(childrenOffset); System.out.print(", length: "); System.out.print(childrenLength); System.out.println(); printChildren(); printStack(); } int result = checkContent(elementIndex, children, childrenOffset, childrenLength); if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result); if (result != -1) { int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE; fGrammar.getElementDecl(elementIndex, fTempElementDecl); if (fTempElementDecl.type == XMLElementDecl.TYPE_EMPTY) { reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), "EMPTY"); } else reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex)); } } fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1; } fDocumentHandler.endElement(fCurrentElement); if (fNamespacesEnabled) { fNamespacesScope.decreaseDepth(); } // now pop this element off the top of the element stack //if (fElementDepth-- < 0) { if (fElementDepth < -1) { throw new RuntimeException("FWK008 Element stack underflow"); } if (fElementDepth < 0) { fCurrentElement.clear(); fCurrentElementEntity = -1; fCurrentElementIndex = -1; fCurrentContentSpecType = -1; fInElementContent = false; // Check after document is fully parsed // (1) check that there was an element with a matching id for every // IDREF and IDREFS attr (V_IDREF0) if (fValidating ) { try{ this.fValIDRef.validate( null, this.fValidateIDRef ); this.fValIDRefs.validate( null, this.fValidateIDRef ); }catch( InvalidDatatypeValueException ex ){ reportRecoverableXMLError( ex.getMajorCode(), ex.getMinorCode(), ex.getMessage() ); } } return; } //restore enclosing element to all the "current" variables // REVISIT: Validation. This information needs to be stored. fCurrentElement.prefix = -1; if (fNamespacesEnabled) { //If Namespace enable then localName != rawName fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].localpart; } else {//REVISIT - jeffreyr - This is so we still do old behavior when namespace is off fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].rawname; } fCurrentElement.rawname = fElementQNamePartsStack[fElementDepth].rawname; fCurrentElement.uri = fElementQNamePartsStack[fElementDepth].uri; fCurrentElement.prefix = fElementQNamePartsStack[fElementDepth].prefix; fCurrentElementEntity = fElementEntityStack[fElementDepth]; fCurrentElementIndex = fElementIndexStack[fElementDepth]; fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth]; fValidating = fValidationFlagStack[fElementDepth] == 0 ? true : false; fCurrentScope = fScopeStack[fElementDepth]; //if ( DEBUG_SCHEMA_VALIDATION ) { /** Call start CDATA section. */ /** Call end CDATA section. */ /** Call characters. */ /** Call processing instruction. */ /** Call comment. */ /** Start a new namespace declaration scope. */ /** End a namespace declaration scope. */ /** Sets the root element. */ /** * Returns true if the element declaration is external. * <p> * <strong>Note:</strong> This method is primarilly useful for * DTDs with internal and external subsets. */ private boolean getElementDeclIsExternal(int elementIndex) { /*if (elementIndex < 0 || elementIndex >= fElementCount) { return false; } int chunk = elementIndex >> CHUNK_SHIFT; int index = elementIndex & CHUNK_MASK; return (fElementDeclIsExternal[chunk][index] != 0); */ if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex); } return false; } /** Returns the content spec type for an element index. */ public int getContentSpecType(int elementIndex) { int contentSpecType = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecType = fTempElementDecl.type; } } return contentSpecType; } /** Returns the content spec handle for an element index. */ public int getContentSpecHandle(int elementIndex) { int contentSpecHandle = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecHandle = fTempElementDecl.contentSpecIndex; } } return contentSpecHandle; } // Protected methods // error reporting /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, null, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception { Object[] args = { fStringPool.toString(stringIndex1) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1) throws Exception { Object[] args = { string1 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception { Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception { Object[] args = { string1, string2 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception { Object[] args = { string1, string2, string3 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String,String) // content spec protected int whatCanGoHere(int elementIndex, boolean fullyValid, InsertableElementsInfo info) throws Exception { // Do some basic sanity checking on the info packet. First, make sure // that insertAt is not greater than the child count. It can be equal, // which means to get appendable elements, but not greater. Or, if // the current children array is null, that's bad too. // Since the current children array must have a blank spot for where // the insert is going to be, the child count must always be at least // one. // Make sure that the child count is not larger than the current children // array. It can be equal, which means get appendable elements, but not // greater. if (info.insertAt > info.childCount || info.curChildren == null || info.childCount < 1 || info.childCount > info.curChildren.length) { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_WCGHI, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } int retVal = 0; try { // Get the content model for this element final XMLContentModel cmElem = getElementContentModel(elementIndex); // And delegate this call to it retVal = cmElem.whatCanGoHere(fullyValid, info); } catch (CMException excToCatch) { // REVISIT - Translate caught error to the protected error handler interface int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); throw excToCatch; } return retVal; } // whatCanGoHere(int,boolean,InsertableElementsInfo):int // attribute information /** Protected for use by AttributeValidator classes. */ protected boolean getAttDefIsExternal(QName element, QName attribute) { int attDefIndex = getAttDef(element, attribute); if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex); } return false; } // Private methods // other /** Returns true if using a standalone reader. */ private boolean usingStandaloneReader() { return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader; } /** Returns a locator implementation. */ private LocatorImpl getLocatorImpl(LocatorImpl fillin) { Locator here = fErrorReporter.getLocator(); if (fillin == null) return new LocatorImpl(here); fillin.setPublicId(here.getPublicId()); fillin.setSystemId(here.getSystemId()); fillin.setLineNumber(here.getLineNumber()); fillin.setColumnNumber(here.getColumnNumber()); return fillin; } // getLocatorImpl(LocatorImpl):LocatorImpl // initialization /** Reset pool. */ private void poolReset() { try{ this.fValIDRef.validate(null, this.fResetIDRef ); this.fValIDRefs.validate(null, this.fResetIDRef ); } catch( InvalidDatatypeValueException ex ){ System.err.println("Error re-Initializing: ID,IDRef,IDRefs pools" ); } } // poolReset() /** Reset common. */ private void resetCommon(StringPool stringPool) throws Exception { fStringPool = stringPool; fValidating = fValidationEnabled; fValidationEnabledByDynamic = false; fDynamicDisabledByValidation = false; poolReset(); fCalledStartDocument = false; fStandaloneReader = -1; fElementChildrenLength = 0; fElementDepth = -1; fSeenRootElement = false; fSeenDoctypeDecl = false; fNamespacesScope = null; fNamespacesPrefix = -1; fRootElement.clear(); fAttrListHandle = -1; fCheckedForSchema = false; fCurrentScope = TOP_LEVEL_SCOPE; fCurrentSchemaURI = -1; fEmptyURI = - 1; fXsiPrefix = - 1; fXsiTypeValidator = null; fGrammar = null; fGrammarNameSpaceIndex = -1; //fGrammarResolver = null; if (fGrammarResolver != null) { fGrammarResolver.clearGrammarResolver(); } fGrammarIsDTDGrammar = false; fGrammarIsSchemaGrammar = false; init(); } // resetCommon(StringPool) /** Initialize. */ private void init() { fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); fEMPTYSymbol = fStringPool.addSymbol("EMPTY"); fANYSymbol = fStringPool.addSymbol("ANY"); fMIXEDSymbol = fStringPool.addSymbol("MIXED"); fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN"); fCDATASymbol = fStringPool.addSymbol("CDATA"); fIDSymbol = fStringPool.addSymbol("ID"); fIDREFSymbol = fStringPool.addSymbol("IDREF"); fIDREFSSymbol = fStringPool.addSymbol("IDREFS"); fENTITYSymbol = fStringPool.addSymbol("ENTITY"); fENTITIESSymbol = fStringPool.addSymbol("ENTITIES"); fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN"); fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS"); fNOTATIONSymbol = fStringPool.addSymbol("NOTATION"); fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION"); fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED"); fFIXEDSymbol = fStringPool.addSymbol("#FIXED"); fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>"); fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>"); fXMLLang = fStringPool.addSymbol("xml:lang"); try{//Initialize ENTITIES and ENTITY Validators Object[] packageArgsEntityVal = { (Object) this.fEntityHandler, (Object) this.fStringPool }; fValidateENTITYMsg.setDatatypeObject( (Object ) packageArgsEntityVal); fValENTITIES.validate( null, fValidateENTITYMsg ); fValENTITY.validate( null, fValidateENTITYMsg ); } catch ( InvalidDatatypeValueException ex ){ System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen } } // init() // other // default attribute /** addDefaultAttributes. */ private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception { //System.out.println("XMLValidator#addDefaultAttributes"); //System.out.print(" "); //fGrammar.printAttributes(elementIndex); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) check that FIXED attrs have matching value (V_TAGd) // (3) add default attrs (FIXED and NOT_FIXED) fGrammar.getElementDecl(elementIndex,fTempElementDecl); int elementNameIndex = fTempElementDecl.name.localpart; int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); int firstCheck = attrIndex; int lastCheck = -1; while (attlistIndex != -1) { //int adChunk = attlistIndex >> CHUNK_SHIFT; //int adIndex = attlistIndex & CHUNK_MASK; fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl); // TO DO: For ericye Debug only /** addDTDDefaultAttributes. */ /** Queries the content model for the specified element index. */ /** Returns an attribute definition for an element type. */ /** Returns an attribute definition for an element type. */ /** Root element specified. */ /** Switchs to correct validating symbol tables when Schema changes.*/ /** Binds namespaces to the element and attributes. */ /** Warning. */ /** Error. */ /** Fatal error. */ /** Returns a string of the location. */ /** Validates element and attributes. */ /*if (attributeDecl.list) { av = fAttValidatorENTITIES; } else { av = fAttValidatorENTITY; }*/ } break; case XMLAttributeDecl.TYPE_ENUMERATION: av = fAttValidatorENUMERATION; break; case XMLAttributeDecl.TYPE_ID: { String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); if (fValidationEnabled){ if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } } try{ //this.fIdDefs = (Hashtable) fValID.validate( value, null ); //System.out.println("this.fIdDefs = " + this.fIdDefs ); this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) ); } catch ( InvalidDatatypeValueException ex ){ reportRecoverableXMLError(ex.getMajorCode(), ex.getMinorCode(), fStringPool.toString( attributeDecl.name.rawname), value ); } } break; case XMLAttributeDecl.TYPE_IDREF: { String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef //changes fTempAttDef if (fValidationEnabled){ if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } } try{ if ( isAlistAttribute ){ fValIDRefs.validate( value, this.fStoreIDRef ); } else { fValIDRef.validate( value, this.fStoreIDRef ); } } catch ( InvalidDatatypeValueException ex ){ if ( ex.getMajorCode() != 1 && ex.getMinorCode() != -1 ) { reportRecoverableXMLError(ex.getMajorCode(), ex.getMinorCode(), fStringPool.toString( attributeDecl.name.rawname), value ); } else { System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen } } } break; case XMLAttributeDecl.TYPE_NOTATION: av = fAttValidatorNOTATION; break; case XMLAttributeDecl.TYPE_NMTOKEN: if (attributeDecl.list) { av = fAttValidatorNMTOKENS; } else { av = fAttValidatorNMTOKEN; } break; } if ( av != null ) av.normalize(element, attributeDecl.name, attValue, attributeDecl.type, attributeDecl.enumeration); } /** Character data in content. */ private void charDataInContent() { if (DEBUG_ELEMENT_CHILDREN) { System.out.println("charDataInContent()"); } if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildren.length * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.clear(); fElementChildrenLength++; } // charDataInCount() /** * Check that the content of an element is valid. * <p> * This is the method of primary concern to the validator. This method is called * upon the scanner reaching the end tag of an element. At that time, the * element's children must be structurally validated, so it calls this method. * The index of the element being checked (in the decl pool), is provided as * well as an array of element name indexes of the children. The validator must * confirm that this element can have these children in this order. * <p> * This can also be called to do 'what if' testing of content models just to see * if they would be valid. * <p> * Note that the element index is an index into the element decl pool, whereas * the children indexes are name indexes, i.e. into the string pool. * <p> * A value of -1 in the children array indicates a PCDATA node. All other * indexes will be positive and represent child elements. The count can be * zero, since some elements have the EMPTY content model and that must be * confirmed. * * @param elementIndex The index within the <code>ElementDeclPool</code> of this * element. * @param childCount The number of entries in the <code>children</code> array. * @param children The children of this element. Each integer is an index within * the <code>StringPool</code> of the child element name. An index * of -1 is used to indicate an occurrence of non-whitespace character * data. * * @return The value -1 if fully valid, else the 0 based index of the child * that first failed. If the value returned is equal to the number * of children, then additional content is required to reach a valid * ending state. * * @exception Exception Thrown on error. */ private int checkContent(int elementIndex, QName[] children, int childOffset, int childCount) throws Exception { // Get the element name index from the element // REVISIT: Validation final int elementType = fCurrentElement.rawname; if (DEBUG_PRINT_CONTENT) { String strTmp = fStringPool.toString(elementType); System.out.println("Name: "+strTmp+", "+ "Count: "+childCount+", "+ "ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex)); for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) { if (index == 0) { System.out.print(" ("); } String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart); if (index + 1 == childCount) { System.out.println(childName + ")"); } else if (index + 1 == 10) { System.out.println(childName + ",...)"); } else { System.out.print(childName + ","); } } } // Get out the content spec for this element final int contentType = fCurrentContentSpecType; // debugging //System.out.println("~~~~~~in checkContent, fCurrentContentSpecType : " + fCurrentContentSpecType); // Deal with the possible types of content. We try to optimized here // by dealing specially with content models that don't require the // full DFA treatment. if (contentType == XMLElementDecl.TYPE_EMPTY) { // If the child count is greater than zero, then this is // an error right off the bat at index 0. if (childCount != 0) { return 0; } } else if (contentType == XMLElementDecl.TYPE_ANY) { // This one is open game so we don't pass any judgement on it // at all. Its assumed to fine since it can hold anything. } else if (contentType == XMLElementDecl.TYPE_MIXED || contentType == XMLElementDecl.TYPE_CHILDREN) { // Get the content model for this element, faulting it in if needed XMLContentModel cmElem = null; try { cmElem = getElementContentModel(elementIndex); int result = cmElem.validateContent(children, childOffset, childCount); if (result != -1 && fGrammarIsSchemaGrammar) { // REVISIT: not optimized for performance, EquivClassComparator comparator = new EquivClassComparator(fGrammarResolver, fStringPool); cmElem.setEquivClassComparator(comparator); result = cmElem.validateContentSpecial(children, childOffset, childCount); } return result; } catch(CMException excToCatch) { // REVISIT - Translate the caught exception to the protected error API int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } } else if (contentType == -1) { reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED, XMLMessages.VC_ELEMENT_VALID, elementType); } else if (contentType == XMLElementDecl.TYPE_SIMPLE ) { XMLContentModel cmElem = null; if (childCount > 0) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { "Can not have element children within a simple type content" }, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } else { try { fGrammar.getElementDecl(elementIndex, fTempElementDecl); DatatypeValidator dv = fTempElementDecl.datatypeValidator; // If there is xsi:type validator, substitute it. if ( fXsiTypeValidator != null ) { dv = fXsiTypeValidator; fXsiTypeValidator = null; } if (dv == null) { System.out.println("Internal Error: this element have a simpletype "+ "but no datatypevalidator was found, element "+fTempElementDecl.name +",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart)); } else { dv.validate(fDatatypeBuffer.toString(), null); } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { idve.getMessage() }, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } else { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_CST, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } // We succeeded return -1; } // checkContent(int,int,int[]):int /** * Checks that all declared elements refer to declared elements * in their content models. This method calls out to the error * handler to indicate warnings. */ private void printChildren() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('['); for (int i = 0; i < fElementChildrenLength; i++) { System.out.print(' '); QName qname = fElementChildren[i]; if (qname != null) { System.out.print(fStringPool.toString(qname.rawname)); } else { System.out.print("null"); } if (i < fElementChildrenLength - 1) { System.out.print(", "); } System.out.flush(); } System.out.print(" ]"); System.out.println(); } } private void printStack() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('{'); for (int i = 0; i <= fElementDepth; i++) { System.out.print(' '); System.out.print(fElementChildrenOffsetStack[i]); if (i < fElementDepth) { System.out.print(", "); } System.out.flush(); } System.out.print(" }"); System.out.println(); } } // Interfaces /** * AttributeValidator. */ public interface AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValue, int attType, int enumHandle) throws Exception; } // interface AttributeValidator /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } // Classes /** * AttValidatorCDATA. */ final class AttValidatorCDATA implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... return attValueHandle; } } // class AttValidatorCDATA /** * AttValidatorNMTOKEN. */ final class AttValidatorNMTOKEN implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validNmtoken(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKEN /** * AttValidatorNMTOKENS. */ final class AttValidatorNMTOKENS implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String nmtoken = tokenizer.nextToken(); if (fValidating && !XMLCharacterProperties.validNmtoken(nmtoken)) { ok = false; } sb.append(nmtoken); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKENS /** * AttValidatorNOTATION. */ final class AttValidatorNOTATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // NOTATION - check that the value is in the AttDef enumeration (V_TAGo) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_NOTATION_ATTRIBUTES, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNOTATION /** * AttValidatorENUMERATION. */ final class AttValidatorENUMERATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENUMERATION - check that value is in the AttDef enumeration (V_TAG9) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_ENUMERATION, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENUMERATION } // class XMLValidator
package org.apache.xerces.validators.common; import org.apache.xerces.framework.XMLAttrList; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.framework.XMLDocumentHandler; import org.apache.xerces.framework.XMLDocumentScanner; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.readers.DefaultEntityHandler; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.utils.ChunkyCharArray; import org.apache.xerces.utils.Hash2intTable; import org.apache.xerces.utils.IntStack; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.apache.xerces.utils.XMLMessages; import org.apache.xerces.utils.ImplementationMessages; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.EntityResolver; import org.xml.sax.Locator; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.validators.dtd.DTDGrammar; import org.apache.xerces.validators.schema.SubstitutionGroupComparator; import org.apache.xerces.validators.schema.SchemaGrammar; import org.apache.xerces.validators.schema.SchemaMessageProvider; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.TraverseSchema; import org.apache.xerces.validators.schema.identity.Field; import org.apache.xerces.validators.schema.identity.FieldActivator; import org.apache.xerces.validators.schema.identity.IdentityConstraint; import org.apache.xerces.validators.schema.identity.IDValue; import org.apache.xerces.validators.schema.identity.Key; import org.apache.xerces.validators.schema.identity.KeyRef; import org.apache.xerces.validators.schema.identity.Selector; import org.apache.xerces.validators.schema.identity.Unique; import org.apache.xerces.validators.schema.identity.ValueStore; import org.apache.xerces.validators.schema.identity.XPathMatcher; import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.validators.datatype.StateMessageDatatype; import org.apache.xerces.validators.datatype.IDREFDatatypeValidator; import org.apache.xerces.validators.datatype.IDDatatypeValidator; import org.apache.xerces.validators.datatype.ENTITYDatatypeValidator; import org.apache.xerces.validators.datatype.NOTATIONDatatypeValidator; import org.apache.xerces.validators.datatype.UnionDatatypeValidator; /** * This class is the super all-in-one validator used by the parser. * * @version $Id$ */ public final class XMLValidator implements DefaultEntityHandler.EventHandler, XMLEntityHandler.CharDataHandler, XMLDocumentScanner.EventHandler, NamespacesScope.NamespacesHandler, FieldActivator // for identity constraints { // Constants // debugging private static final boolean PRINT_EXCEPTION_STACK_TRACE = false; private static final boolean DEBUG_PRINT_ATTRIBUTES = false; private static final boolean DEBUG_PRINT_CONTENT = false; private static final boolean DEBUG_SCHEMA_VALIDATION = false; private static final boolean DEBUG_ELEMENT_CHILDREN = false; /** Compile to true to debug identity constraints. */ protected static final boolean DEBUG_IDENTITY_CONSTRAINTS = false; /** Compile to true to debug value stores. */ protected static final boolean DEBUG_VALUE_STORES = false; // Chunk size constants private static final int CHUNK_SHIFT = 8; // 2^8 = 256 private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT); private static final int CHUNK_MASK = CHUNK_SIZE - 1; private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k private Hashtable fIdDefs = null; private StateMessageDatatype fStoreIDRef = new StateMessageDatatype() { private Hashtable fIdDefs; public Object getDatatypeObject(){ return(Object) fIdDefs; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_STORE; } public void setDatatypeObject( Object data ){ fIdDefs = (Hashtable) data; } }; private StateMessageDatatype fResetID = new StateMessageDatatype() { public Object getDatatypeObject(){ return(Object) null; } public int getDatatypeState(){ return IDDatatypeValidator.ID_CLEAR; } public void setDatatypeObject( Object data ){ } }; private StateMessageDatatype fResetIDRef = new StateMessageDatatype() { public Object getDatatypeObject(){ return(Object) null; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_CLEAR; } public void setDatatypeObject( Object data ){ } }; private StateMessageDatatype fValidateIDRef = new StateMessageDatatype() { public Object getDatatypeObject(){ return(Object) null; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_VALIDATE; } public void setDatatypeObject( Object data ){ } }; private StateMessageDatatype fValidateENTITYMsg = new StateMessageDatatype() { private Object packagedMessage = null; public Object getDatatypeObject(){ return packagedMessage; } public int getDatatypeState(){ return ENTITYDatatypeValidator.ENTITY_INITIALIZE;//No state } public void setDatatypeObject( Object data ){ packagedMessage = data;// Set Entity Handler } }; /* private StateMessageDatatype fValidateNOTATIONMsg = new StateMessageDatatype() { private Object packagedMessage = null; public Object getDatatypeObject(){ return packagedMessage; } public int getDatatypeState(){ return NOTATIONDatatypeValidator.ENTITY_INITIALIZE;//No state } public void setDatatypeObject( Object data ){ packagedMessage = data;// Set Entity Handler } }; */ // Data // REVISIT: The data should be regrouped and re-organized so that // it's easier to find a meaningful field. // attribute validators private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION(); private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION(); private AttributeValidator fAttValidatorDATATYPE = null; // Package access for use by AttributeValidator classes. StringPool fStringPool = null; boolean fValidating = false; boolean fInElementContent = false; int fStandaloneReader = -1; // settings private boolean fValidationEnabled = false; private boolean fDynamicValidation = false; private boolean fSchemaValidation = true; private boolean fValidationEnabledByDynamic = false; private boolean fDynamicDisabledByValidation = false; private boolean fWarningOnDuplicateAttDef = false; private boolean fWarningOnUndeclaredElements = false; private boolean fNormalizeAttributeValues = true; private boolean fLoadDTDGrammar = true; // declarations private DOMParser fSchemaGrammarParser = null; private int fDeclaration[]; private XMLErrorReporter fErrorReporter = null; private DefaultEntityHandler fEntityHandler = null; private QName fCurrentElement = new QName(); private ContentLeafNameTypeVector[] fContentLeafStack = new ContentLeafNameTypeVector[8]; private int[] fValidationFlagStack = new int[8]; private int[] fScopeStack = new int[8]; private int[] fGrammarNameSpaceIndexStack = new int[8]; private int[] fElementEntityStack = new int[8]; private int[] fElementIndexStack = new int[8]; private int[] fContentSpecTypeStack = new int[8]; private static final int sizeQNameParts = 8; private QName[] fElementQNamePartsStack = new QName[sizeQNameParts]; private QName[] fElementChildren = new QName[32]; private int fElementChildrenLength = 0; private int[] fElementChildrenOffsetStack = new int[32]; private int fElementDepth = -1; private boolean fNamespacesEnabled = false; private NamespacesScope fNamespacesScope = null; private int fNamespacesPrefix = -1; private QName fRootElement = new QName(); private int fAttrListHandle = -1; private int fCurrentElementEntity = -1; private int fCurrentElementIndex = -1; private int fCurrentContentSpecType = -1; private boolean fSeenDoctypeDecl = false; private final int TOP_LEVEL_SCOPE = -1; private int fCurrentScope = TOP_LEVEL_SCOPE; private int fCurrentSchemaURI = StringPool.EMPTY_STRING; private int fEmptyURI = StringPool.EMPTY_STRING; private int fXsiPrefix = - 1; private int fXsiURI = -2; private int fXsiTypeAttValue = -1; private DatatypeValidator fXsiTypeValidator = null; private boolean fNil = false; private Grammar fGrammar = null; private int fGrammarNameSpaceIndex = StringPool.EMPTY_STRING; private GrammarResolver fGrammarResolver = null; // state and stuff private boolean fScanningDTD = false; private XMLDocumentScanner fDocumentScanner = null; private boolean fCalledStartDocument = false; private XMLDocumentHandler fDocumentHandler = null; private XMLDocumentHandler.DTDHandler fDTDHandler = null; private boolean fSeenRootElement = false; private XMLAttrList fAttrList = null; private int fXMLLang = -1; private LocatorImpl fAttrNameLocator = null; private boolean fCheckedForSchema = false; private boolean fDeclsAreExternal = false; private StringPool.CharArrayRange fCurrentElementCharArrayRange = null; private char[] fCharRefData = null; private boolean fSendCharDataAsCharArray = false; private boolean fBufferDatatype = false; private StringBuffer fDatatypeBuffer = new StringBuffer(); private QName fTempQName = new QName(); private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl(); private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl(); private XMLElementDecl fTempElementDecl = new XMLElementDecl(); private boolean fGrammarIsDTDGrammar = false; private boolean fGrammarIsSchemaGrammar = false; private boolean fNeedValidationOff = false; //Schema Normalization private static final boolean DEBUG_NORMALIZATION = false; private DatatypeValidator fCurrentDV = null; //current datatype validator private boolean fFirstChunk = true; // got first chunk in characters() (SAX) private boolean fTrailing = false; // Previous chunk had a trailing space private short fWhiteSpace = DatatypeValidator.COLLAPSE; //whiteSpace: preserve/replace/collapse private StringBuffer fStringBuffer = new StringBuffer(CHUNK_SIZE); //holds normalized str value private StringBuffer fTempBuffer = new StringBuffer(CHUNK_SIZE); //holds unnormalized str value // symbols private int fEMPTYSymbol = -1; private int fANYSymbol = -1; private int fMIXEDSymbol = -1; private int fCHILDRENSymbol = -1; private int fCDATASymbol = -1; private int fIDSymbol = -1; private int fIDREFSymbol = -1; private int fIDREFSSymbol = -1; private int fENTITYSymbol = -1; private int fENTITIESSymbol = -1; private int fNMTOKENSymbol = -1; private int fNMTOKENSSymbol = -1; private int fNOTATIONSymbol = -1; private int fENUMERATIONSymbol = -1; private int fREQUIREDSymbol = -1; private int fFIXEDSymbol = -1; private int fDATATYPESymbol = -1; private int fEpsilonIndex = -1; //Datatype Registry private DatatypeValidatorFactoryImpl fDataTypeReg = null; private DatatypeValidator fValID = null; private DatatypeValidator fValIDRef = null; private DatatypeValidator fValIDRefs = null; private DatatypeValidator fValENTITY = null; private DatatypeValidator fValENTITIES = null; private DatatypeValidator fValNMTOKEN = null; private DatatypeValidator fValNMTOKENS = null; private DatatypeValidator fValNOTATION = null; // identity constraint information /** * Stack of active XPath matchers for identity constraints. All * active XPath matchers are notified of startElement, characters * and endElement callbacks in order to perform their matches. * <p> * For each element with identity constraints, the selector of * each identity constraint is activated. When the selector matches * its XPath, then all the fields of the identity constraint are * activated. * <p> * <strong>Note:</strong> Once the activation scope is left, the * XPath matchers are automatically removed from the stack of * active matchers and no longer receive callbacks. */ protected XPathMatcherStack fMatcherStack = new XPathMatcherStack(); /** Cache of value stores for identity constraint fields. */ protected ValueStoreCache fValueStoreCache = new ValueStoreCache(); // Constructors /** Constructs an XML validator. */ public XMLValidator(StringPool stringPool, XMLErrorReporter errorReporter, DefaultEntityHandler entityHandler, XMLDocumentScanner documentScanner) { // keep references fStringPool = stringPool; fErrorReporter = errorReporter; fEntityHandler = entityHandler; fDocumentScanner = documentScanner; fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); // initialize fAttrList = new XMLAttrList(fStringPool); entityHandler.setEventHandler(this); entityHandler.setCharDataHandler(this); fDocumentScanner.setEventHandler(this); for (int i = 0; i < sizeQNameParts; i++) { fElementQNamePartsStack[i] = new QName(); } init(); } // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner) public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; if (fValidating) { //optimization -el initDataTypeValidators(); } } // Public methods // initialization /** Set char data processing preference and handlers. */ public void initHandlers(boolean sendCharDataAsCharArray, XMLDocumentHandler docHandler, XMLDocumentHandler.DTDHandler dtdHandler) { fSendCharDataAsCharArray = sendCharDataAsCharArray; fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray); fDocumentHandler = docHandler; fDTDHandler = dtdHandler; } // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler) /** Reset or copy. */ public void resetOrCopy(StringPool stringPool) throws Exception { fAttrList = new XMLAttrList(stringPool); resetCommon(stringPool); } /** Reset. */ public void reset(StringPool stringPool) throws Exception { fAttrList.reset(stringPool); resetCommon(stringPool); } // settings /** * Turning on validation/dynamic turns on validation if it is off, and * this is remembered. Turning off validation DISABLES validation/dynamic * if it is on. Turning off validation/dynamic DOES NOT turn off * validation if it was explicitly turned on, only if it was turned on * BECAUSE OF the call to turn validation/dynamic on. Turning on * validation will REENABLE and turn validation/dynamic back on if it * was disabled by a call that turned off validation while * validation/dynamic was enabled. */ public void setValidationEnabled(boolean flag) throws Exception { fValidationEnabled = flag; fValidationEnabledByDynamic = false; if (fValidationEnabled) { if (fDynamicDisabledByValidation) { fDynamicValidation = true; fDynamicDisabledByValidation = false; } } else if (fDynamicValidation) { fDynamicValidation = false; fDynamicDisabledByValidation = true; } fValidating = fValidationEnabled; //optimization: don't create unnecessary DatatypeValidators. - el if (fValidating) { initDataTypeValidators(); } } /** Returns true if validation is enabled. */ public boolean getValidationEnabled() { return fValidationEnabled; } /** Sets whether Schema support is on/off. */ public void setSchemaValidationEnabled(boolean flag) { fSchemaValidation = flag; } /** Returns true if Schema support is on. */ public boolean getSchemaValidationEnabled() { return fSchemaValidation; } /** Sets whether validation is dynamic. */ public void setDynamicValidationEnabled(boolean flag) throws Exception { fDynamicValidation = flag; fDynamicDisabledByValidation = false; if (!fDynamicValidation) { if (fValidationEnabledByDynamic) { fValidationEnabled = false; fValidationEnabledByDynamic = false; } } else if (!fValidationEnabled) { fValidationEnabled = true; fValidationEnabledByDynamic = true; } fValidating = fValidationEnabled; //optimization: don't create unnecessary DatatypeValidators. - el if (fValidating) { initDataTypeValidators(); } } /** Returns true if validation is dynamic. */ public boolean getDynamicValidationEnabled() { return fDynamicValidation; } /** Sets fNormalizeAttributeValues **/ public void setNormalizeAttributeValues(boolean normalize){ fNormalizeAttributeValues = normalize; } /** Sets fLoadDTDGrammar when validation is off **/ public void setLoadDTDGrammar(boolean loadDG){ if (fValidating) { fLoadDTDGrammar = true; } else { fLoadDTDGrammar = loadDG; } } /** Returns fLoadDTDGrammar **/ public boolean getLoadDTDGrammar() { return fLoadDTDGrammar; } /** Sets whether namespaces are enabled. */ public void setNamespacesEnabled(boolean flag) { fNamespacesEnabled = flag; } /** Returns true if namespaces are enabled. */ public boolean getNamespacesEnabled() { return fNamespacesEnabled; } /** Sets whether duplicate attribute definitions signal a warning. */ public void setWarningOnDuplicateAttDef(boolean flag) { fWarningOnDuplicateAttDef = flag; } /** Returns true if duplicate attribute definitions signal a warning. */ public boolean getWarningOnDuplicateAttDef() { return fWarningOnDuplicateAttDef; } /** Sets whether undeclared elements signal a warning. */ public void setWarningOnUndeclaredElements(boolean flag) { fWarningOnUndeclaredElements = flag; } /** Returns true if undeclared elements signal a warning. */ public boolean getWarningOnUndeclaredElements() { return fWarningOnUndeclaredElements; } // FieldActivator methods /** * Start the value scope for the specified identity constraint. This * method is called when the selector matches in order to initialize * the value store. * * @param identityConstraint The identity constraint. */ public void startValueScopeFor(IdentityConstraint identityConstraint) throws Exception { for(int i=0; i<identityConstraint.getFieldCount(); i++) { Field field = identityConstraint.getFieldAt(i); ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(field); valueStore.startValueScope(); } } // startValueScopeFor(IdentityConstraint identityConstraint) /** * Request to activate the specified field. This method returns the * matcher for the field. * * @param field The field to activate. */ public XPathMatcher activateField(Field field) throws Exception { if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: activateField(\""+field+"\")"); } ValueStore valueStore = fValueStoreCache.getValueStoreFor(field); field.setMayMatch(true); XPathMatcher matcher = field.createMatcher(valueStore); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(fStringPool); return matcher; } // activateField(Field):XPathMatcher /** * Ends the value scope for the specified identity constraint. * * @param identityConstraint The identity constraint. */ public void endValueScopeFor(IdentityConstraint identityConstraint) throws Exception { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint); valueStore.endValueScope(); } // endValueScopeFor(IdentityConstraint) // DefaultEntityHandler.EventHandler methods /** Start entity reference. */ public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.startEntityReference(entityName, entityType, entityContext); } /** End entity reference. */ public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.endEntityReference(entityName, entityType, entityContext); } /** Send end of input notification. */ public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception { fDocumentScanner.endOfInput(entityName, moreToFollow); /** Send reader change notifications. */ /** External entity standalone check. */ /** Return true if validating. */ /** * Normalize whitespace in an XMLString according to the rules of attribute * value normalization - converting all whitespace characters to space * characters. * In addition for attributes of type other than CDATA: trim leading and * trailing spaces and collapse spaces (0x20 only). * * @param value The string to normalize. * @returns 0 if no triming is done or if there is neither leading nor * trailing whitespace, * 1 if there is only leading whitespace, * 2 if there is only trailing whitespace, * 3 if there is both leading and trailing whitespace. */ private int normalizeWhitespace( StringBuffer chars, boolean collapse) { int length = fTempBuffer.length(); fStringBuffer.setLength(0); boolean skipSpace = collapse; boolean sawNonWS = false; int leading = 0; int trailing = 0; int c; for (int i = 0; i < length; i++) { c = chars.charAt(i); if (c == 0x20 || c == 0x0D || c == 0x0A || c == 0x09) { if (!skipSpace) { // take the first whitespace as a space and skip the others fStringBuffer.append(' '); skipSpace = collapse; } if (!sawNonWS) { // this is a leading whitespace, record it leading = 1; } } else { fStringBuffer.append((char)c); skipSpace = false; sawNonWS = true; } } if (skipSpace) { c = fStringBuffer.length(); if ( c != 0) { // if we finished on a space trim it but also record it fStringBuffer.setLength (--c); trailing = 2; } else if (leading != 0 && !sawNonWS) { // if all we had was whitespace we skipped record it as // trailing whitespace as well trailing = 2; } } //value.setValues(fStringBuffer); return collapse ? leading + trailing : 0; } /** Process characters. Schema Normalization*/ public void processCharacters(char[] chars, int offset, int length) throws Exception { if (DEBUG_NORMALIZATION) { System.out.println("==>processCharacters(char[] chars, int offset, int length"); } if (fValidating) { if (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) { if (DEBUG_NORMALIZATION) { System.out.println("==>charDataInContent()"); } charDataInContent(); } if (fBufferDatatype) { if (fFirstChunk && fGrammar!=null) { fGrammar.getElementDecl(fCurrentElementIndex, fTempElementDecl); fCurrentDV = fTempElementDecl.datatypeValidator; if (fCurrentDV !=null) { fWhiteSpace = fCurrentDV.getWSFacet(); } } if (DEBUG_NORMALIZATION) { System.out.println("Start schema datatype normalization <whiteSpace value=" +fWhiteSpace+">"); } if (fWhiteSpace == DatatypeValidator.PRESERVE) { //do not normalize fDatatypeBuffer.append(chars, offset, length); } else { fTempBuffer.setLength(0); fTempBuffer.append(chars, offset, length); int spaces = normalizeWhitespace(fTempBuffer, (fWhiteSpace==DatatypeValidator.COLLAPSE)); int nLength = fStringBuffer.length(); if (nLength > 0) { if (!fFirstChunk && (fWhiteSpace==DatatypeValidator.COLLAPSE) && fTrailing) { fStringBuffer.insert(0, ' '); nLength++; } if ((length-offset)!=nLength) { char[] newChars = new char[nLength]; fStringBuffer.getChars(0, nLength , newChars, 0); chars = newChars; offset = 0; length = nLength; } else { fStringBuffer.getChars(0, nLength , chars, 0); } fDatatypeBuffer.append(chars, offset, length); fDocumentHandler.characters(chars, offset, length); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { String text = new String(chars, offset, length); System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(chars, offset, length); } } fTrailing = (spaces > 1)?true:false; fFirstChunk = false; return; } } } fFirstChunk = false; fDocumentHandler.characters(chars, offset, length); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { String text = new String(chars, offset, length); System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(chars, offset, length); } } /** Process characters. */ public void processCharacters(int data) throws Exception { if (fValidating) { if (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) { charDataInContent(); } if (fBufferDatatype) { fGrammar.getElementDecl(fCurrentElementIndex, fTempElementDecl); //REVISIT: add normalization according to datatypes fCurrentDV = fTempElementDecl.datatypeValidator; if (fCurrentDV !=null) { fWhiteSpace = fCurrentDV.getWSFacet(); } if (fWhiteSpace == DatatypeValidator.PRESERVE) { //no normalization done fDatatypeBuffer.append(fStringPool.toString(data)); } else { String str = fStringPool.toString(data); int length = str.length(); fTempBuffer.setLength(0); fTempBuffer.append(str); int spaces = normalizeWhitespace(fTempBuffer, (fWhiteSpace == DatatypeValidator.COLLAPSE)); if (fWhiteSpace != DatatypeValidator.PRESERVE) { //normalization was done. fStringPool.releaseString(data); data = fStringPool.addString(fStringBuffer.toString()); } fDatatypeBuffer.append(fStringBuffer.toString()); } } } fDocumentHandler.characters(data); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); if (count > 0) { String text = fStringPool.toString(data); char[] chars = new char[text.length()]; int offset = 0; int length = chars.length; text.getChars(offset, length, chars, offset); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(chars, offset, length); } } } /** Process whitespace. */ public void processWhitespace(char[] chars, int offset, int length) throws Exception { if (fInElementContent) { if (fStandaloneReader != -1 && fValidating && getElementDeclIsExternal(fCurrentElementIndex)) { reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION); } fDocumentHandler.ignorableWhitespace(chars, offset, length); } else { if (fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) { charDataInContent(); } fDocumentHandler.characters(chars, offset, length); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { String text = new String(chars, offset, length); System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(chars, offset, length); } } } // processWhitespace(char[],int,int) /** Process whitespace. */ public void processWhitespace(int data) throws Exception { if (fInElementContent) { if (fStandaloneReader != -1 && fValidating && getElementDeclIsExternal(fCurrentElementIndex)) { reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION); } fDocumentHandler.ignorableWhitespace(data); } else { if (fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) { charDataInContent(); } fDocumentHandler.characters(data); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); if (count > 0) { String text = fStringPool.toString(data); char[] chars = new char[text.length()]; int offset = 0; int length = chars.length; text.getChars(length, length, chars, offset); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(chars, offset, length); } } } } // processWhitespace(int) // XMLDocumentScanner.EventHandler methods /** Scans element type. */ public void scanElementType(XMLEntityHandler.EntityReader entityReader, char fastchar, QName element) throws Exception { if (!fNamespacesEnabled) { element.clear(); element.localpart = entityReader.scanName(fastchar); element.rawname = element.localpart; } else { entityReader.scanQName(fastchar, element); if (entityReader.lookingAtChar(':', false)) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_TWO_COLONS_IN_QNAME, XMLMessages.P5_INVALID_CHARACTER, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); entityReader.skipPastNmtoken(' '); } } } // scanElementType(XMLEntityHandler.EntityReader,char,QName) /** Scans expected element type. */ public boolean scanExpectedElementType(XMLEntityHandler.EntityReader entityReader, char fastchar, QName element) throws Exception { if (fCurrentElementCharArrayRange == null) { fCurrentElementCharArrayRange = fStringPool.createCharArrayRange(); } fStringPool.getCharArrayRange(fCurrentElement.rawname, fCurrentElementCharArrayRange); return entityReader.scanExpectedName(fastchar, fCurrentElementCharArrayRange); } // scanExpectedElementType(XMLEntityHandler.EntityReader,char,QName) /** Scans attribute name. */ public void scanAttributeName(XMLEntityHandler.EntityReader entityReader, QName element, QName attribute) throws Exception { if (!fSeenRootElement) { fSeenRootElement = true; rootElementSpecified(element); fStringPool.resetShuffleCount(); } if (!fNamespacesEnabled) { attribute.clear(); attribute.localpart = entityReader.scanName('='); attribute.rawname = attribute.localpart; } else { entityReader.scanQName('=', attribute); if (entityReader.lookingAtChar(':', false)) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_TWO_COLONS_IN_QNAME, XMLMessages.P5_INVALID_CHARACTER, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); entityReader.skipPastNmtoken(' '); } } } // scanAttributeName(XMLEntityHandler.EntityReader,QName,QName) /** Call start document. */ public void callStartDocument() throws Exception { if (!fCalledStartDocument) { fDocumentHandler.startDocument(); fCalledStartDocument = true; if (fValidating) { fValueStoreCache.startDocument(); } } } /** Call end document. */ public void callEndDocument() throws Exception { if (fCalledStartDocument) { if (fValidating) { if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: ValueStoreCache#endDocument()"); } fValueStoreCache.endDocument(); } fDocumentHandler.endDocument(); } } /** Call XML declaration. */ public void callXMLDecl(int version, int encoding, int standalone) throws Exception { fDocumentHandler.xmlDecl(version, encoding, standalone); } public void callStandaloneIsYes() throws Exception { // standalone = "yes". said XMLDocumentScanner. fStandaloneReader = fEntityHandler.getReaderId() ; } /** Call text declaration. */ public void callTextDecl(int version, int encoding) throws Exception { fDocumentHandler.textDecl(version, encoding); } /** * Signal the scanning of an element name in a start element tag. * * @param element Element name scanned. */ public void element(QName element) throws Exception { fAttrListHandle = -1; } /** * Signal the scanning of an attribute associated to the previous * start element tag. * * @param element Element name scanned. * @param attrName Attribute name scanned. * @param attrValue The string pool index of the attribute value. */ public boolean attribute(QName element, QName attrName, int attrValue) throws Exception { if (fAttrListHandle == -1) { fAttrListHandle = fAttrList.startAttrList(); } // if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element. // specified: true, search : true return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1; } /** Call start element. */ public void callStartElement(QName element) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart)); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) report error for PROHIBITED attrs that are present (V_TAGc) // (3) add default attrs (FIXED and NOT_FIXED) if (!fSeenRootElement) { fSeenRootElement = true; rootElementSpecified(element); fStringPool.resetShuffleCount(); } if (fGrammar != null && fGrammarIsDTDGrammar) { fAttrListHandle = addDTDDefaultAttributes(element, fAttrList, fAttrListHandle, fValidating, fStandaloneReader != -1); } fCheckedForSchema = true; if (fNamespacesEnabled) { bindNamespacesToElementAndAttributes(element, fAttrList); } validateElementAndAttributes(element, fAttrList); if (fAttrListHandle != -1) { fAttrList.endAttrList(); } // activate identity constraints if (fValidating && fGrammar != null) { if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: pushing context - element: "+fStringPool.toString(element.rawname)); } fValueStoreCache.startElement(); fMatcherStack.pushContext(); int eindex = fGrammar.getElementDeclIndex(element, -1); if (eindex != -1) { fGrammar.getElementDecl(eindex, fTempElementDecl); fValueStoreCache.initValueStoresFor(fTempElementDecl); int uCount = fTempElementDecl.unique.size(); for (int i = 0; i < uCount; i++) { activateSelectorFor((IdentityConstraint)fTempElementDecl.unique.elementAt(i)); } int kCount = fTempElementDecl.key.size(); for (int i = 0; i < kCount; i++) { activateSelectorFor((IdentityConstraint)fTempElementDecl.key.elementAt(i)); } int krCount = fTempElementDecl.keyRef.size(); for (int i = 0; i < krCount; i++) { activateSelectorFor((IdentityConstraint)fTempElementDecl.keyRef.elementAt(i)); } } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher.toString()+"#startElement("+fStringPool.toString(element.rawname)+")"); } matcher.startElement(element, fAttrList, fAttrListHandle, fCurrentElementIndex, (SchemaGrammar)fGrammar); } } // call handler fDocumentHandler.startElement(element, fAttrList, fAttrListHandle); fElementDepth++; fAttrListHandle = -1; //if (fElementDepth >= 0) { // REVISIT: Why are doing anything if the grammar is null? -Ac if (fValidating) { // push current length onto stack if (fElementChildrenOffsetStack.length <= fElementDepth) { int newarray[] = new int[fElementChildrenOffsetStack.length * 2]; System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length); fElementChildrenOffsetStack = newarray; } fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength; // add this element to children if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildrenLength * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.setValues(element); fElementChildrenLength++; if (DEBUG_ELEMENT_CHILDREN) { printChildren(); printStack(); } } ensureStackCapacity(fElementDepth); fCurrentElement.setValues(element); fCurrentElementEntity = fEntityHandler.getReaderId(); fElementQNamePartsStack[fElementDepth].setValues(fCurrentElement); fElementEntityStack[fElementDepth] = fCurrentElementEntity; fElementIndexStack[fElementDepth] = fCurrentElementIndex; fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType; if (fNeedValidationOff) { fValidating = false; fNeedValidationOff = false; } if (fValidating && fGrammarIsSchemaGrammar) { pushContentLeafStack(); } fValidationFlagStack[fElementDepth] = fValidating ? 0 : -1; fScopeStack[fElementDepth] = fCurrentScope; fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex; } // callStartElement(QName) private void activateSelectorFor(IdentityConstraint ic) throws Exception { Selector selector = ic.getSelector(); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: XMLValidator#activateSelectorFor("+selector+')'); } FieldActivator activator = this; if(selector == null) return; XPathMatcher matcher = selector.createMatcher(activator); fMatcherStack.addMatcher(matcher); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher+"#startDocumentFragment()"); } matcher.startDocumentFragment(fStringPool); } private void pushContentLeafStack() throws Exception { int contentType = getContentSpecType(fCurrentElementIndex); if ( contentType == XMLElementDecl.TYPE_CHILDREN || contentType == XMLElementDecl.TYPE_MIXED_COMPLEX) { XMLContentModel cm = getElementContentModel(fCurrentElementIndex); ContentLeafNameTypeVector cv = cm.getContentLeafNameTypeVector(); if (cm != null) { fContentLeafStack[fElementDepth] = cv; } } } private void ensureStackCapacity ( int newElementDepth) { if (newElementDepth == fElementQNamePartsStack.length ) { int[] newStack = new int[newElementDepth * 2]; System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth); fScopeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth); fGrammarNameSpaceIndexStack = newStack; QName[] newStackOfQueue = new QName[newElementDepth * 2]; System.arraycopy(this.fElementQNamePartsStack, 0, newStackOfQueue, 0, newElementDepth ); fElementQNamePartsStack = newStackOfQueue; QName qname = fElementQNamePartsStack[newElementDepth]; if (qname == null) { for (int i = newElementDepth; i < fElementQNamePartsStack.length; i++) { fElementQNamePartsStack[i] = new QName(); } } newStack = new int[newElementDepth * 2]; System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth); fElementEntityStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth); fElementIndexStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth); fContentSpecTypeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fValidationFlagStack, 0, newStack, 0, newElementDepth); fValidationFlagStack = newStack; ContentLeafNameTypeVector[] newStackV = new ContentLeafNameTypeVector[newElementDepth * 2]; System.arraycopy(fContentLeafStack, 0, newStackV, 0, newElementDepth); fContentLeafStack = newStackV; } } /** Call end element. */ public void callEndElement(int readerId) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n"); int prefixIndex = fCurrentElement.prefix; int elementType = fCurrentElement.rawname; if (fCurrentElementEntity != readerId) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH, XMLMessages.P78_NOT_WELLFORMED, new Object[] { fStringPool.toString(elementType)}, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } fElementDepth if (fValidating) { int elementIndex = fCurrentElementIndex; if (elementIndex != -1 && fCurrentContentSpecType != -1) { QName children[] = fElementChildren; int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1; int childrenLength = fElementChildrenLength - childrenOffset; if (DEBUG_ELEMENT_CHILDREN) { System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')'); System.out.println("fCurrentContentSpecType : " + fCurrentContentSpecType ); System.out.print("offset: "); System.out.print(childrenOffset); System.out.print(", length: "); System.out.print(childrenLength); System.out.println(); printChildren(); printStack(); } int result = checkContent(elementIndex, children, childrenOffset, childrenLength); if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result); if (result != -1) { int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE; fGrammar.getElementDecl(elementIndex, fTempElementDecl); if (fTempElementDecl.type == XMLElementDecl.TYPE_EMPTY) { reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), "EMPTY"); } else reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex)); } } fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1; // call matchers and de-activate context int oldCount = fMatcherStack.getMatcherCount(); for (int i = oldCount - 1; i >= 0; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher+"#endElement("+fStringPool.toString(fCurrentElement.rawname)+")"); } matcher.endElement(fCurrentElement, fCurrentElementIndex, (SchemaGrammar)fGrammar); } if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: popping context - element: "+fStringPool.toString(fCurrentElement.rawname)); } if (fMatcherStack.size() > 0) { fMatcherStack.popContext(); } int newCount = fMatcherStack.getMatcherCount(); // handle everything *but* keyref's. for (int i = oldCount - 1; i >= newCount; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); IdentityConstraint id; if((id = matcher.getIDConstraint()) != null && id.getType() != IdentityConstraint.KEYREF) { if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher+"#endDocumentFragment()"); } matcher.endDocumentFragment(); fValueStoreCache.transplant(id); } else if (id == null) matcher.endDocumentFragment(); } // now handle keyref's/... for (int i = oldCount - 1; i >= newCount; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); IdentityConstraint id; if((id = matcher.getIDConstraint()) != null && id.getType() == IdentityConstraint.KEYREF) { if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher+"#endDocumentFragment()"); } ValueStoreBase values = fValueStoreCache.getValueStoreFor(id); if(values != null) // nothing to do if nothing matched! values.endDocumentFragment(); matcher.endDocumentFragment(); } } fValueStoreCache.endElement(); } fDocumentHandler.endElement(fCurrentElement); if (fNamespacesEnabled) { fNamespacesScope.decreaseDepth(); } // now pop this element off the top of the element stack //if (fElementDepth-- < 0) { if (fElementDepth < -1) { throw new RuntimeException("FWK008 Element stack underflow"); } if (fElementDepth < 0) { fCurrentElement.clear(); fCurrentElementEntity = -1; fCurrentElementIndex = -1; fCurrentContentSpecType = -1; fInElementContent = false; // Check after document is fully parsed // (1) check that there was an element with a matching id for every // IDREF and IDREFS attr (V_IDREF0) if (fValidating ) { try { this.fValIDRef.validate( null, this.fStoreIDRef ); //Store the ID list this.fValIDRefs.validate( null, this.fStoreIDRef ); this.fValIDRef.validate( null, this.fValidateIDRef ); //Do final IDREF validation round this.fValIDRefs.validate( null, this.fValidateIDRef ); this.fValID.validate( null, this.fResetID );//Reset ID, IDREF, IDREFS validators here this.fValIDRef.validate(null, this.fResetIDRef ); this.fValIDRefs.validate(null, this.fResetID ); } catch ( InvalidDatatypeValueException ex ) { reportRecoverableXMLError( ex.getMajorCode(), ex.getMinorCode(), ex.getMessage() ); } } return; } //restore enclosing element to all the "current" variables // REVISIT: Validation. This information needs to be stored. fCurrentElement.prefix = -1; if (fNamespacesEnabled) { //If Namespace enable then localName != rawName fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].localpart; } else {//REVISIT - jeffreyr - This is so we still do old behavior when namespace is off fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].rawname; } fCurrentElement.rawname = fElementQNamePartsStack[fElementDepth].rawname; fCurrentElement.uri = fElementQNamePartsStack[fElementDepth].uri; fCurrentElement.prefix = fElementQNamePartsStack[fElementDepth].prefix; fCurrentElementEntity = fElementEntityStack[fElementDepth]; fCurrentElementIndex = fElementIndexStack[fElementDepth]; fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth]; fValidating = fValidationFlagStack[fElementDepth] == 0 ? true : false; fCurrentScope = fScopeStack[fElementDepth]; if ( DEBUG_SCHEMA_VALIDATION ) { System.out.println("+++++ currentElement : " + fStringPool.toString(elementType)+ "\n fCurrentElementIndex : " + fCurrentElementIndex + "\n fCurrentScope : " + fCurrentScope + "\n fCurrentContentSpecType : " + fCurrentContentSpecType + "\n++++++++++++++++++++++++++++++++++++++++++++++++" ); } // if enclosing element's Schema is different, need to switch "context" if ( fGrammarNameSpaceIndex != fGrammarNameSpaceIndexStack[fElementDepth] ) { fGrammarNameSpaceIndex = fGrammarNameSpaceIndexStack[fElementDepth]; if ( fValidating && fGrammarIsSchemaGrammar ) if (fGrammarNameSpaceIndex < StringPool.EMPTY_STRING) { fGrammar = null; fGrammarIsSchemaGrammar = false; fGrammarIsDTDGrammar = false; } else if (!switchGrammar(fGrammarNameSpaceIndex)) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Grammar with uri 1: " + fStringPool.toString(fGrammarNameSpaceIndex) + " , can not be found"); } } if (fValidating) { fBufferDatatype = false; } fInElementContent = (fCurrentContentSpecType == XMLElementDecl.TYPE_CHILDREN); } // callEndElement(int) /** Call start CDATA section. */ public void callStartCDATA() throws Exception { if (fValidating && fInElementContent) { charDataInContent(); } fDocumentHandler.startCDATA(); } /** Call end CDATA section. */ public void callEndCDATA() throws Exception { fDocumentHandler.endCDATA(); } /** Call characters. */ public void callCharacters(int ch) throws Exception { if (fCharRefData == null) { fCharRefData = new char[2]; } int count = (ch < 0x10000) ? 1 : 2; if (count == 1) { fCharRefData[0] = (char)ch; } else { fCharRefData[0] = (char)(((ch-0x00010000)>>10)+0xd800); fCharRefData[1] = (char)(((ch-0x00010000)&0x3ff)+0xdc00); } if (fValidating && (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY)) { charDataInContent(); } if (fValidating) { if (fBufferDatatype) { fDatatypeBuffer.append(fCharRefData,0,1); } } if (fSendCharDataAsCharArray) { fDocumentHandler.characters(fCharRefData, 0, count); } else { int index = fStringPool.addString(new String(fCharRefData, 0, count)); fDocumentHandler.characters(index); } // call all active identity constraints int matcherCount = fMatcherStack.getMatcherCount(); for (int i = 0; i < matcherCount; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { String text = new String(fCharRefData, 0, count); System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(fCharRefData, 0, count); } } // callCharacters(int) /** Call processing instruction. */ public void callProcessingInstruction(int target, int data) throws Exception { fDocumentHandler.processingInstruction(target, data); } /** Call comment. */ public void callComment(int comment) throws Exception { fDocumentHandler.comment(comment); } // NamespacesScope.NamespacesHandler methods /** Start a new namespace declaration scope. */ public void startNamespaceDeclScope(int prefix, int uri) throws Exception { fDocumentHandler.startNamespaceDeclScope(prefix, uri); } /** End a namespace declaration scope. */ public void endNamespaceDeclScope(int prefix) throws Exception { fDocumentHandler.endNamespaceDeclScope(prefix); } // attributes // other /** Sets the root element. */ public void setRootElementType(QName rootElement) { fRootElement.setValues(rootElement); } /** * Returns true if the element declaration is external. * <p> * <strong>Note:</strong> This method is primarilly useful for * DTDs with internal and external subsets. */ private boolean getElementDeclIsExternal(int elementIndex) { /*if (elementIndex < 0 || elementIndex >= fElementCount) { return false; } int chunk = elementIndex >> CHUNK_SHIFT; int index = elementIndex & CHUNK_MASK; return (fElementDeclIsExternal[chunk][index] != 0); */ if (fGrammarIsDTDGrammar ) { return((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex); } return false; } /** Returns the content spec type for an element index. */ public int getContentSpecType(int elementIndex) { int contentSpecType = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecType = fTempElementDecl.type; } } return contentSpecType; } /** Returns the content spec handle for an element index. */ public int getContentSpecHandle(int elementIndex) { int contentSpecHandle = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecHandle = fTempElementDecl.contentSpecIndex; } } return contentSpecHandle; } // Protected methods // error reporting /** Report a recoverable schema error. */ private void reportSchemaError(int code, Object[] args) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, code, SchemaMessageProvider.MSG_NONE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportSchemaError(int,Object) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, null, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception { Object[] args = { fStringPool.toString(stringIndex1)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1) throws Exception { Object[] args = { string1}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception { Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception { Object[] args = { string1, string2}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception { Object[] args = { string1, string2, string3}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String,String) // content spec protected int whatCanGoHere(int elementIndex, boolean fullyValid, InsertableElementsInfo info) throws Exception { // Do some basic sanity checking on the info packet. First, make sure // that insertAt is not greater than the child count. It can be equal, // which means to get appendable elements, but not greater. Or, if // the current children array is null, that's bad too. // Since the current children array must have a blank spot for where // the insert is going to be, the child count must always be at least // one. // Make sure that the child count is not larger than the current children // array. It can be equal, which means get appendable elements, but not // greater. if (info.insertAt > info.childCount || info.curChildren == null || info.childCount < 1 || info.childCount > info.curChildren.length) { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_WCGHI, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } int retVal = 0; try { // Get the content model for this element final XMLContentModel cmElem = getElementContentModel(elementIndex); // And delegate this call to it retVal = cmElem.whatCanGoHere(fullyValid, info); } catch (CMException excToCatch) { // REVISIT - Translate caught error to the protected error handler interface int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); throw excToCatch; } return retVal; } // whatCanGoHere(int,boolean,InsertableElementsInfo):int // attribute information /** Protected for use by AttributeValidator classes. */ protected boolean getAttDefIsExternal(QName element, QName attribute) { int attDefIndex = getAttDef(element, attribute); if (fGrammarIsDTDGrammar ) { return((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex); } return false; } // Private methods // other /** Returns true if using a standalone reader. */ private boolean usingStandaloneReader() { return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader; } /** Returns a locator implementation. */ private LocatorImpl getLocatorImpl(LocatorImpl fillin) { Locator here = fErrorReporter.getLocator(); if (fillin == null) return new LocatorImpl(here); fillin.setPublicId(here.getPublicId()); fillin.setSystemId(here.getSystemId()); fillin.setLineNumber(here.getLineNumber()); fillin.setColumnNumber(here.getColumnNumber()); return fillin; } // getLocatorImpl(LocatorImpl):LocatorImpl // initialization /** Reset pool. */ private void poolReset() { if (fValidating) { try { this.fValID.validate( null, this.fResetID ); this.fValIDRef.validate(null, this.fResetIDRef ); this.fValIDRefs.validate(null, this.fResetIDRef ); } catch (InvalidDatatypeValueException ex) { //should use error reporter System.err.println("Error re-Initializing: ID,IDRef,IDRefs pools" ); } } } // poolReset() /** Reset common. */ private void resetCommon(StringPool stringPool) throws Exception { fStringPool = stringPool; fValidating = fValidationEnabled; fValidationEnabledByDynamic = false; fDynamicDisabledByValidation = false; poolReset(); fCalledStartDocument = false; fStandaloneReader = -1; fElementChildrenLength = 0; fElementDepth = -1; fSeenRootElement = false; fSeenDoctypeDecl = false; fNamespacesScope = null; fNamespacesPrefix = -1; fRootElement.clear(); fAttrListHandle = -1; fCheckedForSchema = false; fCurrentScope = TOP_LEVEL_SCOPE; fCurrentSchemaURI = StringPool.EMPTY_STRING; fEmptyURI = StringPool.EMPTY_STRING; fXsiPrefix = - 1; fXsiTypeValidator = null; // xsi:nill fNil = false; fGrammar = null; fGrammarNameSpaceIndex = StringPool.EMPTY_STRING; // we will reset fGrammarResolver in XMLParser before passing it to Validator /*if (fGrammarResolver != null) { fGrammarResolver.clearGrammarResolver(); //This also clears the Datatype registry }*/ fGrammarIsDTDGrammar = false; fGrammarIsSchemaGrammar = false; //Normalization fCurrentDV = null; fFirstChunk = true; fTrailing = false; fWhiteSpace = DatatypeValidator.COLLAPSE; fMatcherStack.clear(); init(); } // resetCommon(StringPool) /** Initialize. */ private void init() { fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); fEMPTYSymbol = fStringPool.addSymbol("EMPTY"); fANYSymbol = fStringPool.addSymbol("ANY"); fMIXEDSymbol = fStringPool.addSymbol("MIXED"); fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN"); fCDATASymbol = fStringPool.addSymbol("CDATA"); fIDSymbol = fStringPool.addSymbol("ID"); fIDREFSymbol = fStringPool.addSymbol("IDREF"); fIDREFSSymbol = fStringPool.addSymbol("IDREFS"); fENTITYSymbol = fStringPool.addSymbol("ENTITY"); fENTITIESSymbol = fStringPool.addSymbol("ENTITIES"); fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN"); fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS"); fNOTATIONSymbol = fStringPool.addSymbol("NOTATION"); fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION"); fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED"); fFIXEDSymbol = fStringPool.addSymbol("#FIXED"); fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>"); fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>"); fXMLLang = fStringPool.addSymbol("xml:lang"); //optimization - must be called ONLY if validation is turned off. -el //initDataTypeValidators(); } // init() /** * This method should only be invoked when validation * is turn on. * fDataTypeReg object of type DatatypeValidatorFactoryImpl * needs to be initialized. * In the XMLValidator the table will be by default * first initialized to 9 validators used by DTD * validation. * These Validators are known. * Later on if we ever find a Schema and need to do * Schema validation then we will expand this * registry table of fDataTypeReg. */ private void initDataTypeValidators() { try { //Initialize Validators //Datatype Registry if ( fGrammarResolver != null ) { fDataTypeReg = (DatatypeValidatorFactoryImpl) fGrammarResolver.getDatatypeRegistry(); fDataTypeReg.initializeDTDRegistry(); } if ( fDataTypeReg != null ) { fValID = fDataTypeReg.getDatatypeValidator("ID" ); fValIDRef = fDataTypeReg.getDatatypeValidator("IDREF" ); fValIDRefs = fDataTypeReg.getDatatypeValidator("IDREFS" ); fValENTITY = fDataTypeReg.getDatatypeValidator("ENTITY" ); fValENTITIES = fDataTypeReg.getDatatypeValidator("ENTITIES" ); fValNMTOKEN = fDataTypeReg.getDatatypeValidator("NMTOKEN"); fValNMTOKENS = fDataTypeReg.getDatatypeValidator("NMTOKENS"); fValNOTATION = fDataTypeReg.getDatatypeValidator("NOTATION" ); //Initialize ENTITY & ENTITIES Validatorh Object[] packageArgsEntityVal = { (Object) this.fEntityHandler, (Object) this.fStringPool}; fValidateENTITYMsg.setDatatypeObject( (Object ) packageArgsEntityVal); fValENTITY.validate( null, fValidateENTITYMsg ); fValENTITIES.validate( null, fValidateENTITYMsg ); } } catch ( InvalidDatatypeValueException ex ) { System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen } } // other // default attribute /** addDefaultAttributes. */ private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception { //System.out.println("XMLValidator#addDefaultAttributes"); //System.out.print(" "); //fGrammar.printAttributes(elementIndex); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) report error for PROHIBITED attrs that are present (V_TAGc) // (3) check that FIXED attrs have matching value (V_TAGd) // (4) add default attrs (FIXED and NOT_FIXED) fGrammar.getElementDecl(elementIndex,fTempElementDecl); int elementNameIndex = fTempElementDecl.name.localpart; int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); int firstCheck = attrIndex; int lastCheck = -1; while (attlistIndex != -1) { fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl); int attPrefix = fTempAttDecl.name.prefix; int attName = fTempAttDecl.name.localpart; int attType = attributeTypeName(fTempAttDecl); int attDefType =fTempAttDecl.defaultType; int attValue = -1 ; if (fTempAttDecl.defaultValue != null ) { attValue = fStringPool.addSymbol(fTempAttDecl.defaultValue); } boolean specified = false; boolean required = (attDefType & XMLAttributeDecl.DEFAULT_TYPE_REQUIRED) > 0; boolean prohibited = (attDefType & XMLAttributeDecl.DEFAULT_TYPE_PROHIBITED) > 0; boolean fixed = (attDefType & XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0; if (firstCheck != -1) { boolean cdata = attType == fCDATASymbol; if (!cdata || required || prohibited || attValue != -1) { int i = attrList.getFirstAttr(firstCheck); while (i != -1 && (lastCheck == -1 || i <= lastCheck)) { if ( (fGrammarIsDTDGrammar && (attrList.getAttrName(i) == fTempAttDecl.name.rawname)) || ( fStringPool.equalNames(attrList.getAttrLocalpart(i), attName) && fStringPool.equalNames(attrList.getAttrURI(i), fTempAttDecl.name.uri) ) ) { if (prohibited && validationEnabled) { Object[] args = { fStringPool.toString(elementNameIndex), fStringPool.toString(attName)}; fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.ProhibitedAttributePresent, SchemaMessageProvider.MSG_NONE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } if (validationEnabled && fixed) { int alistValue = attrList.getAttValue(i); if (alistValue != attValue && !fStringPool.toString(alistValue).equals(fStringPool.toString(attValue))) { Object[] args = { fStringPool.toString(elementNameIndex), fStringPool.toString(attName), fStringPool.toString(alistValue), fStringPool.toString(attValue)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_FIXED_ATTVALUE_INVALID, XMLMessages.VC_FIXED_ATTRIBUTE_DEFAULT, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } specified = true; break; } i = attrList.getNextAttr(i); } } } if (!specified) { if (required) { if (validationEnabled) { Object[] args = { fStringPool.toString(elementNameIndex), fStringPool.toString(attName)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_REQUIRED_ATTRIBUTE_NOT_SPECIFIED, XMLMessages.VC_REQUIRED_ATTRIBUTE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } else if (attValue != -1) { if (validationEnabled && standalone ) { if ( fGrammarIsDTDGrammar && ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attlistIndex) ) { Object[] args = { fStringPool.toString(elementNameIndex), fStringPool.toString(attName)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_DEFAULTED_ATTRIBUTE_NOT_SPECIFIED, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } if (validationEnabled) { if (attType == fIDREFSymbol) { this.fValIDRef.validate( fStringPool.toString(attValue), null ); } else if (attType == fIDREFSSymbol) { this.fValIDRefs.validate( fStringPool.toString(attValue), null ); } } if (attrIndex == -1) { attrIndex = attrList.startAttrList(); } // REVISIT: Validation. What should the prefix be? fTempQName.setValues(attPrefix, attName, attName, fTempAttDecl.name.uri); int newAttr = attrList.addAttr(fTempQName, attValue, attType, false, false); if (lastCheck == -1) { lastCheck = newAttr; } } } attlistIndex = fGrammar.getNextAttributeDeclIndex(attlistIndex); } return attrIndex; } // addDefaultAttributes(int,XMLAttrList,int,boolean,boolean):int /** addDTDDefaultAttributes. */ private int addDTDDefaultAttributes(QName element, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception { // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) check that FIXED attrs have matching value (V_TAGd) // (3) add default attrs (FIXED and NOT_FIXED) int elementIndex = fGrammar.getElementDeclIndex(element, -1); if (elementIndex == -1) { return attrIndex; } fGrammar.getElementDecl(elementIndex,fTempElementDecl); int elementNameIndex = fTempElementDecl.name.rawname; int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); int firstCheck = attrIndex; int lastCheck = -1; while (attlistIndex != -1) { fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl); // TO DO: For ericye Debug only /** Queries the content model for the specified element index. */ /** Returns an attribute definition for an element type. */ /** Returns an attribute definition for an element type. */ /** Root element specified. */ /** Switchs to correct validating symbol tables when Schema changes.*/ /** Binds namespaces to the element and attributes. */ /* * for <notation> must resolve values "b:myNotation" * * @param value string value of element or attribute * @return * @exception Exception */ private String bindNotationURI (String value) throws Exception{ int colonP = value.indexOf(":"); String prefix = ""; String localpart = value; if (colonP > -1) { prefix = value.substring(0,colonP); localpart = value.substring(colonP+1); } String uri = ""; int uriIndex = StringPool.EMPTY_STRING; if (fNamespacesScope != null) { //if prefix.equals("") it would bing to xmlns URI uriIndex = fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix)); if (uriIndex > 0) { return fStringPool.toString(uriIndex)+":"+localpart; } else if (fGrammarNameSpaceIndex!=-1){ // REVISIT: try binding to current namespace // trying to solve the case: // might not work in all cases (need clarification from schema?) return fStringPool.toString( fGrammarNameSpaceIndex)+":"+localpart; } } return value; } static class Resolver implements EntityResolver { // Constants private static final String SYSTEM[] = { "http: "http: "http: }; private static final String PATH[] = { "structures.dtd", "datatypes.dtd", "versionInfo.ent", }; // Data private DefaultEntityHandler fEntityHandler; // Constructors public Resolver(DefaultEntityHandler handler) { fEntityHandler = handler; } // EntityResolver methods public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException { // looking for the schema DTDs? for (int i = 0; i < SYSTEM.length; i++) { if (systemId.equals(SYSTEM[i])) { InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i])); source.setPublicId(publicId); source.setSystemId(systemId); return source; } } // first try to resolve using user's entity resolver EntityResolver resolver = fEntityHandler.getEntityResolver(); if (resolver != null) { InputSource source = resolver.resolveEntity(publicId, systemId); if (source != null) { return source; } } // use default resolution return new InputSource(fEntityHandler.expandSystemId(systemId)); } // resolveEntity(String,String):InputSource } // class Resolver static class ErrorHandler implements org.xml.sax.ErrorHandler { /** Warning. */ public void warning(SAXParseException ex) { System.err.println("[Warning] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Error. */ public void error(SAXParseException ex) { System.err.println("[Error] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Fatal error. */ public void fatalError(SAXParseException ex) { System.err.println("[Fatal Error] "+ getLocationString(ex)+": "+ ex.getMessage()); //throw ex; } // Private methods /** Returns a string of the location. */ private String getLocationString(SAXParseException ex) { StringBuffer str = new StringBuffer(); String systemId_ = ex.getSystemId(); if (systemId_ != null) { int index = systemId_.lastIndexOf('/'); if (index != -1) systemId_ = systemId_.substring(index + 1); str.append(systemId_); } str.append(':'); str.append(ex.getLineNumber()); str.append(':'); str.append(ex.getColumnNumber()); return str.toString(); } // getLocationString(SAXParseException):String } private int attributeTypeName(XMLAttributeDecl attrDecl) { switch (attrDecl.type) { case XMLAttributeDecl.TYPE_ENTITY: { return attrDecl.list ? fENTITIESSymbol : fENTITYSymbol; } case XMLAttributeDecl.TYPE_ENUMERATION: { String enumeration = fStringPool.stringListAsString(attrDecl.enumeration); return fStringPool.addSymbol(enumeration); } case XMLAttributeDecl.TYPE_ID: { return fIDSymbol; } case XMLAttributeDecl.TYPE_IDREF: { return attrDecl.list ? fIDREFSSymbol : fIDREFSymbol; } case XMLAttributeDecl.TYPE_NMTOKEN: { return attrDecl.list ? fNMTOKENSSymbol : fNMTOKENSSymbol; } case XMLAttributeDecl.TYPE_NOTATION: { return fNOTATIONSymbol; } } return fCDATASymbol; } /** Validates element and attributes. */ private void validateElementAndAttributes(QName element, XMLAttrList attrList) throws Exception { if ((fGrammarIsSchemaGrammar && fElementDepth >= 0 && fValidationFlagStack[fElementDepth] != 0 )|| (fGrammar == null && !fValidating && !fNamespacesEnabled) ) { fCurrentElementIndex = -1; fCurrentContentSpecType = -1; fInElementContent = false; if (fAttrListHandle != -1) { fAttrList.endAttrList(); int index = fAttrList.getFirstAttr(fAttrListHandle); while (index != -1) { if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) { fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index)); break; } index = fAttrList.getNextAttr(index); } } return; } int elementIndex = -1; int contentSpecType = -1; boolean skipThisOne = false; boolean laxThisOne = false; if ( fGrammarIsSchemaGrammar && fElementDepth > -1 && fContentLeafStack[fElementDepth] != null ) { ContentLeafNameTypeVector cv = fContentLeafStack[fElementDepth]; QName[] fElemMap = cv.leafNames; for (int i=0; i<cv.leafCount; i++) { int type = cv.leafTypes[i] ; if (type == XMLContentSpec.CONTENTSPECNODE_LEAF) { if (fElemMap[i].uri==element.uri && fElemMap[i].localpart == element.localpart) break; } else if (type == XMLContentSpec.CONTENTSPECNODE_ANY) { int uri = fElemMap[i].uri; if (uri == StringPool.EMPTY_STRING || uri == element.uri) { break; } } else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL) { if (element.uri == StringPool.EMPTY_STRING) { break; } } else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) { if (fElemMap[i].uri != element.uri) { break; } } else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_SKIP) { int uri = fElemMap[i].uri; if (uri == StringPool.EMPTY_STRING || uri == element.uri) { skipThisOne = true; break; } } else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_SKIP) { if (element.uri == StringPool.EMPTY_STRING) { skipThisOne = true; break; } } else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP) { if (fElemMap[i].uri != element.uri) { skipThisOne = true; break; } } else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LAX) { int uri = fElemMap[i].uri; if (uri == StringPool.EMPTY_STRING || uri == element.uri) { laxThisOne = true; break; } } else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_LAX) { if (element.uri == StringPool.EMPTY_STRING) { laxThisOne = true; break; } } else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX) { if (fElemMap[i].uri != element.uri) { laxThisOne = true; break; } } } } if (skipThisOne) { fNeedValidationOff = true; } else { //REVISIT: is this the right place to check on if the Schema has changed? if ( fNamespacesEnabled && fValidating && element.uri != fGrammarNameSpaceIndex && element.uri != StringPool.EMPTY_STRING) { fGrammarNameSpaceIndex = element.uri; boolean success = switchGrammar(fGrammarNameSpaceIndex); if (!success && !laxThisOne) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Grammar with uri 2: " + fStringPool.toString(fGrammarNameSpaceIndex) + " , can not be found"); } } if ( fGrammar != null ) { if (DEBUG_SCHEMA_VALIDATION) { System.out.println("*******Lookup element: uri: " + fStringPool.toString(element.uri)+ " localpart: '" + fStringPool.toString(element.localpart) +"' and scope : " + fCurrentScope+"\n"); } elementIndex = fGrammar.getElementDeclIndex(element,fCurrentScope); if (elementIndex == -1 ) { elementIndex = fGrammar.getElementDeclIndex(element, TOP_LEVEL_SCOPE); } if (elementIndex == -1) { // if validating based on a Schema, try to resolve the element again by searching in its type's ancestor types if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) { TraverseSchema.ComplexTypeInfo baseTypeInfo = null; baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex); int aGrammarNSIndex = fGrammarNameSpaceIndex; while (baseTypeInfo != null) { elementIndex = fGrammar.getElementDeclIndex(element, baseTypeInfo.scopeDefined); if (elementIndex > -1 ) { //System.out.println("found element index for " + fStringPool.toString(element.localpart)); // update the current Grammar NS index if resolving element succeed. fGrammarNameSpaceIndex = aGrammarNSIndex; break; } baseTypeInfo = baseTypeInfo.baseComplexTypeInfo; if (baseTypeInfo != null) { String baseTName = baseTypeInfo.typeName; if (!baseTName.startsWith(" int comma = baseTName.indexOf(','); aGrammarNSIndex = fStringPool.addSymbol(baseTName.substring(0,comma).trim()); if (aGrammarNSIndex != fGrammarNameSpaceIndex) { if ( !switchGrammar(aGrammarNSIndex) ) { break; //exit the loop in this case } } } } } if (elementIndex == -1) { switchGrammar(fGrammarNameSpaceIndex); } } //if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN if ( element.uri == StringPool.EMPTY_STRING && elementIndex == -1 && fNamespacesScope != null && fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING) != StringPool.EMPTY_STRING ) { elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE); // REVISIT: // this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there // is a "noNamespaceSchemaLocation" specified, and element element.uri = StringPool.EMPTY_STRING; } if (elementIndex == -1) { if (laxThisOne) { fNeedValidationOff = true; } else if (DEBUG_SCHEMA_VALIDATION) System.out.println("!!! can not find elementDecl in the grammar, " + " the element localpart: " + element.localpart + "["+fStringPool.toString(element.localpart) +"]" + " the element uri: " + element.uri + "["+fStringPool.toString(element.uri) +"]" + " and the current enclosing scope: " + fCurrentScope ); } } if (DEBUG_SCHEMA_VALIDATION) { fGrammar.getElementDecl(elementIndex, fTempElementDecl); System.out.println("elementIndex: " + elementIndex+" \n and itsName : '" + fStringPool.toString(fTempElementDecl.name.localpart) +"' \n its ContentType:" + fTempElementDecl.type +"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n"+ " and the current enclosing scope: " + fCurrentScope); } } contentSpecType = getContentSpecType(elementIndex); if (fGrammarIsSchemaGrammar && elementIndex != -1) { // handle "xsi:type" right here if (fXsiTypeAttValue > -1) { String xsiType = fStringPool.toString(fXsiTypeAttValue); int colonP = xsiType.indexOf(":"); String prefix = ""; String localpart = xsiType; if (colonP > -1) { prefix = xsiType.substring(0,colonP); localpart = xsiType.substring(colonP+1); } String uri = ""; int uriIndex = StringPool.EMPTY_STRING; if (fNamespacesScope != null) { uriIndex = fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix)); if (uriIndex > 0) { uri = fStringPool.toString(uriIndex); if (uriIndex != fGrammarNameSpaceIndex) { fGrammarNameSpaceIndex = fCurrentSchemaURI = uriIndex; boolean success = switchGrammar(fCurrentSchemaURI); if (!success && !fNeedValidationOff) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Grammar with uri 3: " + fStringPool.toString(fCurrentSchemaURI) + " , can not be found"); } } } } Hashtable complexRegistry = ((SchemaGrammar)fGrammar).getComplexTypeRegistry(); DatatypeValidatorFactoryImpl dataTypeReg = ((SchemaGrammar)fGrammar).getDatatypeRegistry(); if (complexRegistry==null || dataTypeReg == null) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, fErrorReporter.getLocator().getSystemId() +" line"+fErrorReporter.getLocator().getLineNumber() +", canot resolve xsi:type = " + xsiType+" } else { TraverseSchema.ComplexTypeInfo typeInfo = (TraverseSchema.ComplexTypeInfo) complexRegistry.get(uri+","+localpart); if (typeInfo==null) { if (uri.length() == 0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) ) { fXsiTypeValidator = dataTypeReg.getDatatypeValidator(localpart); } else fXsiTypeValidator = dataTypeReg.getDatatypeValidator(uri+","+localpart); if ( fXsiTypeValidator == null ) reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "unresolved type : "+uri+","+localpart +" found in xsi:type handling"); else { // make sure the new type is related to the // type of the expected element XMLElementDecl tempElementDecl = new XMLElementDecl(); fGrammar.getElementDecl(elementIndex, tempElementDecl); DatatypeValidator ancestorValidator = tempElementDecl.datatypeValidator; DatatypeValidator tempVal = fXsiTypeValidator; for(; tempVal != null; tempVal = tempVal.getBaseValidator()) // WARNING!!! Comparison by reference. if(tempVal == ancestorValidator) break; if(tempVal == null) { // now if ancestorValidator is a union, then we must // look through its members to see whether we derive from any of them. if(ancestorValidator instanceof UnionDatatypeValidator) { // fXsiTypeValidator must derive from one of its members... Vector subUnionMemberDV = ((UnionDatatypeValidator)ancestorValidator).getBaseValidators(); int subUnionSize = subUnionMemberDV.size(); boolean found = false; for (int i=0; i<subUnionSize && !found; i++) { DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i); DatatypeValidator dTemp = fXsiTypeValidator; for(; dTemp != null; dTemp = dTemp.getBaseValidator()) { // WARNING!!! This uses comparison by reference andTemp is thus inherently suspect! if(dTempSub == dTemp) { found = true; break; } } } if(!found) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type : "+uri+","+localpart +" does not derive from the type of element " + fStringPool.toString(tempElementDecl.name.localpart)); } } else { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type : "+uri+","+localpart +" does not derive from the type of element " + fStringPool.toString(tempElementDecl.name.localpart)); } } else { // check if element has block set if((((SchemaGrammar)fGrammar).getElementDeclBlockSet(elementIndex) & SchemaSymbols.RESTRICTION) != 0) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Element " + fStringPool.toString(tempElementDecl.name.localpart) + "does not permit substitution by a type such as "+uri+","+localpart); } } } } else { // The type must not be abstract if (typeInfo.isAbstractType()) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Abstract type " + xsiType + " should not be used in xsi:type"); } // now we look at whether there is a type // relation and whether the type (and element) allow themselves to be substituted for. TraverseSchema.ComplexTypeInfo tempType = typeInfo; TraverseSchema.ComplexTypeInfo destType = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(elementIndex); for(; tempType != null; tempType = tempType.baseComplexTypeInfo) { if(tempType.typeName.equals(destType.typeName)) break; } if(tempType == null) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type : "+uri+","+localpart +" does not derive from the type " + destType.typeName); } else { // now check whether the element or typeInfo's baseType blocks us. int derivationMethod = typeInfo.derivedBy; if((((SchemaGrammar)fGrammar).getElementDeclBlockSet(elementIndex) & derivationMethod) != 0) { XMLElementDecl tempElementDecl = new XMLElementDecl(); fGrammar.getElementDecl(elementIndex, tempElementDecl); reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Element " + fStringPool.toString(tempElementDecl.name.localpart) + " does not permit xsi:type substitution in the manner required by type "+uri+","+localpart); } else if ((typeInfo.baseComplexTypeInfo.blockSet & derivationMethod) != 0) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type " + typeInfo.baseComplexTypeInfo.typeName + " does not permit other types, such as " +uri+","+localpart + " to be substituted for itself using xsi:type"); } } elementIndex = typeInfo.templateElementIndex; } } fXsiTypeAttValue = -1; } else { // xsi:type was not specified... // If the corresponding type is abstract, detect an error TraverseSchema.ComplexTypeInfo typeInfo = ((SchemaGrammar) fGrammar).getElementComplexTypeInfo(elementIndex); if (typeInfo != null && typeInfo.isAbstractType()) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Element " + fStringPool.toString(element.rawname) + " is declared with a type that is abstract. Use xsi:type to specify a non-abstract type"); } } // Check whether this element is abstract. If so, an error int miscFlags = ((SchemaGrammar) fGrammar).getElementDeclMiscFlags(elementIndex); if ((miscFlags & SchemaSymbols.ABSTRACT) != 0) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "A member of abstract element " + fStringPool.toString(element.rawname) + "'s substitution group must be specified"); } if (fNil && (miscFlags & SchemaSymbols.NILLABLE) == 0 ) { fNil = false; reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "xsi:nil must not be specified for the element "+ fStringPool.toString(element.rawname)+ " with {nillable} equals 'false'"); } //Change the current scope to be the one defined by this element. fCurrentScope = ((SchemaGrammar) fGrammar).getElementDefinedScope(elementIndex); // here need to check if we need to switch Grammar by asking SchemaGrammar whether // this element actually is of a type in another Schema. String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex); if (anotherSchemaURI != null) { //before switch Grammar, set the elementIndex to be the template elementIndex of its type // but if the content type is empty, we don't bother switching the grammar. if (contentSpecType != -1 && contentSpecType != XMLElementDecl.TYPE_EMPTY ) { TraverseSchema.ComplexTypeInfo typeInfo = ((SchemaGrammar) fGrammar).getElementComplexTypeInfo(elementIndex); if (typeInfo != null) { elementIndex = typeInfo.templateElementIndex; } } // now switch the grammar fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI); boolean success = switchGrammar(fCurrentSchemaURI); if (!success && !fNeedValidationOff) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Grammar with uri 4: " + fStringPool.toString(fCurrentSchemaURI) + " , can not be found"); } } } // since the elementIndex could change since last time we query the content type, so do it again. contentSpecType = getContentSpecType(elementIndex); if (contentSpecType == -1 && fValidating && !fNeedValidationOff ) { reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED, XMLMessages.VC_ELEMENT_VALID, element.rawname); } if (fGrammar != null && fGrammarIsSchemaGrammar && elementIndex != -1) { fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1); } if (fAttrListHandle != -1) { fAttrList.endAttrList(); } if (DEBUG_PRINT_ATTRIBUTES) { String elementStr = fStringPool.toString(element.rawname); System.out.print("startElement: <" + elementStr); if (fAttrListHandle != -1) { int index = attrList.getFirstAttr(fAttrListHandle); while (index != -1) { System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" + fStringPool.toString(attrList.getAttValue(index)) + "\""); index = attrList.getNextAttr(index); } } System.out.println(">"); } // REVISIT: Validation. Do we need to recheck for the xml:lang // attribute? It was already checked above -- perhaps // this is to check values that are defaulted in? If // so, this check could move to the attribute decl // callback so we can check the default value before // it is used. if (fAttrListHandle != -1 && !fNeedValidationOff ) { int index = fAttrList.getFirstAttr(fAttrListHandle); while (index != -1) { int attrNameIndex = attrList.getAttrName(index); if (fStringPool.equalNames(attrNameIndex, fXMLLang)) { fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index)); // break; } // here, we validate every "user-defined" attributes int _xmlns = fStringPool.addSymbol("xmlns"); if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns) if (fGrammar != null) { fTempQName.setValues(attrList.getAttrPrefix(index), attrList.getAttrLocalpart(index), attrList.getAttrName(index), attrList.getAttrURI(index) ); int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName); if (fTempQName.uri != fXsiURI) if (attDefIndex == -1 ) { if (fValidating) { // REVISIT - cache the elem/attr tuple so that we only give // this error once for each unique occurrence Object[] args = { fStringPool.toString(element.rawname), fStringPool.toString(attrList.getAttrName(index))}; fAttrNameLocator = getLocatorImpl(fAttrNameLocator); fErrorReporter.reportError(fAttrNameLocator, XMLMessages.XML_DOMAIN, XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED, XMLMessages.VC_ATTRIBUTE_VALUE_TYPE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } else { fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl); int attributeType = attributeTypeName(fTempAttDecl); attrList.setAttType(index, attributeType); if (fValidating) { if (fGrammarIsDTDGrammar) { int normalizedValue = validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl); attrList.setAttValue(index, normalizedValue); } // check to see if this attribute matched an attribute wildcard else if ( fGrammarIsSchemaGrammar && (fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_ANY ||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LIST ||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER) ) { if ((fTempAttDecl.defaultType & XMLAttributeDecl.PROCESSCONTENTS_SKIP) > 0) { // attribute should just be bypassed, } else if ( (fTempAttDecl.defaultType & XMLAttributeDecl.PROCESSCONTENTS_STRICT) > 0 || (fTempAttDecl.defaultType & XMLAttributeDecl.PROCESSCONTENTS_LAX) > 0) { boolean reportError = false; boolean processContentStrict = (fTempAttDecl.defaultType & XMLAttributeDecl.PROCESSCONTENTS_STRICT) > 0; // ??? REVISIT: can't tell whether it's a local attribute // or a global one with empty namespace //if (fTempQName.uri == StringPool.EMPTY_STRING) { // if (processContentStrict) { // reportError = true; //} else { { Grammar aGrammar = fGrammarResolver.getGrammar(fStringPool.toString(fTempQName.uri)); if (aGrammar == null || !(aGrammar instanceof SchemaGrammar) ) { if (processContentStrict) { reportError = true; } } else { SchemaGrammar sGrammar = (SchemaGrammar) aGrammar; Hashtable attRegistry = sGrammar.getAttributeDeclRegistry(); if (attRegistry == null) { if (processContentStrict) { reportError = true; } } else { XMLAttributeDecl attDecl = (XMLAttributeDecl) attRegistry.get(fStringPool.toString(fTempQName.localpart)); if (attDecl == null) { if (processContentStrict) { reportError = true; } } else { DatatypeValidator attDV = attDecl.datatypeValidator; if (attDV == null) { if (processContentStrict) { reportError = true; } } else { try { String unTrimValue = fStringPool.toString(attrList.getAttValue(index)); String value = unTrimValue.trim(); if (attDV instanceof IDDatatypeValidator) { this.fStoreIDRef.setDatatypeObject( attDV.validate( value, null ) ); } if (attDV instanceof IDREFDatatypeValidator) { attDV.validate(value, null ); } else { fWhiteSpace = attDV.getWSFacet(); if (fWhiteSpace == DatatypeValidator.REPLACE) { //CDATA attDV.validate(unTrimValue, null ); } else { // normalize int normalizedValue = fStringPool.addString(value); attrList.setAttValue(index,normalizedValue ); if (attDV instanceof NOTATIONDatatypeValidator && value !=null) { value=bindNotationURI(value); } attDV.validate(value, null ); } } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { idve.getMessage()}, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } } } } if (reportError) { Object[] args = { fStringPool.toString(element.rawname), "ANY---"+fStringPool.toString(attrList.getAttrName(index))}; fAttrNameLocator = getLocatorImpl(fAttrNameLocator); fErrorReporter.reportError(fAttrNameLocator, XMLMessages.XML_DOMAIN, XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED, XMLMessages.VC_ATTRIBUTE_VALUE_TYPE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } else if (fTempAttDecl.datatypeValidator == null) { Object[] args = { fStringPool.toString(element.rawname), fStringPool.toString(attrList.getAttrName(index))}; System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index)) + " not found in element type " + fStringPool.toString(element.rawname)); fAttrNameLocator = getLocatorImpl(fAttrNameLocator); fErrorReporter.reportError(fAttrNameLocator, XMLMessages.XML_DOMAIN, XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED, XMLMessages.VC_ATTRIBUTE_VALUE_TYPE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } else { try { String unTrimValue = fStringPool.toString(attrList.getAttValue(index)); String value = unTrimValue.trim(); DatatypeValidator tempDV = fTempAttDecl.datatypeValidator; if (tempDV instanceof IDDatatypeValidator) { this.fStoreIDRef.setDatatypeObject( tempDV.validate( value, null ) ); } else if (tempDV instanceof IDREFDatatypeValidator) { tempDV.validate(value, null ); } else { fWhiteSpace = tempDV.getWSFacet(); if (fWhiteSpace == DatatypeValidator.REPLACE) { //CDATA tempDV.validate(unTrimValue, null ); } else { // normalize int normalizedValue = fStringPool.addString(value); attrList.setAttValue(index,normalizedValue ); if (tempDV instanceof NOTATIONDatatypeValidator && value !=null) { value=bindNotationURI(value); } tempDV.validate(value, null ); } } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { idve.getMessage()}, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } // end of if (fValidating) } // end of if (attDefIndex == -1) else }// end of if (fGrammar != null) index = fAttrList.getNextAttr(index); } } } if (fAttrListHandle != -1) { int index = attrList.getFirstAttr(fAttrListHandle); while (index != -1) { int attName = attrList.getAttrName(index); if (!fStringPool.equalNames(attName, fNamespacesPrefix)) { int attPrefix = attrList.getAttrPrefix(index); if (attPrefix != fNamespacesPrefix) { if (attPrefix != -1) { int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix); if (uri == StringPool.EMPTY_STRING) { Object[] args = { fStringPool.toString(attPrefix)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XMLNS_DOMAIN, XMLMessages.MSG_PREFIX_DECLARED, XMLMessages.NC_PREFIX_DECLARED, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } attrList.setAttrURI(index, uri); } } } index = attrList.getNextAttr(index); } } fCurrentElementIndex = elementIndex; fCurrentContentSpecType = contentSpecType; if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) { fBufferDatatype = true; fDatatypeBuffer.setLength(0); } fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN); } // validateElementAndAttributes(QName,XMLAttrList) /** * Validate attributes in DTD fashion. * @return normalized attribute value */ private int validateDTDattribute(QName element, int attValue, XMLAttributeDecl attributeDecl) throws Exception{ AttributeValidator av = null; switch (attributeDecl.type) { case XMLAttributeDecl.TYPE_ENTITY: { boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); //System.out.println("value = " + value ); //changes fTempAttDef if (fValidationEnabled) { if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } } try { if ( isAlistAttribute ) { fValENTITIES.validate( value, null ); } else { fValENTITY.validate( value, null ); } } catch ( InvalidDatatypeValueException ex ) { if ( ex.getMajorCode() != 1 && ex.getMinorCode() != -1 ) { reportRecoverableXMLError(ex.getMajorCode(), ex.getMinorCode(), fStringPool.toString( attributeDecl.name.rawname), value ); } else { System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen } } /*if (attributeDecl.list) { av = fAttValidatorENTITIES; } else { av = fAttValidatorENTITY; }*/ if (fNormalizeAttributeValues) { if (attributeDecl.list) { attValue = normalizeListAttribute(value, attValue, unTrimValue); } else { if (value != unTrimValue) { attValue = fStringPool.addSymbol(value); } } } } break; case XMLAttributeDecl.TYPE_ENUMERATION: av = fAttValidatorENUMERATION; break; case XMLAttributeDecl.TYPE_ID: { String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); if (fValidationEnabled) { if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } } try { this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) ); fValIDRef.validate( value, null ); //just in case we called id after IDREF } catch ( InvalidDatatypeValueException ex ) { reportRecoverableXMLError(ex.getMajorCode(), ex.getMinorCode(), fStringPool.toString( attributeDecl.name.rawname), value ); } if (fNormalizeAttributeValues && value != unTrimValue) { attValue = fStringPool.addSymbol(value); } } break; case XMLAttributeDecl.TYPE_IDREF: { String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef //changes fTempAttDef if (fValidationEnabled) { if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } if (attributeDecl.list && value.length() == 0 ) { reportRecoverableXMLError(XMLMessages.MSG_IDREFS_INVALID, XMLMessages.VC_IDREF, fStringPool.toString(attributeDecl.name.rawname) ) ; } } try { if ( isAlistAttribute ) { fValIDRefs.validate( value, null ); } else { fValIDRef.validate( value, null ); } } catch ( InvalidDatatypeValueException ex ) { if ( ex.getMajorCode() != 1 && ex.getMinorCode() != -1 ) { reportRecoverableXMLError(ex.getMajorCode(), ex.getMinorCode(), fStringPool.toString( attributeDecl.name.rawname), value ); } else { System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen } } if (fNormalizeAttributeValues) { if (attributeDecl.list) { attValue = normalizeListAttribute(value, attValue, unTrimValue); } else { if (value != unTrimValue) { attValue = fStringPool.addSymbol(value); } } } } break; case XMLAttributeDecl.TYPE_NOTATION: { /* WIP String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); if (fValidationEnabled) { if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } } try { //this.fIdDefs = (Hashtable) fValID.validate( value, null ); //System.out.println("this.fIdDefs = " + this.fIdDefs ); this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) ); } catch ( InvalidDatatypeValueException ex ) { reportRecoverableXMLError(ex.getMajorCode(), ex.getMinorCode(), fStringPool.toString( attributeDecl.name.rawname), value ); } } */ av = fAttValidatorNOTATION; } break; case XMLAttributeDecl.TYPE_NMTOKEN: { String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef //changes fTempAttDef if (fValidationEnabled) { if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } if (attributeDecl.list && value.length() == 0 ) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attributeDecl.name.rawname) ) ; } } try { if ( isAlistAttribute ) { fValNMTOKENS.validate( value, null ); } else { fValNMTOKEN.validate( value, null ); } } catch ( InvalidDatatypeValueException ex ) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attributeDecl.name.rawname), value);//TODO NMTOKENS messge } if (fNormalizeAttributeValues) { if (attributeDecl.list) { attValue = normalizeListAttribute(value, attValue, unTrimValue); } else { if (value != unTrimValue) { attValue = fStringPool.addSymbol(value); } } } } break; } if ( av != null ) { int newValue = av.normalize(element, attributeDecl.name, attValue, attributeDecl.type, attributeDecl.enumeration); if (fNormalizeAttributeValues) attValue = newValue; } return attValue; } /** * @param value This is already trimmed. */ private int normalizeListAttribute(String value, int origIndex, String origValue) { int length = value.length(); StringBuffer buffer = null; int state = 0; // 0:non-S, 1: 1st S, 2: non-1st S int copyStart = 0; for (int i = 0; i < length; i++) { int ch = value.charAt(i); if (ch == ' ') { if (state == 0) { state = 1; } else if (state == 1) { state = 2; if (buffer == null) buffer = new StringBuffer(length); buffer.append(value.substring(copyStart, i)); } } else { if (state == 2) copyStart = i; state = 0; } } if (buffer == null) return value == origValue ? origIndex : fStringPool.addSymbol(value); buffer.append(value.substring(copyStart)); return fStringPool.addSymbol(new String(buffer)); } /** Character data in content. */ private void charDataInContent() { if (DEBUG_ELEMENT_CHILDREN) { System.out.println("charDataInContent()"); } if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildren.length * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.clear(); fElementChildrenLength++; } // charDataInCount() /** * Check that the content of an element is valid. * <p> * This is the method of primary concern to the validator. This method is called * upon the scanner reaching the end tag of an element. At that time, the * element's children must be structurally validated, so it calls this method. * The index of the element being checked (in the decl pool), is provided as * well as an array of element name indexes of the children. The validator must * confirm that this element can have these children in this order. * <p> * This can also be called to do 'what if' testing of content models just to see * if they would be valid. * <p> * Note that the element index is an index into the element decl pool, whereas * the children indexes are name indexes, i.e. into the string pool. * <p> * A value of -1 in the children array indicates a PCDATA node. All other * indexes will be positive and represent child elements. The count can be * zero, since some elements have the EMPTY content model and that must be * confirmed. * * @param elementIndex The index within the <code>ElementDeclPool</code> of this * element. * @param childCount The number of entries in the <code>children</code> array. * @param children The children of this element. Each integer is an index within * the <code>StringPool</code> of the child element name. An index * of -1 is used to indicate an occurrence of non-whitespace character * data. * * @return The value -1 if fully valid, else the 0 based index of the child * that first failed. If the value returned is equal to the number * of children, then additional content is required to reach a valid * ending state. * * @exception Exception Thrown on error. */ private int checkContent(int elementIndex, QName[] children, int childOffset, int childCount) throws Exception { // Get the element name index from the element // REVISIT: Validation final int elementType = fCurrentElement.rawname; if (DEBUG_PRINT_CONTENT) { String strTmp = fStringPool.toString(elementType); System.out.println("Name: "+strTmp+", "+ "Count: "+childCount+", "+ "ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex)); for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) { if (index == 0) { System.out.print(" ("); } String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart); if (index + 1 == childCount) { System.out.println(childName + ")"); } else if (index + 1 == 10) { System.out.println(childName + ",...)"); } else { System.out.print(childName + ","); } } } // Get out the content spec for this element final int contentType = fCurrentContentSpecType; // Deal with the possible types of content. We try to optimized here // by dealing specially with content models that don't require the // full DFA treatment. if (contentType == XMLElementDecl.TYPE_EMPTY) { // If the child count is greater than zero, then this is // an error right off the bat at index 0. if (childCount != 0) { return 0; } } else if (contentType == XMLElementDecl.TYPE_ANY) { // This one is open game so we don't pass any judgement on it // at all. Its assumed to fine since it can hold anything. } else if (contentType == XMLElementDecl.TYPE_MIXED_SIMPLE || contentType == XMLElementDecl.TYPE_MIXED_COMPLEX || contentType == XMLElementDecl.TYPE_CHILDREN) { // XML Schema REC: Validation Rule: Element Locally Valid (Element) // 3.2.1 The element information item must have no // character or element information item [children]. if (childCount == 0 && fNil) { fNil = false; //return success return -1; } // Get the content model for this element, faulting it in if needed XMLContentModel cmElem = null; try { cmElem = getElementContentModel(elementIndex); int result = cmElem.validateContent(children, childOffset, childCount); if (result != -1 && fGrammarIsSchemaGrammar) { // REVISIT: not optimized for performance, SubstitutionGroupComparator comparator = new SubstitutionGroupComparator(fGrammarResolver, fStringPool, fErrorReporter); cmElem.setSubstitutionGroupComparator(comparator); result = cmElem.validateContentSpecial(children, childOffset, childCount); } return result; } catch (CMException excToCatch) { // REVISIT - Translate the caught exception to the protected error API int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } } else if (contentType == -1) { reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED, XMLMessages.VC_ELEMENT_VALID, elementType); } else if (contentType == XMLElementDecl.TYPE_SIMPLE ) { XMLContentModel cmElem = null; if (childCount > 0) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { "In element '"+fStringPool.toString(elementType)+"' : "+ "Can not have element children within a simple type content"}, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } else { try { if (fCurrentDV == null) { //no character data fGrammar.getElementDecl(elementIndex, fTempElementDecl); fCurrentDV = fTempElementDecl.datatypeValidator; } // If there is xsi:type validator, substitute it. if ( fXsiTypeValidator != null ) { fCurrentDV = fXsiTypeValidator; fXsiTypeValidator = null; } if (fCurrentDV == null) { System.out.println("Internal Error: this element have a simpletype "+ "but no datatypevalidator was found, element "+fTempElementDecl.name +",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart)); } else { String value =fDatatypeBuffer.toString(); // check for fixed/default values of elements here. if( ((SchemaGrammar)fGrammar).getElementDefaultValue(fCurrentElementIndex) != null && ((SchemaGrammar)fGrammar).getElementDefaultValue(fCurrentElementIndex).equals("")) { if (!fNil) { fCurrentDV.validate(value, null); } else if ( fNil && value.length() != 0 ) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "An element <" +fStringPool.toString(elementType)+"> with attribute xsi:nil=\"true\" must be empty"); } } else { String currentElementDefault = ((SchemaGrammar)fGrammar).getElementDefaultValue(fCurrentElementIndex); if ( (((SchemaGrammar)fGrammar).getElementDeclMiscFlags(fCurrentElementIndex) & SchemaSymbols.FIXED) != 0 ) { if ( value.length() == 0 ) { // use fixed as default value // Note: this is inefficient where the DOMParser // is concerned. However, if we used the characters(int) // callback instead, this would be just as inefficient for SAX. fDocumentHandler.characters(currentElementDefault.toCharArray(), 0, currentElementDefault.length()); } else { // must check in valuespace! if ( fCurrentDV.compare(value, currentElementDefault) != 0 ) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.FixedDiffersFromActual, 0, null, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } else { if ( value.length() == 0 ) { // use default value fDocumentHandler.characters(currentElementDefault.toCharArray(), 0, currentElementDefault.length()); } else if (!fNil){ // must validate value fCurrentDV.validate(value, null); } } } } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { "In element '"+fStringPool.toString(elementType)+"' : "+idve.getMessage()}, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } fNil = false; fCurrentDV = null; fFirstChunk= true; fTrailing=false; } } else { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_CST, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } // We succeeded return -1; } // checkContent(int,int,int[]):int /** * Checks that all declared elements refer to declared elements * in their content models. This method calls out to the error * handler to indicate warnings. */ private void printChildren() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('['); for (int i = 0; i < fElementChildrenLength; i++) { System.out.print(' '); QName qname = fElementChildren[i]; if (qname != null) { System.out.print(fStringPool.toString(qname.rawname)); } else { System.out.print("null"); } if (i < fElementChildrenLength - 1) { System.out.print(", "); } System.out.flush(); } System.out.print(" ]"); System.out.println(); } } private void printStack() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('{'); for (int i = 0; i <= fElementDepth; i++) { System.out.print(' '); System.out.print(fElementChildrenOffsetStack[i]); if (i < fElementDepth) { System.out.print(", "); } System.out.flush(); } System.out.print(" }"); System.out.println(); } } // Interfaces /** * AttributeValidator. */ public interface AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValue, int attType, int enumHandle) throws Exception; } // interface AttributeValidator /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } // Classes /** * AttValidatorNOTATION. */ final class AttValidatorNOTATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // NOTATION - check that the value is in the AttDef enumeration (V_TAGo) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_NOTATION_ATTRIBUTES, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNOTATION /** * AttValidatorENUMERATION. */ final class AttValidatorENUMERATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENUMERATION - check that value is in the AttDef enumeration (V_TAG9) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_ENUMERATION, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENUMERATION // xpath matcher information /** * Stack of XPath matchers for identity constraints. * * @author Andy Clark, IBM */ protected static class XPathMatcherStack { // Data /** Active matchers. */ protected XPathMatcher[] fMatchers = new XPathMatcher[4]; /** Count of active matchers. */ protected int fMatchersCount; /** Offset stack for contexts. */ protected IntStack fContextStack = new IntStack(); // Constructors public XPathMatcherStack() { } // <init>() // Public methods /** Resets the XPath matcher stack. */ public void clear() { for (int i = 0; i < fMatchersCount; i++) { fMatchers[i] = null; } fMatchersCount = 0; fContextStack.clear(); } // clear() /** Returns the size of the stack. */ public int size() { return fContextStack.size(); } // size():int /** Returns the count of XPath matchers. */ public int getMatcherCount() { return fMatchersCount; } // getMatcherCount():int /** Adds a matcher. */ public void addMatcher(XPathMatcher matcher) { ensureMatcherCapacity(); fMatchers[fMatchersCount++] = matcher; } // addMatcher(XPathMatcher) /** Returns the XPath matcher at the specified index. */ public XPathMatcher getMatcherAt(int index) { return fMatchers[index]; } // getMatcherAt(index):XPathMatcher /** Pushes a new context onto the stack. */ public void pushContext() { fContextStack.push(fMatchersCount); } // pushContext() /** Pops a context off of the stack. */ public void popContext() { fMatchersCount = fContextStack.pop(); } // popContext() // Private methods /** Ensures the size of the matchers array. */ private void ensureMatcherCapacity() { if (fMatchersCount == fMatchers.length) { XPathMatcher[] array = new XPathMatcher[fMatchers.length * 2]; System.arraycopy(fMatchers, 0, array, 0, fMatchers.length); fMatchers = array; } } // ensureMatcherCapacity() } // class XPathMatcherStack // value store implementations /** * Value store implementation base class. There are specific subclasses * for handling unique, key, and keyref. * * @author Andy Clark, IBM */ protected abstract class ValueStoreBase implements ValueStore { // Constants /** Not a value (Unicode: #FFFF). */ protected IDValue NOT_AN_IDVALUE = new IDValue("\uFFFF", null); // Data /** Identity constraint. */ protected IdentityConstraint fIdentityConstraint; /** Current data values. */ protected final OrderedHashtable fValues = new OrderedHashtable(); /** Current data value count. */ protected int fValuesCount; /** Data value tuples. */ protected final Vector fValueTuples = new Vector(); // Constructors /** Constructs a value store for the specified identity constraint. */ protected ValueStoreBase(IdentityConstraint identityConstraint) { fIdentityConstraint = identityConstraint; } // <init>(IdentityConstraint) // Public methods // destroys this ValueStore; useful when, for instanc,e a // locally-scoped ID constraint is involved. public void destroy() { fValuesCount = 0; fValues.clear(); fValueTuples.removeAllElements(); } // end destroy():void // appends the contents of one ValueStore to those of us. public void append(ValueStoreBase newVal) { for (int i = 0; i < newVal.fValueTuples.size(); i++) { OrderedHashtable o = (OrderedHashtable)newVal.fValueTuples.elementAt(i); if (!contains(o)) fValueTuples.addElement(o); } } // append(ValueStoreBase) /** Start scope for value store. */ public void startValueScope() throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#startValueScope()"); } fValuesCount = 0; int count = fIdentityConstraint.getFieldCount(); for (int i = 0; i < count; i++) { fValues.put(fIdentityConstraint.getFieldAt(i), NOT_AN_IDVALUE); } } // startValueScope() /** Ends scope for value store. */ public void endValueScope() throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#endValueScope()"); } // is there anything to do? // REVISIT: This check solves the problem with field matchers // that get activated because they are at the same // level as the declaring element (e.g. selector xpath // is ".") but never match. // However, this doesn't help us catch the problem // when we expect a field value but never see it. A // better solution has to be found. -Ac // REVISIT: Is this a problem? -Ac // Yes - NG if (fValuesCount == 0) { if(fIdentityConstraint.getType() == IdentityConstraint.KEY) { int code = SchemaMessageProvider.AbsentKeyValue; String eName = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{eName}); } return; } // do we have enough values? if (fValuesCount != fIdentityConstraint.getFieldCount()) { switch (fIdentityConstraint.getType()) { case IdentityConstraint.UNIQUE: { int code = SchemaMessageProvider.UniqueNotEnoughValues; String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{ename}); break; } case IdentityConstraint.KEY: { int code = SchemaMessageProvider.KeyNotEnoughValues; Key key = (Key)fIdentityConstraint; String ename = fIdentityConstraint.getElementName(); String kname = key.getIdentityConstraintName(); reportSchemaError(code, new Object[]{ename,kname}); break; } case IdentityConstraint.KEYREF: { int code = SchemaMessageProvider.KeyRefNotEnoughValues; KeyRef keyref = (KeyRef)fIdentityConstraint; String ename = fIdentityConstraint.getElementName(); String kname = (keyref.getKey()).getIdentityConstraintName(); reportSchemaError(code, new Object[]{ename,kname}); break; } } return; } } // endValueScope() // This is needed to allow keyref's to look for matched keys // in the correct scope. Unique and Key may also need to // override this method for purposes of their own. // This method is called whenever the DocumentFragment // of an ID Constraint goes out of scope. public void endDocumentFragment() throws Exception { } // endDocumentFragment():void /** * Signals the end of the document. This is where the specific * instances of value stores can verify the integrity of the * identity constraints. */ public void endDocument() throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#endDocument()"); } } // endDocument() // ValueStore methods /* reports an error if an element is matched * has nillable true and is matched by a key. */ public void reportNilError(IdentityConstraint id) throws Exception { if(id.getType() == IdentityConstraint.KEY) { int code = SchemaMessageProvider.KeyMatchesNillable; reportSchemaError(code, new Object[]{id.getElementName()}); } } // reportNilError /** * Adds the specified value to the value store. * * @param value The value to add. * @param field The field associated to the value. This reference * is used to ensure that each field only adds a value * once within a selection scope. */ public void addValue(Field field, IDValue value) throws Exception { if(!field.mayMatch()) { int code = SchemaMessageProvider.FieldMultipleMatch; reportSchemaError(code, new Object[]{field.toString()}); } if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#addValue("+ "field="+field+','+ "value="+value+ ")"); } // do we even know this field? int index = fValues.indexOf(field); if (index == -1) { int code = SchemaMessageProvider.UnknownField; reportSchemaError(code, new Object[]{field.toString()}); return; } // store value IDValue storedValue = fValues.valueAt(index); if (storedValue.isDuplicateOf(NOT_AN_IDVALUE)) { fValuesCount++; } fValues.put(field, value); if (fValuesCount == fValues.size()) { // is this value as a group duplicated? if (contains(fValues)) { duplicateValue(fValues); } // store values OrderedHashtable values = (OrderedHashtable)fValues.clone(); fValueTuples.addElement(values); } } // addValue(String,Field) /** * Returns true if this value store contains the specified * values tuple. */ public boolean contains(OrderedHashtable tuple) { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+this.toString()+"#contains("+toString(tuple)+")"); } // do sizes match? int tcount = tuple.size(); // iterate over tuples to find it int count = fValueTuples.size(); LOOP: for (int i = 0; i < count; i++) { OrderedHashtable vtuple = (OrderedHashtable)fValueTuples.elementAt(i); // compare values for (int j = 0; j < tcount; j++) { IDValue value1 = vtuple.valueAt(j); IDValue value2 = tuple.valueAt(j); if(!(value1.isDuplicateOf(value2))) { continue LOOP; } } // found it return true; } // didn't find it return false; } // contains(Hashtable):boolean // Protected methods /** * Called when a duplicate value is added. Subclasses should override * this method to perform error checking. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws Exception { // no-op } // duplicateValue(Hashtable) /** Returns a string of the specified values. */ protected String toString(OrderedHashtable tuple) { // no values int size = tuple.size(); if (size == 0) { return ""; } // construct value string StringBuffer str = new StringBuffer(); for (int i = 0; i < size; i++) { if (i > 0) { str.append(','); } str.append(tuple.valueAt(i)); } return str.toString(); } // toString(OrderedHashtable):String // Object methods /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { s = s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { s = s.substring(index2 + 1); } return s + '[' + fIdentityConstraint + ']'; } // toString():String } // class ValueStoreBase /** * Unique value store. * * @author Andy Clark, IBM */ protected class UniqueValueStore extends ValueStoreBase { // Constructors /** Constructs a unique value store. */ public UniqueValueStore(Unique unique) { super(unique); } // <init>(Unique) // ValueStoreBase protected methods /** * Called when a duplicate value is added. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws Exception { int code = SchemaMessageProvider.DuplicateUnique; String value = toString(tuple); String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,ename}); } // duplicateValue(Hashtable) } // class UniqueValueStore /** * Key value store. * * @author Andy Clark, IBM */ protected class KeyValueStore extends ValueStoreBase { // REVISIT: Implement a more efficient storage mechanism. -Ac // Constructors /** Constructs a key value store. */ public KeyValueStore(Key key) { super(key); } // <init>(Key) // ValueStoreBase protected methods /** * Called when a duplicate value is added. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws Exception { int code = SchemaMessageProvider.DuplicateKey; String value = toString(tuple); String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,ename}); } // duplicateValue(Hashtable) } // class KeyValueStore /** * Key reference value store. * * @author Andy Clark, IBM */ protected class KeyRefValueStore extends ValueStoreBase { // Data /** Key value store. */ protected ValueStoreBase fKeyValueStore; // Constructors /** Constructs a key value store. */ public KeyRefValueStore(KeyRef keyRef, KeyValueStore keyValueStore) { super(keyRef); fKeyValueStore = keyValueStore; } // <init>(KeyRef) // ValueStoreBase methods // end the value Scope; here's where we have to tie // up keyRef loose ends. public void endDocumentFragment () throws Exception { // do all the necessary management... super.endDocumentFragment (); // verify references // get the key store corresponding (if it exists): fKeyValueStore = (ValueStoreBase)fValueStoreCache.fGlobalIDConstraintMap.get(((KeyRef)fIdentityConstraint).getKey()); if(fKeyValueStore == null) { // report error int code = SchemaMessageProvider.KeyRefOutOfScope; String value = fIdentityConstraint.toString(); reportSchemaError(code, new Object[]{value}); return; } int count = fValueTuples.size(); for (int i = 0; i < count; i++) { OrderedHashtable values = (OrderedHashtable)fValueTuples.elementAt(i); if (!fKeyValueStore.contains(values)) { int code = SchemaMessageProvider.KeyNotFound; String value = toString(values); String element = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,element}); } } } // endDocumentFragment() /** End document. */ public void endDocument() throws Exception { super.endDocument(); } // endDocument() } // class KeyRefValueStore // value store management /** * Value store cache. This class is used to store the values for * identity constraints. * * @author Andy Clark, IBM */ protected class ValueStoreCache { // Data // values stores /** stores all global Values stores. */ protected final Vector fValueStores = new Vector(); /** Values stores associated to specific identity constraints. */ protected final Hashtable fIdentityConstraint2ValueStoreMap = new Hashtable(); // sketch of algorithm: // - when a constraint is first encountered, its // values are stored in the (local) fIdentityConstraint2ValueStoreMap; // - Once it is validated (i.e., wen it goes out of scope), // its values are merged into the fGlobalIDConstraintMap; // - as we encounter keyref's, we look at the global table to // validate them. // the fGlobalIDMapStack has the following structure: // - validation always occurs against the fGlobalIDConstraintMap // (which comprises all the "eligible" id constraints); // When an endelement is found, this Hashtable is merged with the one // below in the stack. // When a start tag is encountered, we create a new // fGlobalIDConstraintMap. // i.e., the top of the fGlobalIDMapStack always contains // the preceding siblings' eligible id constraints; // the fGlobalIDConstraintMap contains descendants+self. // keyrefs can only match descendants+self. protected final Stack fGlobalMapStack = new Stack(); protected final Hashtable fGlobalIDConstraintMap = new Hashtable(); // Constructors /** Default constructor. */ public ValueStoreCache() { } // <init>() // Public methods /** Resets the identity constraint cache. */ public void startDocument() throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#startDocument()"); } fValueStores.removeAllElements(); fIdentityConstraint2ValueStoreMap.clear(); fGlobalIDConstraintMap.clear(); fGlobalMapStack.removeAllElements(); } // startDocument() // startElement: pushes the current fGlobalIDConstraintMap // onto fGlobalMapStack and clears fGlobalIDConstraint map. public void startElement() { fGlobalMapStack.push(fGlobalIDConstraintMap.clone()); fGlobalIDConstraintMap.clear(); } // startElement(void) // endElement(): merges contents of fGlobalIDConstraintMap with the // top of fGlobalMapStack into fGlobalIDConstraintMap. public void endElement() { if (fGlobalMapStack.isEmpty()) return; // must be an invalid doc! Hashtable oldMap = (Hashtable)fGlobalMapStack.pop(); Enumeration keys = oldMap.keys(); while(keys.hasMoreElements()) { IdentityConstraint id = (IdentityConstraint)keys.nextElement(); ValueStoreBase oldVal = (ValueStoreBase)oldMap.get(id); if(oldVal != null) { ValueStoreBase currVal = (ValueStoreBase)fGlobalIDConstraintMap.get(id); if (currVal == null) fGlobalIDConstraintMap.put(id, oldVal); else { currVal.append(oldVal); fGlobalIDConstraintMap.put(id, currVal); } } } } // endElement() /** * Initializes the value stores for the specified element * declaration. */ public void initValueStoresFor(XMLElementDecl eDecl) throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#initValueStoresFor("+ fStringPool.toString(eDecl.name.rawname)+ ")"); } // initialize value stores for unique fields Vector uVector = eDecl.unique; int uCount = uVector.size(); for (int i = 0; i < uCount; i++) { Unique unique = (Unique)uVector.elementAt(i); UniqueValueStore valueStore = (UniqueValueStore)fIdentityConstraint2ValueStoreMap.get(unique); if (valueStore != null) { // NOTE: If already initialized, don't need to // do it again. -Ac continue; } valueStore = new UniqueValueStore(unique); fValueStores.addElement(valueStore); if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+unique+" -> "+valueStore); } fIdentityConstraint2ValueStoreMap.put(unique, valueStore); } // initialize value stores for key fields Vector kVector = eDecl.key; int kCount = kVector.size(); for (int i = 0; i < kCount; i++) { Key key = (Key)kVector.elementAt(i); KeyValueStore valueStore = (KeyValueStore)fIdentityConstraint2ValueStoreMap.get(key); if (valueStore != null) { // NOTE: If already initialized, don't need to // do it again. -Ac continue; } valueStore = new KeyValueStore(key); fValueStores.addElement(valueStore); if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+key+" -> "+valueStore); } fIdentityConstraint2ValueStoreMap.put(key, valueStore); } // initialize value stores for key reference fields Vector krVector = eDecl.keyRef; int krCount = krVector.size(); for (int i = 0; i < krCount; i++) { KeyRef keyRef = (KeyRef)krVector.elementAt(i); KeyRefValueStore keyRefValueStore = new KeyRefValueStore(keyRef, null); fValueStores.addElement(keyRefValueStore); if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+keyRef+" -> "+keyRefValueStore); } fIdentityConstraint2ValueStoreMap.put(keyRef, keyRefValueStore); } } // initValueStoresFor(XMLElementDecl) /** Returns the value store associated to the specified field. */ public ValueStoreBase getValueStoreFor(Field field) { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#getValueStoreFor("+field+")"); } IdentityConstraint identityConstraint = field.getIdentityConstraint(); return (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(identityConstraint); } // getValueStoreFor(Field):ValueStoreBase /** Returns the value store associated to the specified IdentityConstraint. */ public ValueStoreBase getValueStoreFor(IdentityConstraint id) { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#getValueStoreFor("+id+")"); } return (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase /** Returns the global value store associated to the specified IdentityConstraint. */ public ValueStoreBase getGlobalValueStoreFor(IdentityConstraint id) { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#getGlobalValueStoreFor("+id+")"); } return (ValueStoreBase)fGlobalIDConstraintMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase // This method takes the contents of the (local) ValueStore // associated with id and moves them into the global // hashtable, if id is a <unique> or a <key>. // If it's a <keyRef>, then we leave it for later. public void transplant(IdentityConstraint id) throws Exception { if (id.getType() == IdentityConstraint.KEYREF ) return; ValueStoreBase newVals = (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(id); fIdentityConstraint2ValueStoreMap.remove(id); ValueStoreBase currVals = (ValueStoreBase)fGlobalIDConstraintMap.get(id); if (currVals != null) { currVals.append(newVals); fGlobalIDConstraintMap.put(id, currVals); } else fGlobalIDConstraintMap.put(id, newVals); } // transplant(id) /** Check identity constraints. */ public void endDocument() throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#endDocument()"); } int count = fValueStores.size(); for (int i = 0; i < count; i++) { ValueStoreBase valueStore = (ValueStoreBase)fValueStores.elementAt(i); valueStore.endDocument(); } } // endDocument() // Object methods /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { return s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { return s.substring(index2 + 1); } return s; } // toString():String } // class ValueStoreCache // utility classes /** * Ordered hashtable. This class acts as a hashtable with * <code>put()</code> and <code>get()</code> operations but also * allows values to be queried via the order that they were * added to the hashtable. * <p> * <strong>Note:</strong> This class does not perform any error * checking. * <p> * <strong>Note:</strong> This class is <em>not</em> efficient but * is assumed to be used for a very small set of values. * * @author Andy Clark, IBM */ static final class OrderedHashtable implements Cloneable { // Data /** Size. */ private int fSize; /** Hashtable entries. */ private Entry[] fEntries = null; // Public methods /** Returns the number of entries in the hashtable. */ public int size() { return fSize; } // size():int /** Puts an entry into the hashtable. */ public void put(Field key, IDValue value) { int index = indexOf(key); if (index == -1) { ensureCapacity(fSize); index = fSize++; fEntries[index].key = key; } fEntries[index].value = value; } // put(Field,String) /** Returns the value associated to the specified key. */ public IDValue get(Field key) { return fEntries[indexOf(key)].value; } // get(Field):String /** Returns the index of the entry with the specified key. */ public int indexOf(Field key) { for (int i = 0; i < fSize; i++) { // NOTE: Only way to be sure that the keys are the // same is by using a reference comparison. In // order to rely on the equals method, each // field would have to take into account its // position in the identity constraint, the // identity constraint, the declaring element, // and the grammar that it is defined in. // Otherwise, you have the possibility that // the equals method would return true for two // fields that look *very* similar. // The reference compare isn't bad, actually, // because the field objects are cacheable. -Ac if (fEntries[i].key == key) { return i; } } return -1; } // indexOf(Field):int /** Returns the key at the specified index. */ public Field keyAt(int index) { return fEntries[index].key; } // keyAt(int):Field /** Returns the value at the specified index. */ public IDValue valueAt(int index) { return fEntries[index].value; } // valueAt(int):String /** Removes all of the entries from the hashtable. */ public void clear() { fSize = 0; } // clear() // Private methods /** Ensures the capacity of the entries array. */ private void ensureCapacity(int size) { // sizes int osize = -1; int nsize = -1; // create array if (fEntries == null) { osize = 0; nsize = 2; fEntries = new Entry[nsize]; } // resize array else if (fEntries.length <= size) { osize = fEntries.length; nsize = 2 * osize; Entry[] array = new Entry[nsize]; System.arraycopy(fEntries, 0, array, 0, osize); fEntries = array; } // create new entries for (int i = osize; i < nsize; i++) { fEntries[i] = new Entry(); } } // ensureCapacity(int) // Cloneable methods /** Clones this object. */ public Object clone() { OrderedHashtable hashtable = new OrderedHashtable(); for (int i = 0; i < fSize; i++) { hashtable.put(fEntries[i].key, fEntries[i].value); } return hashtable; } // clone():Object // Object methods /** Returns a string representation of this object. */ public String toString() { if (fSize == 0) { return "[]"; } StringBuffer str = new StringBuffer(); str.append('['); for (int i = 0; i < fSize; i++) { if (i > 0) { str.append(','); } str.append('{'); str.append(fEntries[i].key); str.append(','); str.append(fEntries[i].value); str.append('}'); } str.append(']'); return str.toString(); } // toString():String // Classes /** * Hashtable entry. */ public static final class Entry { // Data /** Key. */ public Field key; /** Value. */ public IDValue value; } // class Entry } // class OrderedHashtable } // class XMLValidator
package org.apache.xerces.validators.common; import org.apache.xerces.framework.XMLAttrList; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.framework.XMLDocumentHandler; import org.apache.xerces.framework.XMLDocumentScanner; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.readers.DefaultEntityHandler; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.utils.ChunkyCharArray; import org.apache.xerces.utils.Hash2intTable; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.apache.xerces.utils.XMLMessages; import org.apache.xerces.utils.ImplementationMessages; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.EntityResolver; import org.xml.sax.Locator; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.validators.dtd.DTDGrammar; import org.apache.xerces.validators.schema.EquivClassComparator; import org.apache.xerces.validators.schema.SchemaGrammar; import org.apache.xerces.validators.schema.SchemaMessageProvider; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.TraverseSchema; import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.validators.datatype.StateMessageDatatype; import org.apache.xerces.validators.datatype.IDREFDatatypeValidator; import org.apache.xerces.validators.datatype.IDDatatypeValidator; /** * This class is the super all-in-one validator used by the parser. * * @version $Id$ */ public final class XMLValidator implements DefaultEntityHandler.EventHandler, XMLEntityHandler.CharDataHandler, XMLDocumentScanner.EventHandler, NamespacesScope.NamespacesHandler { // Constants // debugging private static final boolean PRINT_EXCEPTION_STACK_TRACE = false; private static final boolean DEBUG_PRINT_ATTRIBUTES = false; private static final boolean DEBUG_PRINT_CONTENT = false; private static final boolean DEBUG_SCHEMA_VALIDATION = false; private static final boolean DEBUG_ELEMENT_CHILDREN = false; // Chunk size constants private static final int CHUNK_SHIFT = 8; // 2^8 = 256 private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT); private static final int CHUNK_MASK = CHUNK_SIZE - 1; private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k private Hashtable fIdDefs = null; private StateMessageDatatype fStoreIDRef = new StateMessageDatatype() { private Hashtable fIdDefs; public Object getDatatypeObject(){ return(Object) fIdDefs; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_STORE; } public void setDatatypeObject( Object data ){ fIdDefs = (Hashtable) data; } }; private StateMessageDatatype fResetIDRef = new StateMessageDatatype() { public Object getDatatypeObject(){ Hashtable t = null; return(Object) t; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_CLEAR; } public void setDatatypeObject( Object data ){ } }; private StateMessageDatatype fValidateIDRef = new StateMessageDatatype() { public Object getDatatypeObject(){ Hashtable t = null; return(Object) t; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_VALIDATE; } public void setDatatypeObject( Object data ){ } }; // Data // REVISIT: The data should be regrouped and re-organized so that // it's easier to find a meaningful field. // debugging // private static boolean DEBUG = false; // other // attribute validators private AttributeValidator fAttValidatorCDATA = null; private AttributeValidator fAttValidatorENTITY = new AttValidatorENTITY(); private AttributeValidator fAttValidatorENTITIES = new AttValidatorENTITIES(); private AttributeValidator fAttValidatorNMTOKEN = new AttValidatorNMTOKEN(); private AttributeValidator fAttValidatorNMTOKENS = new AttValidatorNMTOKENS(); private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION(); private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION(); private AttributeValidator fAttValidatorDATATYPE = null; // Package access for use by AttributeValidator classes. StringPool fStringPool = null; boolean fValidating = false; boolean fInElementContent = false; int fStandaloneReader = -1; // settings private boolean fValidationEnabled = false; private boolean fDynamicValidation = false; private boolean fSchemaValidation = true; private boolean fValidationEnabledByDynamic = false; private boolean fDynamicDisabledByValidation = false; private boolean fWarningOnDuplicateAttDef = false; private boolean fWarningOnUndeclaredElements = false; private boolean fLoadDTDGrammar = true; // declarations private int fDeclaration[]; private XMLErrorReporter fErrorReporter = null; private DefaultEntityHandler fEntityHandler = null; private QName fCurrentElement = new QName(); private ContentLeafNameTypeVector[] fContentLeafStack = new ContentLeafNameTypeVector[8]; private int[] fValidationFlagStack = new int[8]; private int[] fScopeStack = new int[8]; private int[] fGrammarNameSpaceIndexStack = new int[8]; private int[] fElementEntityStack = new int[8]; private int[] fElementIndexStack = new int[8]; private int[] fContentSpecTypeStack = new int[8]; private static final int sizeQNameParts = 8; private QName[] fElementQNamePartsStack = new QName[sizeQNameParts]; private QName[] fElementChildren = new QName[32]; private int fElementChildrenLength = 0; private int[] fElementChildrenOffsetStack = new int[32]; private int fElementDepth = -1; private boolean fNamespacesEnabled = false; private NamespacesScope fNamespacesScope = null; private int fNamespacesPrefix = -1; private QName fRootElement = new QName(); private int fAttrListHandle = -1; private int fCurrentElementEntity = -1; private int fCurrentElementIndex = -1; private int fCurrentContentSpecType = -1; private boolean fSeenDoctypeDecl = false; private final int TOP_LEVEL_SCOPE = -1; private int fCurrentScope = TOP_LEVEL_SCOPE; private int fCurrentSchemaURI = -1; private int fEmptyURI = - 1; private int fXsiPrefix = - 1; private int fXsiURI = -2; private int fXsiTypeAttValue = -1; private DatatypeValidator fXsiTypeValidator = null; private Grammar fGrammar = null; private int fGrammarNameSpaceIndex = -1; private GrammarResolver fGrammarResolver = null; // state and stuff private boolean fScanningDTD = false; private XMLDocumentScanner fDocumentScanner = null; private boolean fCalledStartDocument = false; private XMLDocumentHandler fDocumentHandler = null; private XMLDocumentHandler.DTDHandler fDTDHandler = null; private boolean fSeenRootElement = false; private XMLAttrList fAttrList = null; private int fXMLLang = -1; private LocatorImpl fAttrNameLocator = null; private boolean fCheckedForSchema = false; private boolean fDeclsAreExternal = false; private StringPool.CharArrayRange fCurrentElementCharArrayRange = null; private char[] fCharRefData = null; private boolean fSendCharDataAsCharArray = false; private boolean fBufferDatatype = false; private StringBuffer fDatatypeBuffer = new StringBuffer(); private QName fTempQName = new QName(); private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl(); private XMLElementDecl fTempElementDecl = new XMLElementDecl(); private boolean fGrammarIsDTDGrammar = false; private boolean fGrammarIsSchemaGrammar = false; private boolean fNeedValidationOff = false; // symbols private int fEMPTYSymbol = -1; private int fANYSymbol = -1; private int fMIXEDSymbol = -1; private int fCHILDRENSymbol = -1; private int fCDATASymbol = -1; private int fIDSymbol = -1; private int fIDREFSymbol = -1; private int fIDREFSSymbol = -1; private int fENTITYSymbol = -1; private int fENTITIESSymbol = -1; private int fNMTOKENSymbol = -1; private int fNMTOKENSSymbol = -1; private int fNOTATIONSymbol = -1; private int fENUMERATIONSymbol = -1; private int fREQUIREDSymbol = -1; private int fFIXEDSymbol = -1; private int fDATATYPESymbol = -1; private int fEpsilonIndex = -1; //Datatype Registry private DatatypeValidatorFactoryImpl fDataTypeReg = DatatypeValidatorFactoryImpl.getDatatypeRegistry(); private DatatypeValidator fValID = this.fDataTypeReg.getDatatypeValidator("ID" ); private DatatypeValidator fValIDRef = this.fDataTypeReg.getDatatypeValidator("IDREF" ); private DatatypeValidator fValIDRefs = this.fDataTypeReg.getDatatypeValidator("IDREFS" ); // Constructors /** Constructs an XML validator. */ public XMLValidator(StringPool stringPool, XMLErrorReporter errorReporter, DefaultEntityHandler entityHandler, XMLDocumentScanner documentScanner) { // keep references fStringPool = stringPool; fErrorReporter = errorReporter; fEntityHandler = entityHandler; fDocumentScanner = documentScanner; fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); // initialize fAttrList = new XMLAttrList(fStringPool); entityHandler.setEventHandler(this); entityHandler.setCharDataHandler(this); fDocumentScanner.setEventHandler(this); for (int i = 0; i < sizeQNameParts; i++) { fElementQNamePartsStack[i] = new QName(); } init(); } // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner) public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; } // Public methods // initialization /** Set char data processing preference and handlers. */ public void initHandlers(boolean sendCharDataAsCharArray, XMLDocumentHandler docHandler, XMLDocumentHandler.DTDHandler dtdHandler) { fSendCharDataAsCharArray = sendCharDataAsCharArray; fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray); fDocumentHandler = docHandler; fDTDHandler = dtdHandler; } // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler) /** Reset or copy. */ public void resetOrCopy(StringPool stringPool) throws Exception { fAttrList = new XMLAttrList(stringPool); resetCommon(stringPool); } /** Reset. */ public void reset(StringPool stringPool) throws Exception { fAttrList.reset(stringPool); resetCommon(stringPool); } // settings /** * Turning on validation/dynamic turns on validation if it is off, and * this is remembered. Turning off validation DISABLES validation/dynamic * if it is on. Turning off validation/dynamic DOES NOT turn off * validation if it was explicitly turned on, only if it was turned on * BECAUSE OF the call to turn validation/dynamic on. Turning on * validation will REENABLE and turn validation/dynamic back on if it * was disabled by a call that turned off validation while * validation/dynamic was enabled. */ public void setValidationEnabled(boolean flag) throws Exception { fValidationEnabled = flag; fValidationEnabledByDynamic = false; if (fValidationEnabled) { if (fDynamicDisabledByValidation) { fDynamicValidation = true; fDynamicDisabledByValidation = false; } } else if (fDynamicValidation) { fDynamicValidation = false; fDynamicDisabledByValidation = true; } fValidating = fValidationEnabled; } /** Returns true if validation is enabled. */ public boolean getValidationEnabled() { return fValidationEnabled; } /** Sets whether Schema support is on/off. */ public void setSchemaValidationEnabled(boolean flag) { fSchemaValidation = flag; } /** Returns true if Schema support is on. */ public boolean getSchemaValidationEnabled() { return fSchemaValidation; } /** Sets whether validation is dynamic. */ public void setDynamicValidationEnabled(boolean flag) throws Exception { fDynamicValidation = flag; fDynamicDisabledByValidation = false; if (!fDynamicValidation) { if (fValidationEnabledByDynamic) { fValidationEnabled = false; fValidationEnabledByDynamic = false; } } else if (!fValidationEnabled) { fValidationEnabled = true; fValidationEnabledByDynamic = true; } fValidating = fValidationEnabled; } /** Returns true if validation is dynamic. */ public boolean getDynamicValidationEnabled() { return fDynamicValidation; } /** Sets fLoadDTDGrammar when validation is off **/ public void setLoadDTDGrammar(boolean loadDG){ if (fValidating) { fLoadDTDGrammar = true; } else{ fLoadDTDGrammar = loadDG; } } /** Returns fLoadDTDGrammar **/ public boolean getLoadDTDGrammar() { return fLoadDTDGrammar; } /** Sets whether namespaces are enabled. */ public void setNamespacesEnabled(boolean flag) { fNamespacesEnabled = flag; } /** Returns true if namespaces are enabled. */ public boolean getNamespacesEnabled() { return fNamespacesEnabled; } /** Sets whether duplicate attribute definitions signal a warning. */ public void setWarningOnDuplicateAttDef(boolean flag) { fWarningOnDuplicateAttDef = flag; } /** Returns true if duplicate attribute definitions signal a warning. */ public boolean getWarningOnDuplicateAttDef() { return fWarningOnDuplicateAttDef; } /** Sets whether undeclared elements signal a warning. */ public void setWarningOnUndeclaredElements(boolean flag) { fWarningOnUndeclaredElements = flag; } /** Returns true if undeclared elements signal a warning. */ public boolean getWarningOnUndeclaredElements() { return fWarningOnUndeclaredElements; } // DefaultEntityHandler.EventHandler methods /** Start entity reference. */ public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.startEntityReference(entityName, entityType, entityContext); } /** End entity reference. */ public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.endEntityReference(entityName, entityType, entityContext); } /** Send end of input notification. */ public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception { fDocumentScanner.endOfInput(entityName, moreToFollow); /** Send reader change notifications. */ /** External entity standalone check. */ /** Return true if validating. */ /** Process characters. */ /** Process characters. */ /** Process whitespace. */ /** Process whitespace. */ /** Scans element type. */ /** Scans expected element type. */ /** Scans attribute name. */ /** Call start document. */ /** Call end document. */ /** Call XML declaration. */ /** Call text declaration. */ /** * Signal the scanning of an element name in a start element tag. * * @param element Element name scanned. */ public void element(QName element) throws Exception { fAttrListHandle = -1; } /** * Signal the scanning of an attribute associated to the previous * start element tag. * * @param element Element name scanned. * @param attrName Attribute name scanned. * @param attrValue The string pool index of the attribute value. */ public boolean attribute(QName element, QName attrName, int attrValue) throws Exception { if (fAttrListHandle == -1) { fAttrListHandle = fAttrList.startAttrList(); } // if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element. // specified: true, search : true return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1; } /** Call start element. */ public void callStartElement(QName element) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart)); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) add default attrs (FIXED and NOT_FIXED) if (!fSeenRootElement) { fSeenRootElement = true; rootElementSpecified(element); fStringPool.resetShuffleCount(); } if (fGrammar != null && fGrammarIsDTDGrammar) { fAttrListHandle = addDTDDefaultAttributes(element, fAttrList, fAttrListHandle, fValidating, fStandaloneReader != -1); } fCheckedForSchema = true; if (fNamespacesEnabled) { bindNamespacesToElementAndAttributes(element, fAttrList); } validateElementAndAttributes(element, fAttrList); if (fAttrListHandle != -1) { fAttrList.endAttrList(); } fDocumentHandler.startElement(element, fAttrList, fAttrListHandle); fAttrListHandle = -1; //before we increment the element depth, add this element's QName to its enclosing element 's children list fElementDepth++; //if (fElementDepth >= 0) { if (fValidating) { // push current length onto stack if (fElementChildrenOffsetStack.length < fElementDepth) { int newarray[] = new int[fElementChildrenOffsetStack.length * 2]; System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length); fElementChildrenOffsetStack = newarray; } fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength; // add this element to children if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildrenLength * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.setValues(element); fElementChildrenLength++; if (DEBUG_ELEMENT_CHILDREN) { printChildren(); printStack(); } } // One more level of depth //fElementDepth++; ensureStackCapacity(fElementDepth); fCurrentElement.setValues(element); fCurrentElementEntity = fEntityHandler.getReaderId(); fElementQNamePartsStack[fElementDepth].setValues(fCurrentElement); fElementEntityStack[fElementDepth] = fCurrentElementEntity; fElementIndexStack[fElementDepth] = fCurrentElementIndex; fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType; if (fNeedValidationOff) { fValidating = false; fNeedValidationOff = false; } if (fValidating && fGrammarIsSchemaGrammar) { pushContentLeafStack(); } fValidationFlagStack[fElementDepth] = fValidating ? 0 : -1; fScopeStack[fElementDepth] = fCurrentScope; fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex; } // callStartElement(QName) private void pushContentLeafStack() throws Exception { int contentType = getContentSpecType(fCurrentElementIndex); if ( contentType == XMLElementDecl.TYPE_CHILDREN) { XMLContentModel cm = getElementContentModel(fCurrentElementIndex); ContentLeafNameTypeVector cv = cm.getContentLeafNameTypeVector(); if (cm != null) { fContentLeafStack[fElementDepth] = cv; } } } private void ensureStackCapacity ( int newElementDepth) { if (newElementDepth == fElementQNamePartsStack.length ) { int[] newStack = new int[newElementDepth * 2]; System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth); fScopeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth); fGrammarNameSpaceIndexStack = newStack; QName[] newStackOfQueue = new QName[newElementDepth * 2]; System.arraycopy(this.fElementQNamePartsStack, 0, newStackOfQueue, 0, newElementDepth ); fElementQNamePartsStack = newStackOfQueue; QName qname = fElementQNamePartsStack[newElementDepth]; if (qname == null) { for (int i = newElementDepth; i < fElementQNamePartsStack.length; i++) { fElementQNamePartsStack[i] = new QName(); } } newStack = new int[newElementDepth * 2]; System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth); fElementEntityStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth); fElementIndexStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth); fContentSpecTypeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fValidationFlagStack, 0, newStack, 0, newElementDepth); fValidationFlagStack = newStack; ContentLeafNameTypeVector[] newStackV = new ContentLeafNameTypeVector[newElementDepth * 2]; System.arraycopy(fContentLeafStack, 0, newStackV, 0, newElementDepth); fContentLeafStack = newStackV; } } /** Call end element. */ public void callEndElement(int readerId) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n"); int prefixIndex = fCurrentElement.prefix; int elementType = fCurrentElement.rawname; if (fCurrentElementEntity != readerId) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH, XMLMessages.P78_NOT_WELLFORMED, new Object[] { fStringPool.toString(elementType) }, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } fElementDepth if (fValidating) { int elementIndex = fCurrentElementIndex; if (elementIndex != -1 && fCurrentContentSpecType != -1) { QName children[] = fElementChildren; int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1; int childrenLength = fElementChildrenLength - childrenOffset; if (DEBUG_ELEMENT_CHILDREN) { System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')'); System.out.print("offset: "); System.out.print(childrenOffset); System.out.print(", length: "); System.out.print(childrenLength); System.out.println(); printChildren(); printStack(); } int result = checkContent(elementIndex, children, childrenOffset, childrenLength); if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result); if (result != -1) { int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE; fGrammar.getElementDecl(elementIndex, fTempElementDecl); if (fTempElementDecl.type == XMLElementDecl.TYPE_EMPTY) { reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), "EMPTY"); } else reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex)); } } fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1; } fDocumentHandler.endElement(fCurrentElement); if (fNamespacesEnabled) { fNamespacesScope.decreaseDepth(); } // now pop this element off the top of the element stack //if (fElementDepth-- < 0) { if (fElementDepth < -1) { throw new RuntimeException("FWK008 Element stack underflow"); } if (fElementDepth < 0) { fCurrentElement.clear(); fCurrentElementEntity = -1; fCurrentElementIndex = -1; fCurrentContentSpecType = -1; fInElementContent = false; // Check after document is fully parsed // (1) check that there was an element with a matching id for every // IDREF and IDREFS attr (V_IDREF0) if (fValidating ) { try{ this.fValIDRef.validate( null, this.fValidateIDRef ); this.fValIDRefs.validate( null, this.fValidateIDRef ); }catch( InvalidDatatypeValueException ex ){ reportRecoverableXMLError( ex.getMajorCode(), ex.getMinorCode(), ex.getMessage() ); } } return; } //restore enclosing element to all the "current" variables // REVISIT: Validation. This information needs to be stored. fCurrentElement.prefix = -1; if (fNamespacesEnabled) { //If Namespace enable then localName != rawName fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].localpart; } else {//REVISIT - jeffreyr - This is so we still do old behavior when namespace is off fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].rawname; } fCurrentElement.rawname = fElementQNamePartsStack[fElementDepth].rawname; fCurrentElement.uri = fElementQNamePartsStack[fElementDepth].uri; fCurrentElement.prefix = fElementQNamePartsStack[fElementDepth].prefix; fCurrentElementEntity = fElementEntityStack[fElementDepth]; fCurrentElementIndex = fElementIndexStack[fElementDepth]; fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth]; fValidating = fValidationFlagStack[fElementDepth] == 0 ? true : false; fCurrentScope = fScopeStack[fElementDepth]; //if ( DEBUG_SCHEMA_VALIDATION ) { /** Call start CDATA section. */ /** Call end CDATA section. */ /** Call characters. */ /** Call processing instruction. */ /** Call comment. */ /** Start a new namespace declaration scope. */ /** End a namespace declaration scope. */ /** Sets the root element. */ /** * Returns true if the element declaration is external. * <p> * <strong>Note:</strong> This method is primarilly useful for * DTDs with internal and external subsets. */ private boolean getElementDeclIsExternal(int elementIndex) { /*if (elementIndex < 0 || elementIndex >= fElementCount) { return false; } int chunk = elementIndex >> CHUNK_SHIFT; int index = elementIndex & CHUNK_MASK; return (fElementDeclIsExternal[chunk][index] != 0); */ if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex); } return false; } /** Returns the content spec type for an element index. */ public int getContentSpecType(int elementIndex) { int contentSpecType = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecType = fTempElementDecl.type; } } return contentSpecType; } /** Returns the content spec handle for an element index. */ public int getContentSpecHandle(int elementIndex) { int contentSpecHandle = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecHandle = fTempElementDecl.contentSpecIndex; } } return contentSpecHandle; } // Protected methods // error reporting /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, null, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception { Object[] args = { fStringPool.toString(stringIndex1) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1) throws Exception { Object[] args = { string1 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception { Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception { Object[] args = { string1, string2 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception { Object[] args = { string1, string2, string3 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String,String) // content spec protected int whatCanGoHere(int elementIndex, boolean fullyValid, InsertableElementsInfo info) throws Exception { // Do some basic sanity checking on the info packet. First, make sure // that insertAt is not greater than the child count. It can be equal, // which means to get appendable elements, but not greater. Or, if // the current children array is null, that's bad too. // Since the current children array must have a blank spot for where // the insert is going to be, the child count must always be at least // one. // Make sure that the child count is not larger than the current children // array. It can be equal, which means get appendable elements, but not // greater. if (info.insertAt > info.childCount || info.curChildren == null || info.childCount < 1 || info.childCount > info.curChildren.length) { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_WCGHI, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } int retVal = 0; try { // Get the content model for this element final XMLContentModel cmElem = getElementContentModel(elementIndex); // And delegate this call to it retVal = cmElem.whatCanGoHere(fullyValid, info); } catch (CMException excToCatch) { // REVISIT - Translate caught error to the protected error handler interface int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); throw excToCatch; } return retVal; } // whatCanGoHere(int,boolean,InsertableElementsInfo):int // attribute information /** Protected for use by AttributeValidator classes. */ protected boolean getAttDefIsExternal(QName element, QName attribute) { int attDefIndex = getAttDef(element, attribute); if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex); } return false; } // Private methods // other /** Returns true if using a standalone reader. */ private boolean usingStandaloneReader() { return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader; } /** Returns a locator implementation. */ private LocatorImpl getLocatorImpl(LocatorImpl fillin) { Locator here = fErrorReporter.getLocator(); if (fillin == null) return new LocatorImpl(here); fillin.setPublicId(here.getPublicId()); fillin.setSystemId(here.getSystemId()); fillin.setLineNumber(here.getLineNumber()); fillin.setColumnNumber(here.getColumnNumber()); return fillin; } // getLocatorImpl(LocatorImpl):LocatorImpl // initialization /** Reset pool. */ private void poolReset() { try{ this.fValIDRef.validate(null, this.fResetIDRef ); this.fValIDRefs.validate(null, this.fResetIDRef ); } catch( InvalidDatatypeValueException ex ){ System.err.println("Error re-Initializing: ID,IDRef,IDRefs pools" ); } } // poolReset() /** Reset common. */ private void resetCommon(StringPool stringPool) throws Exception { fStringPool = stringPool; fValidating = fValidationEnabled; fValidationEnabledByDynamic = false; fDynamicDisabledByValidation = false; poolReset(); fCalledStartDocument = false; fStandaloneReader = -1; fElementChildrenLength = 0; fElementDepth = -1; fSeenRootElement = false; fSeenDoctypeDecl = false; fNamespacesScope = null; fNamespacesPrefix = -1; fRootElement.clear(); fAttrListHandle = -1; fCheckedForSchema = false; fCurrentScope = TOP_LEVEL_SCOPE; fCurrentSchemaURI = -1; fEmptyURI = - 1; fXsiPrefix = - 1; fXsiTypeValidator = null; fGrammar = null; fGrammarNameSpaceIndex = -1; //fGrammarResolver = null; if (fGrammarResolver != null) { fGrammarResolver.clearGrammarResolver(); } fGrammarIsDTDGrammar = false; fGrammarIsSchemaGrammar = false; init(); } // resetCommon(StringPool) /** Initialize. */ private void init() { fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); fEMPTYSymbol = fStringPool.addSymbol("EMPTY"); fANYSymbol = fStringPool.addSymbol("ANY"); fMIXEDSymbol = fStringPool.addSymbol("MIXED"); fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN"); fCDATASymbol = fStringPool.addSymbol("CDATA"); fIDSymbol = fStringPool.addSymbol("ID"); fIDREFSymbol = fStringPool.addSymbol("IDREF"); fIDREFSSymbol = fStringPool.addSymbol("IDREFS"); fENTITYSymbol = fStringPool.addSymbol("ENTITY"); fENTITIESSymbol = fStringPool.addSymbol("ENTITIES"); fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN"); fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS"); fNOTATIONSymbol = fStringPool.addSymbol("NOTATION"); fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION"); fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED"); fFIXEDSymbol = fStringPool.addSymbol("#FIXED"); fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>"); fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>"); fXMLLang = fStringPool.addSymbol("xml:lang"); } // init() // other // default attribute /** addDefaultAttributes. */ private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception { //System.out.println("XMLValidator#addDefaultAttributes"); //System.out.print(" "); //fGrammar.printAttributes(elementIndex); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) check that FIXED attrs have matching value (V_TAGd) // (3) add default attrs (FIXED and NOT_FIXED) fGrammar.getElementDecl(elementIndex,fTempElementDecl); int elementNameIndex = fTempElementDecl.name.localpart; int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); int firstCheck = attrIndex; int lastCheck = -1; while (attlistIndex != -1) { //int adChunk = attlistIndex >> CHUNK_SHIFT; //int adIndex = attlistIndex & CHUNK_MASK; fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl); // TO DO: For ericye Debug only /** addDTDDefaultAttributes. */ /** Queries the content model for the specified element index. */ /** Returns the validatator for an attribute type. */ /** Returns an attribute definition for an element type. */ /** Returns an attribute definition for an element type. */ /** Root element specified. */ /** Switchs to correct validating symbol tables when Schema changes.*/ /** Binds namespaces to the element and attributes. */ /** Warning. */ /** Error. */ /** Fatal error. */ /** Returns a string of the location. */ /** Validates element and attributes. */ /** Character data in content. */ /** * Check that the content of an element is valid. * <p> * This is the method of primary concern to the validator. This method is called * upon the scanner reaching the end tag of an element. At that time, the * element's children must be structurally validated, so it calls this method. * The index of the element being checked (in the decl pool), is provided as * well as an array of element name indexes of the children. The validator must * confirm that this element can have these children in this order. * <p> * This can also be called to do 'what if' testing of content models just to see * if they would be valid. * <p> * Note that the element index is an index into the element decl pool, whereas * the children indexes are name indexes, i.e. into the string pool. * <p> * A value of -1 in the children array indicates a PCDATA node. All other * indexes will be positive and represent child elements. The count can be * zero, since some elements have the EMPTY content model and that must be * confirmed. * * @param elementIndex The index within the <code>ElementDeclPool</code> of this * element. * @param childCount The number of entries in the <code>children</code> array. * @param children The children of this element. Each integer is an index within * the <code>StringPool</code> of the child element name. An index * of -1 is used to indicate an occurrence of non-whitespace character * data. * * @return The value -1 if fully valid, else the 0 based index of the child * that first failed. If the value returned is equal to the number * of children, then additional content is required to reach a valid * ending state. * * @exception Exception Thrown on error. */ private int checkContent(int elementIndex, QName[] children, int childOffset, int childCount) throws Exception { // Get the element name index from the element // REVISIT: Validation final int elementType = fCurrentElement.rawname; if (DEBUG_PRINT_CONTENT) { String strTmp = fStringPool.toString(elementType); System.out.println("Name: "+strTmp+", "+ "Count: "+childCount+", "+ "ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex)); for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) { if (index == 0) { System.out.print(" ("); } String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart); if (index + 1 == childCount) { System.out.println(childName + ")"); } else if (index + 1 == 10) { System.out.println(childName + ",...)"); } else { System.out.print(childName + ","); } } } // Get out the content spec for this element final int contentType = fCurrentContentSpecType; // debugging //System.out.println("~~~~~~in checkContent, fCurrentContentSpecType : " + fCurrentContentSpecType); // Deal with the possible types of content. We try to optimized here // by dealing specially with content models that don't require the // full DFA treatment. if (contentType == XMLElementDecl.TYPE_EMPTY) { // If the child count is greater than zero, then this is // an error right off the bat at index 0. if (childCount != 0) { return 0; } } else if (contentType == XMLElementDecl.TYPE_ANY) { // This one is open game so we don't pass any judgement on it // at all. Its assumed to fine since it can hold anything. } else if (contentType == XMLElementDecl.TYPE_MIXED || contentType == XMLElementDecl.TYPE_CHILDREN) { // Get the content model for this element, faulting it in if needed XMLContentModel cmElem = null; try { cmElem = getElementContentModel(elementIndex); int result = cmElem.validateContent(children, childOffset, childCount); if (result != -1 && fGrammarIsSchemaGrammar) { // REVISIT: not optimized for performance, EquivClassComparator comparator = new EquivClassComparator(fGrammarResolver, fStringPool); cmElem.setEquivClassComparator(comparator); result = cmElem.validateContentSpecial(children, childOffset, childCount); } return result; } catch(CMException excToCatch) { // REVISIT - Translate the caught exception to the protected error API int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } } else if (contentType == -1) { reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED, XMLMessages.VC_ELEMENT_VALID, elementType); } else if (contentType == XMLElementDecl.TYPE_SIMPLE ) { XMLContentModel cmElem = null; if (childCount > 0) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { "Can not have element children within a simple type content" }, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } else { try { fGrammar.getElementDecl(elementIndex, fTempElementDecl); DatatypeValidator dv = fTempElementDecl.datatypeValidator; // If there is xsi:type validator, substitute it. if ( fXsiTypeValidator != null ) { dv = fXsiTypeValidator; fXsiTypeValidator = null; } if (dv == null) { System.out.println("Internal Error: this element have a simpletype "+ "but no datatypevalidator was found, element "+fTempElementDecl.name +",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart)); } else { dv.validate(fDatatypeBuffer.toString(), null); } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { idve.getMessage() }, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } else { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_CST, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } // We succeeded return -1; } // checkContent(int,int,int[]):int /** * Checks that all declared elements refer to declared elements * in their content models. This method calls out to the error * handler to indicate warnings. */ private void printChildren() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('['); for (int i = 0; i < fElementChildrenLength; i++) { System.out.print(' '); QName qname = fElementChildren[i]; if (qname != null) { System.out.print(fStringPool.toString(qname.rawname)); } else { System.out.print("null"); } if (i < fElementChildrenLength - 1) { System.out.print(", "); } System.out.flush(); } System.out.print(" ]"); System.out.println(); } } private void printStack() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('{'); for (int i = 0; i <= fElementDepth; i++) { System.out.print(' '); System.out.print(fElementChildrenOffsetStack[i]); if (i < fElementDepth) { System.out.print(", "); } System.out.flush(); } System.out.print(" }"); System.out.println(); } } // Interfaces /** * AttributeValidator. */ public interface AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValue, int attType, int enumHandle) throws Exception; } // interface AttributeValidator /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } // Classes /** * AttValidatorCDATA. */ final class AttValidatorCDATA implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... return attValueHandle; } } // class AttValidatorCDATA /** * AttValidatorENTITY. */ final class AttValidatorENTITY implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENTITY - check that the value is an unparsed entity name (V_TAGa) if (!fEntityHandler.isUnparsedEntity(attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENTITY /** * AttValidatorENTITIES. */ final class AttValidatorENTITIES implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String entityName = tokenizer.nextToken(); // ENTITIES - check that each value is an unparsed entity name (V_TAGa) if (fValidating && !fEntityHandler.isUnparsedEntity(fStringPool.addSymbol(entityName))) { ok = false; } sb.append(entityName); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_ENTITIES_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENTITIES /** * AttValidatorNMTOKEN. */ final class AttValidatorNMTOKEN implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validNmtoken(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKEN /** * AttValidatorNMTOKENS. */ final class AttValidatorNMTOKENS implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String nmtoken = tokenizer.nextToken(); if (fValidating && !XMLCharacterProperties.validNmtoken(nmtoken)) { ok = false; } sb.append(nmtoken); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKENS /** * AttValidatorNOTATION. */ final class AttValidatorNOTATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // NOTATION - check that the value is in the AttDef enumeration (V_TAGo) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_NOTATION_ATTRIBUTES, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNOTATION /** * AttValidatorENUMERATION. */ final class AttValidatorENUMERATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENUMERATION - check that value is in the AttDef enumeration (V_TAG9) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_ENUMERATION, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENUMERATION } // class XMLValidator
package org.bitbucket.ardimaster.guarddogs; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Wolf; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; import java.util.Random; public class EventListener implements Listener { protected GuardDogs plugin; public EventListener(GuardDogs plugin) { this.plugin = plugin; } @EventHandler public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { if (!(event.getRightClicked() instanceof Wolf)) { return; } Wolf wolf = (Wolf) event.getRightClicked(); Player player = event.getPlayer(); if (player.getItemInHand().getType().equals(Material.PUMPKIN_SEEDS)) { if (!wolf.isTamed()) { player.sendMessage(ChatColor.RED + "You can't make this dog your guard dog as it isn't tamed!"); return; } if (!wolf.getOwner().equals(player)) { player.sendMessage(ChatColor.RED + "You can't make this dog your guard dog as it isn't yours!"); return; } if (plugin.createGuard(wolf)) { player.getInventory().removeItem(new ItemStack(Material.PUMPKIN_SEEDS, 1)); player.sendMessage(ChatColor.DARK_GREEN + "Guard dog" + ChatColor.GREEN + " ready for action"); wolf.setSitting(true); } else { player.sendMessage(ChatColor.RED + "This is already your guard dog!"); } } else if (player.getItemInHand().getType().equals(Material.STICK)) { if (!wolf.isTamed() || !wolf.getOwner().equals(player)) { player.sendMessage(ChatColor.RED + "This isn't your dog. Thus, it can't be your guard dog. " + "Thus, you can't disable it."); return; } if (plugin.removeGuard(wolf, player)) { player.sendMessage(ChatColor.DARK_GREEN + "Guard dog " + ChatColor.AQUA + "disabled."); } else { player.sendMessage(ChatColor.RED + "This isn't a guard dog, it's just a normal dog!"); } } } @EventHandler public void onEntityDeath(EntityDeathEvent event){ if (event.getEntity() instanceof Wolf) { Wolf wolf = (Wolf) event.getEntity(); plugin.deadGuard(wolf); } LivingEntity deadEntity = event.getEntity(); if (plugin.guardTargets.containsValue(deadEntity)) { for (Wolf wolf : plugin.guards) { if (plugin.guardTargets.get(wolf).equals(deadEntity)) { wolf.setSitting(true); plugin.guardTargets.remove(wolf); // TODO: Teleport guard back to its original location } } } } // TODO: Move to syncRepeatedTask running every 5 Ticks and extend. @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); LivingEntity playerEntity = player; ArrayList<LivingEntity> near = new ArrayList<>(); Random rand = new Random(); double radius = 15d; for (Wolf wolf : plugin.guards) { if (!wolf.isSitting()) { continue; } List<LivingEntity> all = wolf.getLocation().getWorld().getLivingEntities(); for (LivingEntity e : all) { if (e.getLocation().distance(wolf.getLocation()) <= radius) { if (wolf.getOwner().equals(player) && e.equals(playerEntity)) { continue; } if (e instanceof Wolf) { if (plugin.guards.contains(e)) { continue; } } near.add(e); } } LivingEntity target = near.get(rand.nextInt(near.size())); plugin.guardTargets.put(wolf, target); wolf.setSitting(false); wolf.damage(0d, target); } } }
package org.encog.solve.genetic.crossover; import java.util.HashSet; import java.util.Set; import org.encog.solve.genetic.genes.Gene; import org.encog.solve.genetic.genome.Chromosome; /** * A simple cross over where genes are simply "spliced". * Genes are not allowed to repeat. */ public class SpliceNoRepeat implements Crossover { /** * The cut length. */ private final int cutLength; /** * Get a list of the genes that have not been taken before. This is useful * if you do not wish the same gene to appear more than once in a * chromosome. * * @param source * The pool of genes to select from. * @param taken * An array of the taken genes. * @return Those genes in source that are not taken. */ private static Gene getNotTaken(final Chromosome source, final Set<Gene> taken) { for (Gene trial: source.getGenes() ) { if( !taken.contains(trial) ) { taken.add(trial); return trial; } } return null; } /** * Construct a splice crossover. * @param cutLength The cut length. */ public SpliceNoRepeat(final int cutLength) { this.cutLength = cutLength; } /** * Assuming this chromosome is the "mother" mate with the passed in * "father". * * @param father * The father. * @param offspring1 * Returns the first offspring * @param offspring2 * Returns the second offspring. */ public void mate(final Chromosome mother, final Chromosome father, final Chromosome offspring1, final Chromosome offspring2) { final int geneLength = father.getGenes().size(); // the chromosome must be cut at two positions, determine them final int cutpoint1 = (int) (Math.random() * (geneLength - cutLength)); final int cutpoint2 = cutpoint1 + cutLength; // keep track of which genes have been taken in each of the two // offspring, defaults to false. final Set<Gene> taken1 = new HashSet<Gene>(); final Set<Gene> taken2 = new HashSet<Gene>(); // handle cut section for (int i = 0; i < geneLength; i++) { if (!((i < cutpoint1) || (i > cutpoint2))) { offspring1.getGene(i).copy(father.getGene(i)); offspring2.getGene(i).copy(mother.getGene(i)); taken1.add(father.getGene(i)); taken2.add(mother.getGene(i)); } } // handle outer sections for (int i = 0; i < geneLength; i++) { if ((i < cutpoint1) || (i > cutpoint2)) { offspring1.getGene(i).copy( SpliceNoRepeat.getNotTaken(mother, taken1)); offspring2.getGene(i).copy( SpliceNoRepeat.getNotTaken(father, taken2)); } } } }
package org.exist.xquery.functions.validation; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.List; import org.exist.dom.QName; import org.exist.memtree.DocumentImpl; import org.exist.memtree.MemTreeBuilder; import org.exist.memtree.NodeImpl; import org.exist.storage.BrokerPool; import org.exist.storage.io.ExistIOException; import org.exist.validation.ValidationReport; import org.exist.validation.ValidationReportItem; import org.exist.validation.Validator; import org.exist.validation.internal.node.NodeInputStream; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.BooleanValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; import org.exist.xquery.value.ValueSequence; import org.xml.sax.helpers.AttributesImpl; /** * xQuery function for validation of XML instance documents * using grammars like XSDs and DTDs. * * @author Dannes Wessels (dizzzz@exist-db.org) */ public class Validation extends BasicFunction { private static final String simpleFunctionTxt= "Validate document specified by $a. " + "$a is of type xs:anyURI, or a node (element or returned by fn:doc()). "+ "The grammar files are resolved using the global catalog file(s)."; private static final String extendedFunctionTxt= "Validate document specified by $a using $b. "+ "$a is of type xs:anyURI, or a node (element or returned by fn:doc()). "+ "$b can point to an OASIS catalog file, a grammar (xml schema only) "+ "or a collection (path ends with '/')"; private final Validator validator; private final BrokerPool brokerPool; // Setup function signature public final static FunctionSignature signatures[] = { new FunctionSignature( new QName("validate", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), simpleFunctionTxt, new SequenceType[]{ new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE) }, new SequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE) ), new FunctionSignature( new QName("validate", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), extendedFunctionTxt, new SequenceType[]{ new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE), new SequenceType(Type.ANY_URI, Cardinality.EXACTLY_ONE) }, new SequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE) ), new FunctionSignature( new QName("validate-report", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), simpleFunctionTxt+" A simple report is returned.", new SequenceType[]{ new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE) }, new SequenceType(Type.NODE, Cardinality.EXACTLY_ONE) ), new FunctionSignature( new QName("validate-report", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), extendedFunctionTxt+" A simple report is returned.", new SequenceType[]{ new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE), new SequenceType(Type.ANY_URI, Cardinality.EXACTLY_ONE) }, new SequenceType(Type.NODE, Cardinality.EXACTLY_ONE) ) }; public Validation(XQueryContext context, FunctionSignature signature) { super(context, signature); brokerPool = context.getBroker().getBrokerPool(); validator = new Validator(brokerPool); } /** * @see BasicFunction#eval(Sequence[], Sequence) */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { // Check input parameters if (args.length != 1 && args.length != 2) { return Sequence.EMPTY_SEQUENCE; } InputStream is = null; ValidationReport vr = null; try { // Get inputstream of XML instance document if (args[0].getItemType() == Type.ANY_URI || args[0].getItemType() == Type.STRING) { // anyURI provided String url = args[0].getStringValue(); // Fix URL if (url.startsWith("/")) { url = "xmldb:exist://" + url; } is = new URL(url).openStream(); } else if (args[0].getItemType() == Type.ELEMENT || args[0].getItemType() == Type.DOCUMENT) { // Node provided is = new NodeInputStream(context, args[0].iterate()); // new NodeInputStream() } else { LOG.error("Wrong item type " + Type.getTypeName(args[0].getItemType())); throw new XPathException(getASTNode(), "wrong item type " + Type.getTypeName(args[0].getItemType())); } // Perform validation if (args.length == 1) { // Validate using system catalog vr = validator.validate(is); } else { // Validate using resource speciefied in second parameter String url = args[1].getStringValue(); if (url.startsWith("/")) { url = "xmldb:exist://" + url; } vr = validator.validate(is, url); } } catch (MalformedURLException ex) { LOG.error(ex); throw new XPathException(getASTNode(), "Invalid resource URI", ex); } catch (ExistIOException ex) { LOG.error(ex.getCause()); throw new XPathException(getASTNode(), "eXistIOexception", ex.getCause()); } catch (Exception ex) { LOG.error(ex); throw new XPathException(getASTNode(), "exception", ex); } finally { // Force release stream if(is != null){ try { is.close(); } catch (Exception ex) { LOG.debug("Attemted to close stream. ignore.", ex); } } } // Create response if (isCalledAs("validate")) { Sequence result = new ValueSequence(); result.add(new BooleanValue(vr.isValid())); return result; } else if (isCalledAs("validate-report")) { MemTreeBuilder builder = context.getDocumentBuilder(); NodeImpl result = writeReport(vr, builder); return result; } // Oops LOG.error("invoked with wrong function name"); throw new XPathException(getASTNode(), "unknown function"); } private NodeImpl writeReport(ValidationReport report, MemTreeBuilder builder) { // start root element int nodeNr = builder.startElement("", "report", "report", null); // validation status: valid or invalid builder.startElement("", "status", "status", null); if (report.isValid()) { builder.characters("valid"); } else { builder.characters("invalid"); } builder.endElement(); // namespace when available if (report.getNamespaceUri() != null) { builder.startElement("", "namespace", "namespace", null); builder.characters(report.getNamespaceUri()); builder.endElement(); } // validation duration builder.startElement("", "time", "time", null); builder.characters("" + report.getValidationDuration()); builder.endElement(); // print exceptions if any if (report.getThrowable() != null) { builder.startElement("", "exception", "exception", null); builder.characters("" + report.getThrowable().getMessage()); builder.endElement(); } // reusable attributes AttributesImpl attribs = new AttributesImpl(); // iterate validation report items, write message List cr = report.getValidationReportItemList(); for (Iterator iter = cr.iterator(); iter.hasNext();) { ValidationReportItem vri = (ValidationReportItem) iter.next(); // construct attributes attribs.addAttribute("", "level", "level", "CDATA", vri.getTypeText()); attribs.addAttribute("", "line", "line", "CDATA", Integer.toString(vri.getLineNumber())); attribs.addAttribute("", "column", "column", "CDATA", Integer.toString(vri.getColumnNumber())); if (vri.getRepeat() > 1) { attribs.addAttribute("", "repeat", "repeat", "CDATA", Integer.toString(vri.getRepeat())); } // write message builder.startElement("", "message", "message", attribs); builder.characters(vri.getMessage()); builder.endElement(); // Reuse attributes attribs.clear(); } // finish root element builder.endElement(); // return result return ((DocumentImpl) builder.getDocument()).getNode(nodeNr); } }
package org.jaudiotagger.tag.id3.framebody; import org.jaudiotagger.tag.datatype.*; import org.jaudiotagger.tag.InvalidTagException; import org.jaudiotagger.tag.id3.ID3v24Frames; import org.jaudiotagger.tag.id3.valuepair.TextEncoding; import org.jaudiotagger.tag.id3.valuepair.Languages; import java.nio.ByteBuffer; import java.io.ByteArrayOutputStream; import java.io.IOException; public class FrameBodyUSLT extends AbstractID3v2FrameBody implements ID3v23FrameBody,ID3v24FrameBody { /** * Creates a new FrameBodyUSLT datatype. */ public FrameBodyUSLT() { // setObject("Text Encoding", new Byte((byte) 0)); // setObject("Language", ""); // setObject(ObjectTypes.OBJ_DESCRIPTION, ""); // setObject("Lyrics/Text", ""); } /** * Copy constructor * * @param body */ public FrameBodyUSLT(FrameBodyUSLT body) { super(body); } /** * Creates a new FrameBodyUSLT datatype. * * @param textEncoding * @param language * @param description * @param text */ public FrameBodyUSLT(byte textEncoding, String language, String description, String text) { setObjectValue(DataTypes.OBJ_TEXT_ENCODING, new Byte(textEncoding)); setObjectValue(DataTypes.OBJ_LANGUAGE, language); setObjectValue(DataTypes.OBJ_DESCRIPTION, description); setObjectValue(DataTypes.OBJ_LYRICS, text); } /** * Creates a new FrameBodyUSLT datatype, populated from buffer * * @param byteBuffer * @throws InvalidTagException * @throws InvalidTagException */ public FrameBodyUSLT(ByteBuffer byteBuffer, int frameSize) throws InvalidTagException { super(byteBuffer, frameSize); } /** * Set a description field * * @param description */ public void setDescription(String description) { setObjectValue(DataTypes.OBJ_DESCRIPTION, description); } /** * Get a description field * * @return description */ public String getDescription() { return (String) getObjectValue(DataTypes.OBJ_DESCRIPTION); } /** * The ID3v2 frame identifier * * @return the ID3v2 frame identifier for this frame type */ public String getIdentifier() { return ID3v24Frames.FRAME_ID_UNSYNC_LYRICS; } /** * Set the language field * * @param language */ public void setLanguage(String language) { setObjectValue(DataTypes.OBJ_LANGUAGE, language); } /** * Get the language field * * @return language */ public String getLanguage() { return (String) getObjectValue(DataTypes.OBJ_LANGUAGE); } /** * Set the lyric field * * @param lyric */ public void setLyric(String lyric) { setObjectValue(DataTypes.OBJ_LYRICS, lyric); } /** * Get the lyric field * * @return lyrics */ public String getLyric() { return (String) getObjectValue(DataTypes.OBJ_LYRICS); } /** * Add additional lyric to the lyric field * * @param text */ public void addLyric(String text) { setLyric(getLyric() + text); ; } /** * * * @param line */ public void addLyric(Lyrics3Line line) { setLyric(getLyric() + line.writeString()); } public void write(ByteArrayOutputStream tagBuffer) throws IOException { if (((AbstractString) getObject(DataTypes.OBJ_DESCRIPTION)).canBeEncoded() == false) { this.setTextEncoding(TextEncoding.UTF_16); } if (((AbstractString) getObject(DataTypes.OBJ_LYRICS)).canBeEncoded() == false) { this.setTextEncoding(TextEncoding.UTF_16); } super.write(tagBuffer); } protected void setupObjectList() { objectList.add(new NumberHashMap(DataTypes.OBJ_TEXT_ENCODING, this, TextEncoding.TEXT_ENCODING_FIELD_SIZE)); objectList.add(new StringHashMap(DataTypes.OBJ_LANGUAGE, this, Languages.LANGUAGE_FIELD_SIZE)); objectList.add(new TextEncodedStringNullTerminated(DataTypes.OBJ_DESCRIPTION, this)); objectList.add(new TextEncodedStringSizeTerminated(DataTypes.OBJ_LYRICS, this)); } }
package org.owasp.esapi.reference; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.owasp.esapi.ESAPI; import org.owasp.esapi.HTTPUtilities; import org.owasp.esapi.Logger; import org.owasp.esapi.Randomizer; import org.owasp.esapi.User; import org.owasp.esapi.errors.AccessControlException; import org.owasp.esapi.errors.AuthenticationAccountsException; import org.owasp.esapi.errors.AuthenticationCredentialsException; import org.owasp.esapi.errors.AuthenticationException; import org.owasp.esapi.errors.AuthenticationLoginException; import org.owasp.esapi.errors.EncryptionException; public class FileBasedAuthenticator implements org.owasp.esapi.Authenticator { /** Key for user in session */ protected static final String USER = "ESAPIUserSessionKey"; /** The logger. */ private final Logger logger = ESAPI.getLogger("Authenticator"); /** The file that contains the user db */ private File userDB = null; /** How frequently to check the user db for external modifications */ private long checkInterval = 60 * 1000; /** The last modified time we saw on the user db. */ private long lastModified = 0; /** The last time we checked if the user db had been modified externally */ private long lastChecked = 0; private final int MAX_ACCOUNT_NAME_LENGTH = 250; /** * Fail safe main program to add or update an account in an emergency. * <P> * Warning: this method does not perform the level of validation and checks * generally required in ESAPI, and can therefore be used to create a username and password that do not comply * with the username and password strength requirements. * <P> * Example: Use this to add the alice account with the admin role to the users file: * <PRE> * * java -Dorg.owasp.esapi.resources="/path/resources" -classpath esapi.jar org.owasp.esapi.Authenticator alice password admin * * </PRE> * * @param args the args * @throws AuthenticationException the authentication exception */ public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Usage: Authenticator accountname password role"); return; } FileBasedAuthenticator auth = new FileBasedAuthenticator(); String accountName = args[0].toLowerCase(); String password = args[1]; String role = args[2]; DefaultUser user = (DefaultUser) auth.getUser(args[0]); if (user == null) { user = new DefaultUser(accountName); String newHash = auth.hashPassword(password, accountName); auth.setHashedPassword(user, newHash); user.addRole(role); user.enable(); user.unlock(); auth.userMap.put(new Long(user.getAccountId()), user); System.out.println("New user created: " + accountName); auth.saveUsers(); System.out.println("User account " + user.getAccountName() + " updated"); } else { System.err.println("User account " + user.getAccountName() + " already exists!"); } } private void setHashedPassword(User user, String hash) { List hashes = getAllHashedPasswords(user, true); hashes.add( 0, hash); if (hashes.size() > ESAPI.securityConfiguration().getMaxOldPasswordHashes() ) hashes.remove( hashes.size() - 1 ); logger.info(Logger.SECURITY, "New hashed password stored for " + user.getAccountName() ); } String getHashedPassword(User user) { List hashes = getAllHashedPasswords(user, false); return (String) hashes.get(0); } void setOldPasswordHashes(User user, List oldHashes) { List hashes = getAllHashedPasswords(user, true); if (hashes.size() > 1) hashes.removeAll(hashes.subList(1, hashes.size()-1)); hashes.addAll(oldHashes); } List getAllHashedPasswords(User user, boolean create) { List hashes = (List) passwordMap.get(user); if (hashes != null) return hashes; if (create) { hashes = new ArrayList(); passwordMap.put(user, hashes); return hashes; } throw new RuntimeException("No hashes found for " + user.getAccountName() + ". Is User.hashcode() and equals() implemented correctly?"); } List getOldPasswordHashes(User user) { List hashes = getAllHashedPasswords(user, false); if (hashes.size() > 1) return Collections.unmodifiableList(hashes.subList(1, hashes.size()-1)); return Collections.EMPTY_LIST; } /** The user map. */ private Map userMap = new HashMap(); // Map<User, List<String>>, where the strings are password hashes, with the current hash in entry 0 private Map passwordMap = new Hashtable(); /* * The currentUser ThreadLocal variable is used to make the currentUser available to any call in any part of an * application. Otherwise, each thread would have to pass the User object through the calltree to any methods that * need it. Because we want exceptions and log calls to contain user data, that could be almost anywhere. Therefore, * the ThreadLocal approach simplifies things greatly. <P> As a possible extension, one could create a delegation * framework by adding another ThreadLocal to hold the delegating user identity. */ private ThreadLocalUser currentUser = new ThreadLocalUser(); private class ThreadLocalUser extends InheritableThreadLocal { public Object initialValue() { return User.ANONYMOUS; } public User getUser() { return (User)super.get(); } public void setUser(User newUser) { super.set(newUser); } }; public FileBasedAuthenticator() { } /** * Clears all threadlocal variables from the thread. This should ONLY be called after * all possible ESAPI operations have concluded. If you clear too early, many calls will * fail, including logging, which requires the user identity. */ public void clearCurrent() { currentUser.setUser(null); } /* * (non-Javadoc) * * @see org.owasp.esapi.interfaces.IAuthenticator#createAccount(java.lang.String, java.lang.String) */ public synchronized User createUser(String accountName, String password1, String password2) throws AuthenticationException { loadUsersIfNecessary(); if (accountName == null) { throw new AuthenticationAccountsException("Account creation failed", "Attempt to create user with null accountName"); } if (getUser(accountName) != null) { throw new AuthenticationAccountsException("Account creation failed", "Duplicate user creation denied for " + accountName); } verifyAccountNameStrength(accountName); if ( password1 == null ) { throw new AuthenticationCredentialsException( "Invalid account name", "Attempt to create account " + accountName + " with a null password" ); } verifyPasswordStrength(null, password1); if (!password1.equals(password2)) throw new AuthenticationCredentialsException("Passwords do not match", "Passwords for " + accountName + " do not match"); DefaultUser user = new DefaultUser(accountName); try { setHashedPassword( user, hashPassword(password1, accountName) ); } catch (EncryptionException ee) { throw new AuthenticationException("Internal error", "Error hashing password for " + accountName, ee); } userMap.put(new Long( user.getAccountId() ), user); logger.info(Logger.SECURITY, "New user created: " + accountName); saveUsers(); return user; } /* * (non-Javadoc) * * @see org.owasp.esapi.interfaces.IAuthenticator#exists(java.lang.String) */ public boolean exists(String accountName) { return getUser(accountName) != null; } /* * (non-Javadoc) * * @see org.owasp.esapi.interfaces.IAuthenticator#generateStrongPassword(int, char[]) */ public String generateStrongPassword() { return generateStrongPassword(""); } private String generateStrongPassword(String oldPassword) { Randomizer r = ESAPI.randomizer(); int letters = r.getRandomInteger(4, 6); // inclusive, exclusive int digits = 7-letters; String passLetters = r.getRandomString(letters, DefaultEncoder.CHAR_PASSWORD_LETTERS ); String passDigits = r.getRandomString( digits, DefaultEncoder.CHAR_PASSWORD_DIGITS ); String passSpecial = r.getRandomString( 1, DefaultEncoder.CHAR_PASSWORD_SPECIALS ); String newPassword = passLetters + passSpecial + passDigits; return newPassword; } /* (non-Javadoc) * @see org.owasp.esapi.interfaces.IAuthenticator#changePassword(org.owasp.esapi.interfaces.IUser, java.lang.String, java.lang.String, java.lang.String) */ public void changePassword(User user, String currentPassword, String newPassword, String newPassword2) throws AuthenticationException { String accountName = user.getAccountName(); try { String currentHash = getHashedPassword(user); String verifyHash = hashPassword(currentPassword, accountName); if (!currentHash.equals(verifyHash)) { throw new AuthenticationCredentialsException("Password change failed", "Authentication failed for password change on user: " + accountName ); } if (newPassword == null || newPassword2 == null || !newPassword.equals(newPassword2)) { throw new AuthenticationCredentialsException("Password change failed", "Passwords do not match for password change on user: " + accountName ); } verifyPasswordStrength(currentPassword, newPassword); ((DefaultUser)user).setLastPasswordChangeTime(new Date()); String newHash = hashPassword(newPassword, accountName); if (getOldPasswordHashes(user).contains(newHash)) { throw new AuthenticationCredentialsException( "Password change failed", "Password change matches a recent password for user: " + accountName ); } setHashedPassword(user, newHash); logger.info(Logger.SECURITY, "Password changed for user: " + accountName ); } catch (EncryptionException ee) { throw new AuthenticationException("Password change failed", "Encryption exception changing password for " + accountName, ee); } } /* (non-Javadoc) * @see org.owasp.esapi.interfaces.IAuthenticator#verifyPassword(org.owasp.esapi.interfaces.IUser, java.lang.String) */ public boolean verifyPassword(User user, String password) { String accountName = user.getAccountName(); try { String hash = hashPassword(password, accountName); String currentHash = getHashedPassword(user); if (hash.equals(currentHash)) { ((DefaultUser)user).setLastLoginTime(new Date()); ((DefaultUser)user).setFailedLoginCount(0); logger.info(Logger.SECURITY, "Password verified for " + accountName ); return true; } } catch( EncryptionException e ) { logger.fatal(Logger.SECURITY, "Encryption error verifying password for " + accountName ); } logger.fatal(Logger.SECURITY, "Password verification failed for " + accountName ); return false; } /* * (non-Javadoc) * * @see org.owasp.esapi.interfaces.IAuthenticator#generateStrongPassword(int, char[]) */ public String generateStrongPassword(User user, String oldPassword) { String newPassword = generateStrongPassword(oldPassword); if (newPassword != null) logger.info(Logger.SECURITY, "Generated strong password for " + user.getAccountName()); return newPassword; } /* * Returns the currently logged user as set by the setCurrentUser() methods. Must not log in this method because the * logger calls getCurrentUser() and this could cause a loop. * * @see org.owasp.esapi.interfaces.IAuthenticator#getCurrentUser() */ public User getCurrentUser() { User user = (User) currentUser.get(); if (user == null) { user = User.ANONYMOUS; } return user; } /** * Gets the user object with the matching account name or null if there is no match. * * @param accountId the account name * @return the user, or null if not matched. */ public synchronized User getUser(long accountId) { if ( accountId == 0 ) { return User.ANONYMOUS; } loadUsersIfNecessary(); User user = (User) userMap.get(new Long( accountId )); return user; } /** * Gets the user object with the matching account name or null if there is no match. * * @param accountName the account name * @return the user, or null if not matched. */ public synchronized User getUser(String accountName) { if ( accountName == null ) { return User.ANONYMOUS; } loadUsersIfNecessary(); Iterator i = userMap.values().iterator(); while( i.hasNext() ) { User u = (User)i.next(); if ( u.getAccountName().equalsIgnoreCase(accountName) ) return u; } return null; } /** * Gets the user from session. * * @return the user from session */ protected User getUserFromSession() { HttpSession session = ESAPI.httpUtilities().getCurrentRequest().getSession(); return (User)session.getAttribute(USER); } /** * Returns the user if a matching remember token is found, or null if the token * is missing, token is corrupt, token is expired, account name does not match * and existing account, or hashed password does not match user's hashed password. */ protected DefaultUser getUserFromRememberToken() { Cookie token = ESAPI.httpUtilities().getCookie( ESAPI.currentRequest(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); if ( token == null ) { return null; } String[] data = null; try { data = ESAPI.encryptor().unseal( token.getValue() ).split( ":" ); } catch (EncryptionException e) { logger.warning(Logger.SECURITY, "Found corrupt or expired remember token" ); ESAPI.httpUtilities().killCookie( ESAPI.currentRequest(), ESAPI.currentResponse(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); return null; } if ( data.length != 3 ) { return null; } // data[0] is a random nonce, which can be ignored String username = data[1]; String password = data[2]; DefaultUser user = (DefaultUser) getUser( username ); if ( user == null ) { logger.warning( Logger.SECURITY, "Found valid remember token but no user matching " + username ); return null; } logger.warning( Logger.SECURITY, "Logging in user with remember token: " + user.getAccountName() ); try { user.loginWithPassword(password); } catch (AuthenticationException ae) { logger.warning( Logger.SECURITY, "Login via remember me cookie failed for user " + username, ae); ESAPI.httpUtilities().killCookie( ESAPI.currentRequest(), ESAPI.currentResponse(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); return null; } return user; } /** * Gets the user names. * * @return list of user account names */ public synchronized Set getUserNames() { loadUsersIfNecessary(); HashSet results = new HashSet(); Iterator i = userMap.values().iterator(); while( i.hasNext() ) { User u = (User)i.next(); results.add( u.getAccountName() ); } return results; } /* * (non-Javadoc) * * @see org.owasp.esapi.interfaces.IAuthenticator#hashPassword(java.lang.String, java.lang.String) */ public String hashPassword(String password, String accountName) throws EncryptionException { String salt = accountName.toLowerCase(); return ESAPI.encryptor().hash(password, salt); } /** * Load users. * * @return the hash map * @throws AuthenticationException the authentication exception */ protected void loadUsersIfNecessary() { if (userDB == null) { userDB = new File((ESAPI.securityConfiguration()).getResourceDirectory(), "users.txt"); } // We only check at most every checkInterval milliseconds long now = System.currentTimeMillis(); if (now - lastChecked < checkInterval) { return; } lastChecked = now; if (lastModified == userDB.lastModified()) { return; } loadUsersImmediately(); } // file was touched so reload it protected void loadUsersImmediately() { synchronized( this ) { logger.trace(Logger.SECURITY, "Loading users from " + userDB.getAbsolutePath(), null); BufferedReader reader = null; try { HashMap map = new HashMap(); reader = new BufferedReader(new FileReader(userDB)); String line = null; while ((line = reader.readLine()) != null) { if (line.length() > 0 && line.charAt(0) != ' DefaultUser user = createUser(line); if (map.containsKey( new Long( user.getAccountId()))) { logger.fatal(Logger.SECURITY, "Problem in user file. Skipping duplicate user: " + user, null); } map.put( new Long( user.getAccountId() ), user); } } userMap = map; this.lastModified = System.currentTimeMillis(); logger.trace(Logger.SECURITY, "User file reloaded: " + map.size(), null); } catch (Exception e) { logger.fatal(Logger.SECURITY, "Failure loading user file: " + userDB.getAbsolutePath(), e); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { logger.fatal(Logger.SECURITY, "Failure closing user file: " + userDB.getAbsolutePath(), e); } } } } private DefaultUser createUser(String line) throws AuthenticationException { String[] parts = line.split(" *\\| *"); String accountIdString = parts[0]; long accountId = Long.parseLong(accountIdString); String accountName = parts[1]; verifyAccountNameStrength( accountName ); DefaultUser user = new DefaultUser( accountName ); user.accountId = accountId; String password = parts[2]; verifyPasswordStrength(null, password); setHashedPassword(user, password); String[] roles = parts[3].toLowerCase().split(" *, *"); for (int i=0; i<roles.length; i++) if (!"".equals(roles[i])) user.addRole(roles[i]); if (!"unlocked".equalsIgnoreCase(parts[4])) user.lock(); if ("enabled".equalsIgnoreCase(parts[5])) { user.enable(); } else { user.disable(); } // generate a new csrf token user.resetCSRFToken(); setOldPasswordHashes(user, Arrays.asList(parts[6].split(" *, *"))); user.setLastHostAddress("null".equals(parts[7]) ? null : parts[7]); user.setLastPasswordChangeTime(new Date( Long.parseLong(parts[8]))); user.setLastLoginTime(new Date( Long.parseLong(parts[9]))); user.setLastFailedLoginTime(new Date( Long.parseLong(parts[10]))); user.setExpirationTime(new Date( Long.parseLong(parts[11]))); user.setFailedLoginCount(Integer.parseInt(parts[12])); return user; } /** * Utility method to extract credentials and verify them. * * @param request * @param response * @return * @throws AuthenticationException * @throws */ private User loginWithUsernameAndPassword(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String username = request.getParameter(ESAPI.securityConfiguration().getUsernameParameterName()); String password = request.getParameter(ESAPI.securityConfiguration().getPasswordParameterName()); // if a logged-in user is requesting to login, log them out first User user = getCurrentUser(); if (user != null && !user.isAnonymous()) { logger.warning(Logger.SECURITY, "User requested relogin. Performing logout then authentication" ); user.logout(); } // now authenticate with username and password if (username == null || password == null) { if (username == null) { username = "unspecified user"; } throw new AuthenticationCredentialsException("Authentication failed", "Authentication failed for " + username + " because of null username or password"); } user = getUser(username); if (user == null) { throw new AuthenticationCredentialsException("Authentication failed", "Authentication failed because user " + username + " doesn't exist"); } user.loginWithPassword(password); request.setAttribute(user.getCSRFToken(), "authenticated"); return user; } /* * (non-Javadoc) * * @see org.owasp.esapi.interfaces.IAuthenticator#removeUser(java.lang.String) */ public synchronized void removeUser(String accountName) throws AuthenticationException { loadUsersIfNecessary(); User user = getUser(accountName); if (user == null) { throw new AuthenticationAccountsException("Remove user failed", "Can't remove invalid accountName " + accountName); } userMap.remove( new Long( user.getAccountId() )); System.out.println("Removing user " +user.getAccountName()); passwordMap.remove(user.getAccountName()); saveUsers(); } /** * Saves the user database to the file system. In this implementation you must call save to commit any changes to * the user file. Otherwise changes will be lost when the program ends. * * @throws AuthenticationException the authentication exception */ protected synchronized void saveUsers() throws AuthenticationException { PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(userDB)); writer.println(" writer.println("# accountId | accountName | hashedPassword | roles | locked | enabled | csrfToken | oldPasswordHashes | lastPasswordChangeTime | lastLoginTime | lastFailedLoginTime | expirationTime | failedLoginCount"); writer.println(); saveUsers(writer); writer.flush(); logger.info(Logger.SECURITY, "User file written to disk" ); } catch (IOException e) { logger.fatal(Logger.SECURITY, "Problem saving user file " + userDB.getAbsolutePath(), e ); throw new AuthenticationException("Internal Error", "Problem saving user file " + userDB.getAbsolutePath(), e); } finally { if (writer != null) { writer.close(); lastModified = userDB.lastModified(); lastChecked = lastModified; } } } /** * Save users. * * @param writer the writer * @throws IOException */ protected synchronized void saveUsers(PrintWriter writer) { Iterator i = getUserNames().iterator(); while (i.hasNext()) { String accountName = (String) i.next(); DefaultUser u = (DefaultUser) getUser(accountName); if ( u != null && !u.isAnonymous() ) { writer.println(save(u)); } else { new AuthenticationCredentialsException("Problem saving user", "Skipping save of user " + accountName ); } } } /** * Save. * * @return the string */ private String save(DefaultUser user) { StringBuffer sb = new StringBuffer(); sb.append( user.getAccountId() ); sb.append( " | " ); sb.append( user.getAccountName() ); sb.append( " | " ); sb.append( getHashedPassword(user) ); sb.append( " | " ); sb.append( dump(user.getRoles()) ); sb.append( " | " ); sb.append( user.isLocked() ? "locked" : "unlocked" ); sb.append( " | " ); sb.append( user.isEnabled() ? "enabled" : "disabled" ); sb.append( " | " ); sb.append( dump(getOldPasswordHashes(user)) ); sb.append( " | " ); sb.append( user.getLastHostAddress() ); sb.append( " | " ); sb.append( user.getLastPasswordChangeTime().getTime() ); sb.append( " | " ); sb.append( user.getLastLoginTime().getTime() ); sb.append( " | " ); sb.append( user.getLastFailedLoginTime().getTime() ); sb.append( " | " ); sb.append( user.getExpirationTime().getTime() ); sb.append( " | " ); sb.append( user.getFailedLoginCount() ); return sb.toString(); } /** * Dump a collection as a comma-separated list. * @return the string */ private String dump( Collection c ) { StringBuffer sb = new StringBuffer(); Iterator i = c.iterator(); while ( i.hasNext() ) { String s = (String)i.next(); sb.append( s ); if ( i.hasNext() ) sb.append( ","); } return sb.toString(); } /** * This method should be called for every HTTP request, to login the current user either from the session of HTTP * request. This method will set the current user so that getCurrentUser() will work properly. This method also * checks that the user's access is still enabled, unlocked, and unexpired before allowing login. For convenience * this method also returns the current user. * * @param request the request * @param response the response * @return the user * @throws AuthenticationException the authentication exception */ public User login(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if ( request == null || response == null ) { throw new AuthenticationCredentialsException( "Invalid request", "Request or response objects were null" ); } // if there's a user in the session then use that DefaultUser user = (DefaultUser)getUserFromSession(); // else if there's a remember token then use that if ( user == null ) { user = getUserFromRememberToken(); } // else try to verify credentials - throws exception if login fails if ( user == null ) { user = (DefaultUser)loginWithUsernameAndPassword(request, response); } // set last host address user.setLastHostAddress( request.getRemoteHost() ); // warn if this authentication request was not POST or non-SSL connection, exposing credentials or session id try { ESAPI.httpUtilities().assertSecureRequest( ESAPI.currentRequest() ); } catch( AccessControlException e ) { throw new AuthenticationException( "Attempt to login with an insecure request", e.getLogMessage(), e ); } // don't let anonymous user log in if (user.isAnonymous()) { user.logout(); throw new AuthenticationLoginException("Login failed", "Anonymous user cannot be set to current user. User: " + user.getAccountName() ); } // don't let disabled users log in if (!user.isEnabled()) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Disabled user cannot be set to current user. User: " + user.getAccountName() ); } // don't let locked users log in if (user.isLocked()) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Locked user cannot be set to current user. User: " + user.getAccountName() ); } // don't let expired users log in if (user.isExpired()) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Expired user cannot be set to current user. User: " + user.getAccountName() ); } // check session inactivity timeout if ( user.isSessionTimeout() ) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Session inactivity timeout: " + user.getAccountName() ); } // check session absolute timeout if ( user.isSessionAbsoluteTimeout() ) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Session absolute timeout: " + user.getAccountName() ); } request.getSession().setAttribute(USER, user); setCurrentUser(user); return user; } /** * Log out the current user. */ public void logout() { User user = getCurrentUser(); if ( user != null && !user.isAnonymous() ) { user.logout(); } } /* * (non-Javadoc) * * @see org.owasp.esapi.interfaces.IAuthenticator#setCurrentUser(org.owasp.esapi.User) */ public void setCurrentUser(User user) { currentUser.setUser(user); } /* * This implementation simply verifies that account names are at least 5 characters long. This helps to defeat a * brute force attack, however the real strength comes from the name length and complexity. * * @see org.owasp.esapi.interfaces.IAuthenticator#validateAccountNameStrength(java.lang.String) */ /* * (non-Javadoc) * * @see org.owasp.esapi.interfaces.IAuthenticator#verifyAccountNameStrength(java.lang.String) */ public void verifyAccountNameStrength(String newAccountName) throws AuthenticationException { if (newAccountName == null) { throw new AuthenticationCredentialsException("Invalid account name", "Attempt to create account with a null account name"); } if (!ESAPI.validator().isValidInput("verifyAccountNameStrength", newAccountName, "AccountName", MAX_ACCOUNT_NAME_LENGTH, false )) { throw new AuthenticationCredentialsException("Invalid account name", "New account name is not valid: " + newAccountName); } } /* * This implementation checks: - for any 3 character substrings of the old password - for use of a length * * character sets > 16 (where character sets are upper, lower, digit, and special (non-Javadoc) * * @see org.owasp.esapi.interfaces.IAuthenticator#verifyPasswordStrength(java.lang.String) */ public void verifyPasswordStrength(String oldPassword, String newPassword) throws AuthenticationException { if ( oldPassword == null ) oldPassword = ""; if ( newPassword == null ) throw new AuthenticationCredentialsException("Invalid password", "New password cannot be null" ); // can't change to a password that contains any 3 character substring of old password int length = oldPassword.length(); for (int i = 0; i < length - 2; i++) { String sub = oldPassword.substring(i, i + 3); if (newPassword.indexOf(sub) > -1 ) { throw new AuthenticationCredentialsException("Invalid password", "New password cannot contain pieces of old password" ); } } // new password must have enough character sets and length int charsets = 0; for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_LOWERS, newPassword.charAt(i)) > 0) { charsets++; break; } for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_UPPERS, newPassword.charAt(i)) > 0) { charsets++; break; } for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_DIGITS, newPassword.charAt(i)) > 0) { charsets++; break; } for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_SPECIALS, newPassword.charAt(i)) > 0) { charsets++; break; } // calculate and verify password strength int strength = newPassword.length() * charsets; if (strength < 16) { throw new AuthenticationCredentialsException("Invalid password", "New password is not long and complex enough"); } } }
import java.util.ArrayList; public class Transactions { private ArrayList<Entry> transactions; private FileIO fileIO; private String transactionLocation; /** * Constructor for creating a transaction session. * @param transactionLocation The location of the daily transaction file. * @param accountLocation The location of the user accounts file. * @param ticketLocation The location of the available tickets file. * @param newAccountLocation The location of the output user accounts file. * @param newTicketLocation The location of the output available tickets file. */ public Transactions(final String transactionLocation, final String accountLocation, final String ticketLocation, final String newAccountLocation, final String newTicketLocation) { this.transactionLocation = transactionLocation; this.fileIO = new FileIO(accountLocation, ticketLocation, newAccountLocation, newTicketLocation); this.transactions = new ArrayList<Entry>(); } public ArrayList<Entry> getTransactions() { return this.transactions; } /** * * @param transactions */ public void setTransactions(final ArrayList<Entry> transactions) { this.transactions = transactions; } public void logout() { throw new UnsupportedOperationException(); } /** * * @param buyName * @param event * @param numTickets * @param sellName */ public boolean buy(final String buyName, final String event, final int numTickets, final String sellName) { throw new UnsupportedOperationException(); } /** * * @param sellName * @param event * @param sellPrice * @param availTicket */ public boolean sell(final String sellName, final String event, final double sellPrice, final int availTicket) { throw new UnsupportedOperationException(); } /** * * @param newUser * @param accountType * @param accountBalance */ public boolean create(final String newUser, final String accountType, final double accountBalance) { throw new UnsupportedOperationException(); } /** * * @param username */ public boolean delete(final String username) { throw new UnsupportedOperationException(); } /** * * @param buyName * @param sellName * @param account */ public boolean refund(final String buyName, final String sellName, final double account) { throw new UnsupportedOperationException(); } /** * * @param username * @param amount */ public boolean addcredit(final String username, final double amount) { throw new UnsupportedOperationException(); } }
package pitt.search.semanticvectors.vectors; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import java.util.logging.Logger; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.OpenBitSet; /** * Binary implementation of Vector. * * Uses an "elemental" representation which is a single bit string (Lucene OpenBitSet). * * Superposes on this a "semantic" representation which contains the weights with which different * vectors have been added (superposed) onto this one. Calling {@link #superpose} causes the * voting record to be updated, but for performance the votes are not tallied back into the * elemental bit set representation until {@link #normalize} or one of the writing functions * is called. * * @author Trevor Cohen */ public class BinaryVector implements Vector { public static final Logger logger = Logger.getLogger(BinaryVector.class.getCanonicalName()); // TODO: Determing proper interface for default constants. /** * Number of decimal places to consider in weighted superpositions of binary vectors. * Higher precision requires additional memory during training. */ public static final int BINARY_VECTOR_DECIMAL_PLACES = 2; public static final boolean BINARY_BINDING_WITH_PERMUTE = false; private static final int DEBUG_PRINT_LENGTH = 64; private Random random; private final int dimension; /** * Elemental representation for binary vectors. */ protected OpenBitSet bitSet; private boolean isSparse; /** * Representation of voting record for superposition. Each OpenBitSet object contains one bit * of the count for the vote in each dimension. The count for any given dimension is derived from * all of the bits in that dimension across the OpenBitSets in the voting record. * * The precision of the voting record (in number of decimal places) is defined upon initialization. * By default, if the first weight added is an integer, rounding occurs to the nearest integer. * Otherwise, rounding occurs to the second binary place. */ private ArrayList<OpenBitSet> votingRecord; int decimalPlaces = 0; /** Accumulated sum of the weights with which vectors have been added into the voting record */ int totalNumberOfVotes = 0; // TODO(widdows) Understand and comment this. int minimum = 0; // Used only for temporary internal storage. private OpenBitSet tempSet; public BinaryVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } this.dimension = dimension; this.bitSet = new OpenBitSet(dimension); this.isSparse = true; this.random = new Random(); } /** * Returns a new copy of this vector, in dense format. */ @SuppressWarnings("unchecked") public BinaryVector copy() { BinaryVector copy = new BinaryVector(dimension); copy.bitSet = (OpenBitSet) bitSet.clone(); if (!isSparse) copy.votingRecord = (ArrayList<OpenBitSet>) votingRecord.clone(); return copy; } public String toString() { StringBuilder debugString = new StringBuilder("BinaryVector."); if (isSparse) { debugString.append(" Elemental. First " + DEBUG_PRINT_LENGTH + " values are:\n"); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); } else { debugString.append(" Semantic. First " + DEBUG_PRINT_LENGTH + " values are:\n"); // output voting record for first DEBUG_PRINT_LENGTH dimension debugString.append("\nVOTING RECORD: \n"); for (int y =0; y < votingRecord.size(); y++) { for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(votingRecord.get(y).getBit(x) + " "); debugString.append("\n"); } // TODO - output count from first DEBUG_PRINT_LENGTH dimension debugString.append("\nNORMALIZED: "); this.normalize(); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\n"); // Calculate actual values for first 20 dimension double[] actualvals = new double[DEBUG_PRINT_LENGTH]; debugString.append("COUNTS : "); for (int x =0; x < votingRecord.size(); x++) { for (int y = 0; y < DEBUG_PRINT_LENGTH; y++) { if (votingRecord.get(x).fastGet(y)) actualvals[y] += Math.pow(2, x); } } for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) { debugString.append((int) ((minimum + actualvals[x]) / Math.pow(10, decimalPlaces)) + " "); } debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); debugString.append("Votes " + totalNumberOfVotes+"\n"); debugString.append("Minimum " + minimum + "\n"); } return debugString.toString(); } @Override public int getDimension() { return dimension; } public BinaryVector createZeroVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { logger.severe("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } return new BinaryVector(dimension); } @Override public boolean isZeroVector() { if (isSparse) { return bitSet.cardinality() == 0; } else { return (votingRecord == null) || (votingRecord.size() == 0); } } @Override /** * Generates a basic elemental vector with a given number of 1's and otherwise 0's. * For binary vectors, the numnber of 1's and 0's must be the same, half the dimension. * * @return representation of basic binary vector. */ public BinaryVector generateRandomVector(int dimension, int numEntries, Random random) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } // Check for balance between 1's and 0's if (numEntries != dimension / 2) { logger.severe("Attempting to create binary vector with unequal number of zeros and ones." + " Unlikely to produce meaningful results. Therefore, seedlength has been set to " + " dimension/2, as recommended for binary vectors"); numEntries = dimension / 2; } BinaryVector randomVector = new BinaryVector(dimension); randomVector.bitSet = new OpenBitSet(dimension); int testPlace = dimension - 1, entryCount = 0; // Iterate across dimension of bitSet, changing 0 to 1 if random(1) > 0.5 // until dimension/2 1's added. while (entryCount < numEntries) { testPlace = random.nextInt(dimension); if (!randomVector.bitSet.fastGet(testPlace)) { randomVector.bitSet.fastSet(testPlace); entryCount++; } } return randomVector; } @Override /** * Measures overlap of two vectors using 1 - normalized Hamming distance * * Causes this and other vector to be converted to dense representation. */ public double measureOverlap(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (isZeroVector()) return 0; BinaryVector binaryOther = (BinaryVector) other; if (binaryOther.isZeroVector()) return 0; // Calculate hamming distance in place using cardinality and XOR, then return bitset to // original state. double hammingDistance = OpenBitSet.xorCount(binaryOther.bitSet, this.bitSet); return 2*(0.5 - (hammingDistance / (double) dimension)); } @Override /** * Adds the other vector to this one. If this vector was an elemental vector, the * "semantic vector" components (i.e. the voting record and temporary bitset) will be * initialized. * * Note that the precision of the voting record (in decimal places) is decided at this point: * if the initialization weight is an integer, rounding will occur to the nearest integer. * If not, rounding will occur to the second decimal place. * * This is an attempt to save space, as voting records can be prohibitively expansive * if not contained. */ public void superpose(Vector other, double weight, int[] permutation) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (weight == 0d) return; if (other.isZeroVector()) return; BinaryVector binaryOther = (BinaryVector) other; if (isSparse) { if (Math.round(weight) != weight) { decimalPlaces = BINARY_VECTOR_DECIMAL_PLACES; } elementalToSemantic(); } if (permutation != null) { // Rather than permuting individual dimensions, we permute 64 bit groups at a time. // This should be considerably quicker, and dimension/64 should allow for sufficient // permutations if (permutation.length != dimension / 64) { throw new IllegalArgumentException("Binary vector of dimension " + dimension + " must have permutation of length " + dimension / 64 + " not " + permutation.length); } //TODO permute in place and reverse, to avoid creating a new BinaryVector here BinaryVector temp = binaryOther.copy(); temp.permute(permutation); superposeBitSet(temp.bitSet, weight); } else { superposeBitSet(binaryOther.bitSet, weight); } } /** * This method is the first of two required to facilitate superposition. The underlying representation * (i.e. the voting record) is an ArrayList of OpenBitSet, each with dimension "dimension", which can * be thought of as an expanding 2D array of bits. Each column keeps count (in binary) for the respective * dimension, and columns are incremented in parallel by sweeping a bitset across the rows. In any dimension * in which the BitSet to be added contains a "1", the effect will be that 1's are changed to 0's until a * new 1 is added (e.g. the column '110' would become '001' and so forth). * * The first method deals with floating point issues, and accelerates superposition by decomposing * the task into segments. * * @param incomingBitSet * @param weight */ protected void superposeBitSet(OpenBitSet incomingBitSet, double weight) { // If fractional weights are used, encode all weights as integers (1000 x double value). weight = (int) Math.round(weight * Math.pow(10, decimalPlaces)); if (weight == 0) return; // Keep track of number (or cumulative weight) of votes. totalNumberOfVotes += weight; // Decompose superposition task such that addition of some power of 2 (e.g. 64) is accomplished // by beginning the process at the relevant row (e.g. 7) instead of starting multiple (e.g. 64) // superposition processes at the first row. int logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logFloorOfWeight < votingRecord.size() - 1) { while (logFloorOfWeight > 0) { superposeBitSetFromRowFloor(incomingBitSet, logFloorOfWeight); weight = weight - (int) Math.pow(2,logFloorOfWeight); logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } // Add remaining component of weight incrementally. for (int x = 0; x < weight; x++) superposeBitSetFromRowFloor(incomingBitSet, 0); } /** * Performs superposition from a particular row by sweeping a bitset across the voting record * such that for any column in which the incoming bitset contains a '1', 1's are changed * to 0's until a new 1 can be added, facilitating incrementation of the * binary number represented in this column. * * @param incomingBitSet the bitset to be added * @param rowfloor the index of the place in the voting record to start the sweep at */ protected void superposeBitSetFromRowFloor(OpenBitSet incomingBitSet, int rowfloor) { // Attempt to save space when minimum value across all columns > 0 // by decrementing across the board and raising the minimum where possible. int max = getMaximumSharedWeight(); if (max > 0) { decrement(max); } // Handle overflow: if any column that will be incremented // contains all 1's, add a new row to the voting record. tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor; x < votingRecord.size() && tempSet.cardinality() > 0; x++) { tempSet.and(votingRecord.get(x)); } if (tempSet.cardinality() > 0) { votingRecord.add(new OpenBitSet(dimension)); } // Sweep copy of bitset to be added across rows of voting record. // If a new '1' is added, this position in the copy is changed to zero // and will not affect future rows. // The xor step will transform 1's to 0's or vice versa for // dimension in which the temporary bitset contains a '1'. votingRecord.get(rowfloor).xor(incomingBitSet); tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor + 1; x < votingRecord.size(); x++) { tempSet.andNot(votingRecord.get(x-1)); //if 1 already added, eliminate dimension from tempSet votingRecord.get(x).xor(tempSet); votingRecord.get(x).trimTrailingZeros(); //attempt to save in sparsely populated rows } } /** * Reverses a string - simplifies the decoding of the binary vector for the 'exact' method * although it wouldn't be difficult to reverse the counter instead */ public static String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return new StringBuffer(str).reverse().toString(); } /** * Sets {@link #tempSet} to be a bitset with a "1" in the position of every dimension * in the {@link #votingRecord} that exactly matches the target number. */ private void setTempSetToExactMatches(int target) { if (target == 0) { tempSet.set(0, dimension); tempSet.xor(votingRecord.get(0)); for (int x = 1; x < votingRecord.size(); x++) tempSet.andNot(votingRecord.get(x)); } else { String inbinary = reverse(Integer.toBinaryString(target)); tempSet.xor(tempSet); tempSet.xor(votingRecord.get(inbinary.indexOf("1"))); for (int q =0; q < votingRecord.size(); q++) { if (q < inbinary.length() && inbinary.charAt(q) == '1') tempSet.and(votingRecord.get(q)); else tempSet.andNot(votingRecord.get(q)); } } } /** * This method is used determine which dimension will receive 1 and which 0 when the voting * process is concluded. It produces an OpenBitSet in which * "1" is assigned to all dimension with a count > 50% of the total number of votes (i.e. more 1's than 0's added) * "0" is assigned to all dimension with a count < 50% of the total number of votes (i.e. more 0's than 1's added) * "0" or "1" are assigned to all dimension with a count = 50% of the total number of votes (i.e. equal 1's and 0's added) * * @return an OpenBitSet representing the superposition of all vectors added up to this point */ protected OpenBitSet concludeVote() { if (votingRecord.size() == 0 || votingRecord.size() == 1 && votingRecord.get(0).cardinality() ==0) return new OpenBitSet(dimension); else return concludeVote(totalNumberOfVotes); } protected OpenBitSet concludeVote(int target) { int target2 = (int) Math.ceil((double) target / (double) 2); target2 = target2 - minimum; // Unlikely other than in testing: minimum more than half the votes if (target2 < 0) { OpenBitSet ans = new OpenBitSet(dimension); ans.set(0, dimension); return ans; } boolean even = (target % 2 == 0); OpenBitSet result = concludeVote(target2, votingRecord.size() - 1); if (even) { setTempSetToExactMatches(target2); boolean switcher = true; // 50% chance of being true with split vote. for (int q = 0; q < dimension; q++) { if (tempSet.fastGet(q)) { switcher = !switcher; if (switcher) tempSet.fastClear(q); } } result.andNot(tempSet); } return result; } protected OpenBitSet concludeVote(int target, int row_ceiling) { /** logger.info("Entering conclude vote, target " + target + " row_ceiling " + row_ceiling + "voting record " + votingRecord.size() + " minimum "+ minimum + " index "+ Math.log(target)/Math.log(2) + " vector\n" + toString()); **/ if (target == 0) { OpenBitSet atLeastZero = new OpenBitSet(dimension); atLeastZero.set(0, dimension); return atLeastZero; } double rowfloor = Math.log(target)/Math.log(2); int row_floor = (int) Math.floor(rowfloor); //for 0 index int remainder = target - (int) Math.pow(2,row_floor); //System.out.println(target+"\t"+rowfloor+"\t"+row_floor+"\t"+remainder); if (row_ceiling == 0 && target == 1) { return votingRecord.get(0); } if (remainder == 0) { // Simple case - the number we're looking for is 2^n, so anything with a "1" in row n or above is true. OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); return definitePositives; } else { // Simple part of complex case: first get anything with a "1" in a row above n (all true). OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor+1; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); // Complex part of complex case: get those that have a "1" in the row of n. OpenBitSet possiblePositives = (OpenBitSet) votingRecord.get(row_floor).clone(); OpenBitSet definitePositives2 = concludeVote(remainder, row_floor-1); possiblePositives.and(definitePositives2); definitePositives.or(possiblePositives); return definitePositives; } } /** * Decrement every dimension. Assumes at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement() { tempSet.set(0, dimension); for (int q = 0; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Decrement every dimension by the number passed as a parameter. Again at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement(int weight) { if (weight == 0) return; minimum+= weight; int logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logfloor < votingRecord.size() - 1) { while (logfloor > 0) { selectedDecrement(logfloor); weight = weight - (int) Math.pow(2,logfloor); logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } for (int x = 0; x < weight; x++) { decrement(); } } public void selectedDecrement(int floor) { tempSet.set(0, dimension); for (int q = floor; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Returns the highest value shared by all dimensions. */ protected int getMaximumSharedWeight() { int thismaximum = 0; tempSet.xor(tempSet); // Reset tempset to zeros. for (int x = votingRecord.size() - 1; x >= 0; x tempSet.or(votingRecord.get(x)); if (tempSet.cardinality() == dimension) { thismaximum += (int) Math.pow(2, x); tempSet.xor(tempSet); } } return thismaximum; } @Override /** * Implements binding using permutations and XOR. */ public void bind(Vector other, int direction) { IncompatibleVectorsException.checkVectorsCompatible(this, other); BinaryVector binaryOther = (BinaryVector) other.copy(); if (direction > 0) { //as per Kanerva 2009: bind(A,B) = perm+(A) XOR B = C //this also functions as the left inverse: left inverse (A,C) = perm+(A) XOR C = B this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, 1)); //perm+(A) this.bitSet.xor(binaryOther.bitSet); //perm+(A) XOR B } else { //as per Kanerva 2009: right inverse(C,B) = perm-(C XOR B) = perm-(perm+(A)) = A this.bitSet.xor(binaryOther.bitSet); //C XOR B this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, -1)); //perm-(C XOR B) = A } } @Override /** * Implements inverse of binding using permutations and XOR. */ public void release(Vector other, int direction) { if (!BINARY_BINDING_WITH_PERMUTE) bind(other); else bind (other, direction); } @Override /** * Implements binding using exclusive OR. */ public void bind(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (!BINARY_BINDING_WITH_PERMUTE) { BinaryVector binaryOther = (BinaryVector) other; this.bitSet.xor(binaryOther.bitSet); } else { bind(other, 1); } } @Override /** * Implements inverse binding using exclusive OR. */ public void release(Vector other) { if (!BINARY_BINDING_WITH_PERMUTE) bind(other); else bind(other, -1); } @Override /** * Normalizes the vector, converting sparse to dense representations in the process. This approach deviates from the "majority rule" * approach that is standard in the Binary Spatter Code(). Rather, the probability of assigning a one in a particular dimension * is a function of the probability of encountering the number of votes in the voting record in this dimension. * * This will be slower than normalizeBSC() below, but discards less information with positive effects on accuracy in preliminary experiments * * As a simple example to illustrate why this would be the case, consider the superposition of vectors for the terms "jazz","jazz" and "rock" * With the BSC normalization, the vector produced is identical to "jazz" (as jazz wins the vote in each case). With probabilistic normalization, * the vector produced is somewhat similar to both "jazz" and "rock", with a similarity that is proportional to the weights assigned to the * superposition, e.g. 0.624000:jazz; 0.246000:rock * */ public void normalize() { if (votingRecord == null) return; if (votingRecord.size() == 1) { this.bitSet = votingRecord.get(0); return; } //clear bitset; this.bitSet.xor(this.bitSet); //Ensure that the same set of superposed vectors will always produce the same result long theSuperpositionSeed = 0; for (int q =0; q < votingRecord.size(); q++) theSuperpositionSeed += votingRecord.get(q).getBits()[0]; random.setSeed(theSuperpositionSeed); //Determine value above the universal minimum for each dimension of the voting record int[] counts = new int[dimension]; int max = totalNumberOfVotes; //Determine the maximum possible votes on the voting record int maxpossiblevotesonrecord = 0; for (int q=0; q < votingRecord.size(); q++) maxpossiblevotesonrecord += Math.pow(2, q); //For each possible value on the record, get a BitSet with a "1" in the //position of the dimensions that match this value for (int x = 1; x <= maxpossiblevotesonrecord; x++) { this.setTempSetToExactMatches(x); //no exact matches if (this.tempSet.cardinality() == 0) continue; //For each y==1 on said BitSet (indicating votes in dimension[y] == x) int y = tempSet.nextSetBit(0); //determine total number of votes double votes = minimum+x; //calculate standard deviations above/below the mean of max/2 double z = (votes - (max/2)) / (Math.sqrt(max)/2); //find proportion of data points anticipated within z standard deviations of the mean (assuming approximately normal distribution) double proportion = erf(z/Math.sqrt(2)); //convert into a value between 0 and 1 (i.e. centered on 0.5 rather than centered on 0) proportion = (1+proportion) /2; while (y != -1) { //probabilistic normalization if ((random.nextDouble()) <= proportion) this.bitSet.fastSet(y); y++; y = tempSet.nextSetBit(y); } } //housekeeping votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); totalNumberOfVotes = 1; tempSet = new OpenBitSet(dimension); minimum = 0; } // approximation of error function, equation 7.1.27 from //in Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables, //9th printing. New York: Dover, pp. 299-300, 1972. // error of approximation <= 5*10^-4 public double erf(double z) { //erf(-x) == -erf(x) double sign = Math.signum(z); z = Math.abs(z); double a1 = 0.278393, a2 = 0.230389, a3 = 0.000972, a4 = 0.078108; double sumterm = 1 + a1*z + a2*Math.pow(z,2) + a3*Math.pow(z,3) + a4*Math.pow(z,4); return sign * ( 1-1/(Math.pow(sumterm, 4))); } /** * Faster normalization according to the Binary Spatter Code's "majority" rule */ public void normalizeBSC() { if (!isSparse) this.bitSet = concludeVote(); votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); totalNumberOfVotes = 1; tempSet = new OpenBitSet(dimension); minimum = 0; } /** * Counts votes without normalizing vector (i.e. voting record is not altered). Used in SemanticVectorCollider. */ public void tallyVotes() { if (!isSparse) this.bitSet = concludeVote(); } @Override /** * Writes vector out to object output stream. Converts to dense format if necessary. */ public void writeToLuceneStream(IndexOutput outputStream) { if (isSparse) { elementalToSemantic(); } long[] bitArray = bitSet.getBits(); for (int i = 0; i < bitArray.length; i++) { try { outputStream.writeLong(bitArray[i]); } catch (IOException e) { logger.severe("Couldn't write binary vector to lucene output stream."); e.printStackTrace(); } } } @Override /** * Reads a (dense) version of a vector from a Lucene input stream. */ public void readFromLuceneStream(IndexInput inputStream) { long bitArray[] = new long[(dimension / 64)]; for (int i = 0; i < dimension / 64; ++i) { try { bitArray[i] = inputStream.readLong(); } catch (IOException e) { logger.severe("Couldn't read binary vector from lucene output stream."); e.printStackTrace(); } } this.bitSet = new OpenBitSet(bitArray, bitArray.length); this.isSparse = true; } @Override /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < dimension; ++i) { builder.append(Integer.toString(bitSet.getBit(i))); } return builder.toString(); } /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeLongToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < (bitSet.getBits().length); ++i) { builder.append(Long.toString(bitSet.getBits()[i])+"|"); } return builder.toString(); } @Override /** * Writes vector from a string of the form 01001 etc. */ public void readFromString(String input) { if (input.length() != dimension) { throw new IllegalArgumentException("Found " + (input.length()) + " possible coordinates: " + "expected " + dimension); } for (int i = 0; i < dimension; ++i) { if (input.charAt(i) == '1') bitSet.fastSet(i); } } /** * Automatically translate elemental vector (no storage capacity) into * semantic vector (storage capacity initialized, this will occupy RAM) */ protected void elementalToSemantic() { if (!isSparse) { logger.warning("Tried to transform an elemental vector which is not in fact elemental." + "This may be a programming error."); return; } votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); tempSet = new OpenBitSet(dimension); isSparse = false; } /** * Permute the long[] array underlying the OpenBitSet binary representation */ public void permute(int[] permutation) { if (permutation.length != getDimension() / 64) { throw new IllegalArgumentException("Binary vector of dimension " + getDimension() + " must have permutation of length " + getDimension() / 64 + " not " + permutation.length); } //TODO permute in place without creating additional long[] (if proves problematic at scale) long[] coordinates = bitSet.getBits(); long[] newCoordinates = new long[coordinates.length]; for (int i = 0; i < coordinates.length; ++i) { int positionToAdd = i; positionToAdd = permutation[positionToAdd]; newCoordinates[i] = coordinates[positionToAdd]; } bitSet.setBits(newCoordinates); } // Available for testing and copying. protected BinaryVector(OpenBitSet inSet) { this.dimension = (int) inSet.size(); this.bitSet = inSet; } // Available for testing protected int bitLength() { return bitSet.getBits().length; } // Monitor growth of voting record. protected int numRows() { if (isSparse) return 0; return votingRecord.size(); } }
package pl.grzegorz2047.survivalcg.managers; import com.zaxxer.hikari.HikariDataSource; import org.bukkit.Bukkit; import pl.grzegorz2047.survivalcg.SCG; import pl.grzegorz2047.survivalcg.mysql.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class MysqlManager { private final SCG plugin; private String host, user, password, db, usertable; private String guildstable, bantable; private Integer port; private HikariDataSource hikari; //Uzywaj hikari DeathQuery deathQuery; GuildQuery guildQuery; RankingQuery rankingQuery; UserQuery userQuery; private RelationQuery relationQuery; private String relationTable; public MysqlManager(String host, int port, String user, String password, String db, String usertable, String guildTable, String bantable, String relationTable, SCG plugin) { SettingsManager settings = plugin.getManager().getSettingsManager(); String prefix = settings.getSqlprefix(); this.host = host; this.port = port; this.user = user; this.password = password; this.db = db; this.usertable = prefix + usertable; this.guildstable = prefix + guildTable; this.bantable = prefix + bantable; this.relationTable = prefix + relationTable; this.plugin = plugin; connectToDB(); initiateQueries(); } private void initiateQueries() { this.deathQuery = new DeathQuery(this); this.deathQuery.checkIfTableExists(); this.guildQuery = new GuildQuery(this, plugin); this.guildQuery.checkIfTableExists(); this.rankingQuery = new RankingQuery(this); this.userQuery = new UserQuery(this, plugin); this.userQuery.checkIfTableExists(); this.relationQuery = new RelationQuery(this, plugin); this.relationQuery.checkIfTableExists(); } private void connectToDB() { //if mysql hikari = new HikariDataSource(); hikari.setMaximumPoolSize(3); hikari.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); hikari.addDataSourceProperty("serverName", host); hikari.addDataSourceProperty("port", port); hikari.addDataSourceProperty("databaseName", db); hikari.addDataSourceProperty("user", user); hikari.addDataSourceProperty("password", password); hikari.addDataSourceProperty("cachePrepStmts", true); hikari.addDataSourceProperty("prepStmtCacheSize", 250); hikari.addDataSourceProperty("prepStmtCacheSqlLimit", 2048); //else sqlite } public String getHost() { return host; } public String getUser() { return user; } public String getPassword() { return password; } public String getDb() { return db; } public String getUsertable() { return usertable; } public String getGuildTable() { return guildstable; } public Integer getPort() { return port; } public HikariDataSource getHikari() { return hikari; } public DeathQuery getDeathQuery() { return deathQuery; } public GuildQuery getGuildQuery() { return guildQuery; } public RankingQuery getRankingQuery() { return rankingQuery; } public UserQuery getUserQuery() { return userQuery; } public void dispose() { this.getHikari().close(); } public String getBantable() { return bantable; } public void setBantable(String bantable) { this.bantable = bantable; } public RelationQuery getRelationQuery() { return relationQuery; } public String getRelationTable() { return relationTable; } public void setRelationTable(String relationTable) { this.relationTable = relationTable; } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: // Tab Size = 8 package org.opennms.netmgt.snmp; import java.net.InetAddress; /** * @author david * */ public class SnmpAgentConfig { public static final int DEFAULT_TIMEOUT = 3000; public static final int DEFAULT_PORT = 161; public static final int VERSION1 = 1; public static final int VERSION2C = 2; public static final int VERSION3 = 3; public static final int DEFAULT_VERSION = VERSION1; public static final int GET_PDU = 1; public static final int GETNEXT_PDU = 2; public static final int GETBULK_PDU = 3; public static final int SET_PDU = 4; public static final int DEFAULT_RETRIES = 1; public static final int DEFAULT_MAX_REQUEST_SIZE = 65535; public static final int NOAUTH_NOPRIV = 1; public static final int AUTH_NOPRIV = 2; public static final int AUTH_PRIV = 3; public static final String DEFAULT_READ_COMMUNITY = "public"; public static final int DEFAULT_MAX_VARS_PER_PDU = 50; public static final int DEFAULT_PDU_TYPE = GET_PDU; public static final String DEFAULT_WRITE_COMMUNITY = "private"; public static final int DEFAULT_SECURITY_LEVEL = NOAUTH_NOPRIV; public static final String DEFAULT_SECURITY_NAME = "opennmsUser"; public static final String DEFAULT_AUTH_PASS_PHRASE = "0p3nNMSv3"; public static final String DEFAULT_AUTH_PROTOCOL = "MD5"; public static final String DEFAULT_PRIV_PROTOCOL = "DES"; public static final String DEFAULT_PRIV_PASS_PHRASE = DEFAULT_AUTH_PASS_PHRASE; private InetAddress m_address; private int m_timeout; private int m_retries; private int m_port; private int m_version; private int m_maxRequestSize; private int m_securityLevel; private String m_securityName; private String m_readCommunity; private int m_maxVarsPerPdu; private int m_pduType; private boolean m_adapted; private String m_writeCommunity; private String m_authPassPhrase; private String m_authProtocol; private String m_PrivProtocol; private String m_privPassPhrase; public SnmpAgentConfig() { setDefaults(); } public SnmpAgentConfig(InetAddress agentAddress) { m_address = agentAddress; setDefaults(); } private void setDefaults() { m_timeout = DEFAULT_TIMEOUT; m_retries = DEFAULT_RETRIES; m_port = DEFAULT_PORT; m_version = DEFAULT_VERSION; m_maxRequestSize = DEFAULT_MAX_REQUEST_SIZE; m_securityLevel = DEFAULT_SECURITY_LEVEL; m_securityName = DEFAULT_SECURITY_NAME; m_authPassPhrase = DEFAULT_AUTH_PASS_PHRASE; m_authProtocol = DEFAULT_AUTH_PROTOCOL; m_PrivProtocol = DEFAULT_PRIV_PROTOCOL; m_privPassPhrase = DEFAULT_PRIV_PASS_PHRASE; m_readCommunity = DEFAULT_READ_COMMUNITY; m_maxVarsPerPdu = DEFAULT_MAX_VARS_PER_PDU; m_pduType = DEFAULT_PDU_TYPE; m_adapted = false; m_writeCommunity = DEFAULT_WRITE_COMMUNITY; } public String toString() { StringBuffer buff = new StringBuffer("AgentConfig["); buff.append("Address: "+m_address); buff.append(", Port: "+m_port); buff.append(", Community: "+m_readCommunity); buff.append(", Timeout: "+m_timeout); buff.append(", Retries: "+m_retries); buff.append(", MaxVarsPerPdu: "+m_maxVarsPerPdu); buff.append(", Max request size: "+m_maxRequestSize); buff.append(", Version: "+m_version); if (m_version == VERSION3) { buff.append(", Security level: "+m_securityLevel); buff.append(", Security name: "+m_securityName); buff.append(", auth-passphrase: "+m_authPassPhrase); buff.append(", auth-protocol: "+m_authProtocol); buff.append(", priv-passprhase: "+m_privPassPhrase); buff.append(", priv-protocol: "+m_PrivProtocol); } buff.append("]"); return buff.toString(); } public InetAddress getAddress() { return m_address; } public void setAddress(InetAddress address) { m_address = address; } public int getPort() { return m_port; } public void setPort(int port) { m_port = port; } public int getTimeout() { return m_timeout; } public void setTimeout(int timeout) { m_timeout = timeout; } public int getVersion() { return m_version; } public void setVersion(int version) { m_version = version; } public int getRetries() { return m_retries; } public void setRetries(int retries) { m_retries = retries; } public int getSecurityLevel() { return m_securityLevel; } public void setSecurityLevel(int securityLevel) { m_securityLevel = securityLevel; } public String getSecurityName() { return m_securityName; } public void setSecurityName(String securityName) { m_securityName = securityName; } public void setReadCommunity(String community) { m_readCommunity = community; } public int getMaxRequestSize() { return m_maxRequestSize; } public void setMaxRequestSize(int maxRequestSize) { m_maxRequestSize = maxRequestSize; } public String getReadCommunity() { return m_readCommunity; } public int getMaxVarsPerPdu() { return m_maxVarsPerPdu; } public void setMaxVarsPerPdu(int maxVarsPerPdu) { m_maxVarsPerPdu = maxVarsPerPdu; } public int getPduType() { return m_pduType; } public void setPduType(int pduType) { m_pduType = pduType; } public void setAdapted(boolean adapted) { m_adapted = adapted; } public boolean isAdapted() { return m_adapted; } public String getWriteCommunity() { return m_writeCommunity; } public void setWriteCommunity(String community) { m_writeCommunity = community; } public static String versionToString(int version) { switch (version) { case VERSION1 : return "v1"; case VERSION2C : return "v2c"; case VERSION3 : return "v3"; default : return "unknown"; } } public String getAuthPassPhrase() { return m_authPassPhrase; } public void setAuthPassPhrase(String authPassPhrase) { m_authPassPhrase = authPassPhrase; } public String getPrivProtocol() { return m_PrivProtocol; } public void setPrivProtocol(String authPrivProtocol) { m_PrivProtocol = authPrivProtocol; } public String getAuthProtocol() { return m_authProtocol; } public void setAuthProtocol(String authProtocol) { m_authProtocol = authProtocol; } public String getPrivPassPhrase() { return m_privPassPhrase; } public void setPrivPassPhrase(String privPassPhrase) { m_privPassPhrase = privPassPhrase; } }
package io.teknek.tunit.integration; import static io.teknek.tunit.TUnit.*; import io.teknek.tunit.TUnit; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.ComparisonFailure; import org.junit.Test; public class TUnitTests { @Test public void basicImmutableTest(){ assertThat( new Callable<Integer>(){ public Integer call() throws Exception { return 5; }} ).afterWaitingAtMost(1000, TimeUnit.MILLISECONDS).isEqualTo(5); } @Test public void equalsShortcut(){ assertThat( new Callable<Integer>(){ public Integer call() throws Exception { return 5; }} ).isEqualTo(5); } @Test(expected=ComparisonFailure.class) public void shouldAssertTest(){ assertThat( new Callable<Integer>(){ public Integer call() throws Exception { return 6; }} ).afterWaitingAtMost(1000, TimeUnit.MILLISECONDS).isEqualTo(5); } class Changing implements Runnable { public volatile int x; public void run() { while (x < 10){ x++; try { Thread.sleep(10); } catch (InterruptedException e) { } } } } @Test public void aStatefulThingThatChanges() throws InterruptedException{ final Changing c = new Changing(); new Thread(c).start(); TUnit.assertThat( new Callable<Integer>() { public Integer call() throws Exception { return c.x; }}).afterWaitingAtMost(2000, TimeUnit.MILLISECONDS).isEqualTo(10); } @Test public void aStatefulThingThatChangesButNeverPasss() throws InterruptedException{ final Changing c = new Changing(); new Thread(c).start(); long start = System.currentTimeMillis(); boolean threw = false; try { TUnit.assertThat( new Callable<Integer>() { public Integer call() throws Exception { return c.x; }}).afterWaitingAtMost(2000, TimeUnit.MILLISECONDS).isEqualTo(40); } catch (ComparisonFailure ex){ threw = true; } Assert.assertTrue(threw); Assert.assertTrue((System.currentTimeMillis()- start ) >= 2000 ); } }
package javax.time.calendar; import static org.testng.Assert.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.SortedMap; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Test DateTimeFields. */ @Test public class TestDateTimeFields { private static final Map<DateTimeFieldRule<?>, Integer> NULL_MAP = null; private static final DateTimeFieldRule<?> NULL_RULE = null; private static final DateTimeFieldRule<Integer> YEAR_RULE = ISOChronology.yearRule(); private static final DateTimeFieldRule<MonthOfYear> MOY_RULE = ISOChronology.monthOfYearRule(); private static final DateTimeFieldRule<Integer> DOM_RULE = ISOChronology.dayOfMonthRule(); // private static final DateTimeFieldRule<Integer> DOY_RULE = ISOChronology.dayOfYearRule(); private static final DateTimeFieldRule<DayOfWeek> DOW_RULE = ISOChronology.dayOfWeekRule(); // private static final DateTimeFieldRule<Integer> QOY_RULE = ISOChronology.quarterOfYearRule(); // private static final DateTimeFieldRule<Integer> MOQ_RULE = ISOChronology.monthOfQuarterRule(); private static final DateTimeFieldRule<Integer> HOUR_RULE = ISOChronology.hourOfDayRule(); private static final DateTimeFieldRule<AmPmOfDay> AMPM_RULE = ISOChronology.amPmOfDayRule(); // private static final DateTimeFieldRule<Integer> HOUR_AMPM_RULE = ISOChronology.hourOfAmPmRule(); private static final DateTimeFieldRule<Integer> MIN_RULE = ISOChronology.minuteOfHourRule(); // private static final DateTimeFieldRule<Integer> MILLI_RULE = ISOChronology.milliOfDayRule(); // basics public void test_interfaces() { assertTrue(Calendrical.class.isAssignableFrom(DateTimeFields.class)); assertTrue(CalendricalMatcher.class.isAssignableFrom(DateTimeFields.class)); assertTrue(Iterable.class.isAssignableFrom(DateTimeFields.class)); assertTrue(Serializable.class.isAssignableFrom(DateTimeFields.class)); } @DataProvider(name="simple") Object[][] data_simple() { return new Object[][] { {DateTimeFields.EMPTY}, {DateTimeFields.of(YEAR_RULE, 2008)}, {DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6)}, }; } @Test(dataProvider="simple") public void test_serialization(DateTimeFields fields) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(fields); oos.close(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream( baos.toByteArray())); if (fields.toFieldValueMap().isEmpty()) { assertSame(ois.readObject(), fields); } else { assertEquals(ois.readObject(), fields); } } public void test_immutable() { Class<DateTimeFields> cls = DateTimeFields.class; assertTrue(Modifier.isPublic(cls.getModifiers())); assertTrue(Modifier.isFinal(cls.getModifiers())); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { assertTrue(Modifier.isFinal(field.getModifiers()), "Field:" + field.getName()); if (Modifier.isStatic(field.getModifiers()) == false) { assertTrue(Modifier.isPrivate(field.getModifiers()), "Field:" + field.getName()); } } Constructor<?>[] cons = cls.getDeclaredConstructors(); for (Constructor<?> con : cons) { assertTrue(Modifier.isPrivate(con.getModifiers())); } } public void singleton_empty() { DateTimeFields test = DateTimeFields.EMPTY; assertEquals(test.toFieldValueMap().size(), 0); assertSame(DateTimeFields.EMPTY, DateTimeFields.EMPTY); } // factories public void factory_fields_onePair() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008); assertFields(test, YEAR_RULE, 2008); } @Test(expectedExceptions=IllegalCalendarFieldValueException.class) public void factory_fields_onePair_invalidValue() { try { DateTimeFields.of(MOY_RULE, -1); } catch (IllegalCalendarFieldValueException ex) { assertEquals(ex.getRule(), MOY_RULE); throw ex; } } @Test(expectedExceptions=NullPointerException.class) public void factory_fields_onePair_null() { DateTimeFields.of(NULL_RULE, 1); } public void factory_fields_twoPairs() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertFields(test, YEAR_RULE, 2008, MOY_RULE, 6); } public void factory_fields_twoPairs_orderNotSignificant() { DateTimeFields test = DateTimeFields.of(MOY_RULE, 6, YEAR_RULE, 2008); assertFields(test, YEAR_RULE, 2008, MOY_RULE, 6); } public void factory_fields_twoPairs_sameFieldOverwrites() { DateTimeFields test = DateTimeFields.of(MOY_RULE, 6, MOY_RULE, 7); assertFields(test, MOY_RULE, 7); } @Test(expectedExceptions=IllegalCalendarFieldValueException.class) public void factory_fields_twoPairs_invalidValue() { try { DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, -1); } catch (IllegalCalendarFieldValueException ex) { assertEquals(ex.getRule(), MOY_RULE); throw ex; } } @Test(expectedExceptions=NullPointerException.class) public void factory_fields_twoPairs_nullFirst() { DateTimeFields.of(NULL_RULE, 1, MOY_RULE, 6); } @Test(expectedExceptions=NullPointerException.class) public void factory_fields_twoPairs_nullSecond() { DateTimeFields.of(MOY_RULE, 6, NULL_RULE, 1); } @Test(expectedExceptions=NullPointerException.class) public void factory_fields_twoPairs_nullBoth() { DateTimeFields.of(NULL_RULE, 1, NULL_RULE, 6); } public void factory_fields_map() { // using Hashtable checks for incorrect null handling Map<DateTimeFieldRule<?>, Integer> map = new Hashtable<DateTimeFieldRule<?>, Integer>(); map.put(YEAR_RULE, 2008); map.put(MOY_RULE, 6); DateTimeFields test = DateTimeFields.of(map); assertFields(test, YEAR_RULE, 2008, MOY_RULE, 6); } public void factory_fields_map_cloned() { Map<DateTimeFieldRule<?>, Integer> map = new HashMap<DateTimeFieldRule<?>, Integer>(); map.put(YEAR_RULE, 2008); DateTimeFields test = DateTimeFields.of(map); assertFields(test, YEAR_RULE, 2008); map.put(MOY_RULE, 6); assertFields(test, YEAR_RULE, 2008); } public void factory_fields_map_empty_singleton() { Map<DateTimeFieldRule<?>, Integer> map = new HashMap<DateTimeFieldRule<?>, Integer>(); assertSame(DateTimeFields.of(map), DateTimeFields.EMPTY); } @Test(expectedExceptions=NullPointerException.class) public void factory_fields_map_null() { DateTimeFields.of(NULL_MAP); } @Test(expectedExceptions=NullPointerException.class) public void factory_fields_map_nullKey() { Map<DateTimeFieldRule<?>, Integer> map = new HashMap<DateTimeFieldRule<?>, Integer>(); map.put(YEAR_RULE, 2008); map.put(null, 6); DateTimeFields.of(map); } @Test(expectedExceptions=NullPointerException.class) public void factory_fields_map_nullValue() { Map<DateTimeFieldRule<?>, Integer> map = new HashMap<DateTimeFieldRule<?>, Integer>(); map.put(YEAR_RULE, 2008); map.put(MOY_RULE, null); DateTimeFields.of(map); } // size() public void test_size0() { DateTimeFields test = DateTimeFields.EMPTY; assertEquals(test.size(), 0); } public void test_size1() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008); assertEquals(test.size(), 1); } public void test_size2() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(test.size(), 2); } // iterator() public void test_iterator0() { DateTimeFields test = DateTimeFields.EMPTY; Iterator<DateTimeFieldRule<?>> iterator = test.iterator(); assertEquals(iterator.hasNext(), false); } public void test_iterator2() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); Iterator<DateTimeFieldRule<?>> iterator = test.iterator(); assertEquals(iterator.hasNext(), true); assertEquals(iterator.next(), YEAR_RULE); assertEquals(iterator.hasNext(), true); assertEquals(iterator.next(), MOY_RULE); assertEquals(iterator.hasNext(), false); } // contains() public void test_contains() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(test.contains(YEAR_RULE), true); assertEquals(test.contains(MOY_RULE), true); } public void test_contains_null() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(test.contains(NULL_RULE), false); } public void test_contains_fieldNotPresent() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(test.contains(DOM_RULE), false); } // get() public void test_get() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(test.get(YEAR_RULE), (Integer) 2008); assertEquals(test.get(MOY_RULE), MonthOfYear.JUNE); } @Test(expectedExceptions=NullPointerException.class) public void test_get_null() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); test.get((CalendricalRule<?>) null); } public void test_get_fieldNotPresent() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(test.get(DOM_RULE), null); } // getInt() public void test_getInt() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(test.getInt(YEAR_RULE), 2008); assertEquals(test.getInt(MOY_RULE), 6); } @Test(expectedExceptions=NullPointerException.class) public void test_getInt_null() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); test.getInt(NULL_RULE); } @Test(expectedExceptions=UnsupportedRuleException.class) public void test_getInt_fieldNotPresent() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); try { test.getInt(DOM_RULE); } catch (UnsupportedRuleException ex) { assertEquals(ex.getRule(), DOM_RULE); throw ex; } } // getQuiet() public void test_getQuiet() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(test.getQuiet(YEAR_RULE), Integer.valueOf(2008)); assertEquals(test.getQuiet(MOY_RULE), Integer.valueOf(6)); } public void test_getQuiet_null() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(test.getQuiet(NULL_RULE), null); } public void test_getQuiet_fieldNotPresent() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(test.getQuiet(DOM_RULE), null); } // with() public void test_with() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields test = base.with(DOM_RULE, 30); assertFields(test, YEAR_RULE, 2008, MOY_RULE, 6, DOM_RULE, 30); // check original immutable assertFields(base, YEAR_RULE, 2008, MOY_RULE, 6); } @Test(expectedExceptions=IllegalCalendarFieldValueException.class) public void test_with_invalidValue() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); try { base.with(DOM_RULE, -1); } catch (IllegalCalendarFieldValueException ex) { assertEquals(ex.getRule(), DOM_RULE); throw ex; } } public void test_with_sameFieldOverwrites() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields test = base.with(MOY_RULE, 1); assertFields(test, YEAR_RULE, 2008, MOY_RULE, 1); } @Test(expectedExceptions=NullPointerException.class) public void test_with_null() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); test.with(NULL_RULE, 30); } // // with(Map) // public void test_with_map() { // // using Hashtable checks for incorrect null checking // DateTimeFields base = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule<?>, Integer> map = new Hashtable<DateTimeFieldRule<?>, Integer>(); // map.put(DOM_RULE, 30); // DateTimeFields test = base.with(map); // assertFields(test, YEAR_RULE, 2008, MOY_RULE, 6, DOM_RULE, 30); // // check original immutable // assertFields(base, YEAR_RULE, 2008, MOY_RULE, 6); // public void test_with_map_empty() { // DateTimeFields base = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule<?>, Integer> map = new HashMap<DateTimeFieldRule<?>, Integer>(); // DateTimeFields test = base.with(map); // assertSame(test, base); // public void test_with_map_invalidValue() { // DateTimeFields base = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule<?>, Integer> map = new HashMap<DateTimeFieldRule<?>, Integer>(); // map.put(DOM_RULE, -1); // try { // base.with(map); // assertEquals(ex.getFieldRule(), DOM_RULE); // assertFields(base, YEAR_RULE, 2008, MOY_RULE, 6); // throw ex; // public void test_with_map_sameFieldOverwrites() { // DateTimeFields base = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule<?>, Integer> map = new HashMap<DateTimeFieldRule<?>, Integer>(); // map.put(MOY_RULE, 1); // DateTimeFields test = base.with(map); // assertFields(test, YEAR_RULE, 2008, MOY_RULE, 1); // @Test(expectedExceptions=NullPointerException.class) // public void test_with_map_null() { // DateTimeFields test = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // test.with(NULL_MAP); // @Test(expectedExceptions=NullPointerException.class) // public void test_with_map_nullKey() { // DateTimeFields test = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule<?>, Integer> map = new HashMap<DateTimeFieldRule<?>, Integer>(); // map.put(null, 1); // test.with(map); // @Test(expectedExceptions=NullPointerException.class) // public void test_with_map_nullValue() { // DateTimeFields test = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule<?>, Integer> map = new HashMap<DateTimeFieldRule<?>, Integer>(); // map.put(DOM_RULE, null); // test.with(map); // @Test(expectedExceptions=NullPointerException.class) // public void test_with_map_nullBoth() { // DateTimeFields test = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule<?>, Integer> map = new HashMap<DateTimeFieldRule<?>, Integer>(); // map.put(null, null); // test.with(map); // with(DateTimeFields) public void test_with_fields() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields fields = DateTimeFields.of(DOM_RULE, 30); DateTimeFields test = base.with(fields); assertFields(test, YEAR_RULE, 2008, MOY_RULE, 6, DOM_RULE, 30); // check original immutable assertFields(base, YEAR_RULE, 2008, MOY_RULE, 6); } public void test_with_fields_sameFieldOverwrites() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields fields = DateTimeFields.of(MOY_RULE, 1); DateTimeFields test = base.with(fields); assertFields(test, YEAR_RULE, 2008, MOY_RULE, 1); } public void test_with_fields_self() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields test = base.with(base); assertSame(test, base); } public void test_with_fields_emptyAdd() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields test = base.with(DateTimeFields.EMPTY); assertSame(test, base); } @Test(expectedExceptions=NullPointerException.class) public void test_with_fields_null() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields fields = null; test.with(fields); } // withFieldRemoved() public void test_withFieldRemoved() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields test = base.withFieldRemoved(MOY_RULE); assertFields(test, YEAR_RULE, 2008); // check original immutable assertFields(base, YEAR_RULE, 2008, MOY_RULE, 6); } public void test_withFieldRemoved_fieldNotPresent() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields test = base.withFieldRemoved(DOM_RULE); assertSame(test, base); } public void test_withFieldRemoved_emptySingleton() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008); DateTimeFields test = base.withFieldRemoved(YEAR_RULE); assertSame(test, DateTimeFields.EMPTY); } @Test(expectedExceptions=NullPointerException.class) public void test_withFieldRemoved_null() { DateTimeFields test = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); test.withFieldRemoved(NULL_RULE); } // matchesCalendrical() public void test_matchesCalendrical_ymd_date() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR_RULE, 2008) .with(MOY_RULE, 6) .with(DOM_RULE, 30); LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), true); // check original immutable assertFields(test, YEAR_RULE, 2008, MOY_RULE, 6, DOM_RULE, 30); } public void test_matchesCalendrical_dowMatches() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR_RULE, 2008) .with(MOY_RULE, 6) .with(DOM_RULE, 30) .with(DOW_RULE, 1); LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), true); } public void test_matchesCalendrical_dowNotMatches() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR_RULE, 2008) .with(MOY_RULE, 6) .with(DOM_RULE, 30) .with(DOW_RULE, 2); // 2008-06-30 is Monday not Tuesday LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), false); } public void test_matchesCalendrical_ym_date_partialMatch() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR_RULE, 2008) .with(MOY_RULE, 6); LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), true); } public void test_matchesCalendrical_timeIgnored() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR_RULE, 2008) .with(MOY_RULE, 6) .with(DOM_RULE, 30) .with(HOUR_RULE, 12); LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), true); } public void test_matchesCalendrical_invalidDay() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR_RULE, 2008) .with(MOY_RULE, 6) .with(DOM_RULE, 31); LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), false); } public void test_matchesCalendrical_hm_time() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_RULE, 11) .with(MIN_RULE, 30); LocalTime time = LocalTime.of(11, 30); assertEquals(test.matchesCalendrical(time), true); // check original immutable assertFields(test, HOUR_RULE, 11, MIN_RULE, 30); } public void test_matchesCalendrical_amPmMatches() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_RULE, 11) .with(MIN_RULE, 30) .with(AMPM_RULE, 0); LocalTime time = LocalTime.of(11, 30); assertEquals(test.matchesCalendrical(time), true); } public void test_matchesCalendrical_amPmNotMatches() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_RULE, 11) .with(MIN_RULE, 30) .with(AMPM_RULE, 1); // time is 11:30, but this says PM LocalTime time = LocalTime.of(11, 30); assertEquals(test.matchesCalendrical(time), false); } public void test_matchesCalendrical_h_time_partialMatch() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_RULE, 11); LocalTime time = LocalTime.of(11, 30); assertEquals(test.matchesCalendrical(time), true); } public void test_matchesCalendrical_dateIgnored() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_RULE, 11) .with(MIN_RULE, 30) .with(YEAR_RULE, 2008); LocalTime time = LocalTime.of(11, 30); assertEquals(test.matchesCalendrical(time), true); } @Test(expectedExceptions=NullPointerException.class) public void test_matchesCalendrical_null() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_RULE, 11) .with(MIN_RULE, 30); test.matchesCalendrical(null); } @Test(expectedExceptions=NullPointerException.class) public void test_matchesCalendrical_null_emptyFields() { DateTimeFields test = DateTimeFields.EMPTY; test.matchesCalendrical((LocalTime) null); } // toFieldValueMap() public void test_toFieldValueMap() { DateTimeFields base = DateTimeFields.EMPTY .with(YEAR_RULE, 2008) .with(MOY_RULE, 6) .with(DOM_RULE, 30); SortedMap<DateTimeFieldRule<?>, Integer> test = base.toFieldValueMap(); assertEquals(test.size(), 3); assertEquals(test.get(YEAR_RULE).intValue(), 2008); assertEquals(test.get(MOY_RULE).intValue(), 6); assertEquals(test.get(DOM_RULE).intValue(), 30); Iterator<DateTimeFieldRule<?>> it = test.keySet().iterator(); assertEquals(it.next(), YEAR_RULE); assertEquals(it.next(), MOY_RULE); assertEquals(it.next(), DOM_RULE); // check original immutable test.clear(); assertFields(base, YEAR_RULE, 2008, MOY_RULE, 6, DOM_RULE, 30); } // equals() / hashCode() public void test_equals0() { DateTimeFields a = DateTimeFields.EMPTY; DateTimeFields b = DateTimeFields.EMPTY; assertEquals(a.equals(b), true); assertEquals(a.hashCode() == b.hashCode(), true); assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } public void test_equals1_equal() { DateTimeFields a = DateTimeFields.of(YEAR_RULE, 2008); DateTimeFields b = DateTimeFields.of(YEAR_RULE, 2008); assertEquals(a.equals(b), true); assertEquals(a.hashCode() == b.hashCode(), true); assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } public void test_equals1_notEqualValue() { DateTimeFields a = DateTimeFields.of(YEAR_RULE, 2008); DateTimeFields b = DateTimeFields.of(YEAR_RULE, 2007); assertEquals(a.equals(b), false); //assertEquals(a.hashCode() == b.hashCode(), false); // doesn't have to be so assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } public void test_equals1_notEqualField() { DateTimeFields a = DateTimeFields.of(MOY_RULE, 3); DateTimeFields b = DateTimeFields.of(DOM_RULE, 3); assertEquals(a.equals(b), false); //assertEquals(a.hashCode() == b.hashCode(), false); // doesn't have to be so assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } public void test_equals2_equal() { DateTimeFields a = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields b = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(a.equals(b), true); assertEquals(a.hashCode() == b.hashCode(), true); assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } public void test_equals2_notEqualOneValue() { DateTimeFields a = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields b = DateTimeFields.of(YEAR_RULE, 2007, MOY_RULE, 6); assertEquals(a.equals(b), false); //assertEquals(a.hashCode() == b.hashCode(), false); // doesn't have to be so assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } public void test_equals2_notEqualTwoValues() { DateTimeFields a = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields b = DateTimeFields.of(YEAR_RULE, 2007, MOY_RULE, 5); assertEquals(a.equals(b), false); //assertEquals(a.hashCode() == b.hashCode(), false); // doesn't have to be so assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } public void test_equals2_notEqualField() { DateTimeFields a = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); DateTimeFields b = DateTimeFields.of(YEAR_RULE, 2008, DOM_RULE, 6); assertEquals(a.equals(b), false); //assertEquals(a.hashCode() == b.hashCode(), false); // doesn't have to be so assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } public void test_equals_otherType() { DateTimeFields a = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(a.equals("Rubbish"), false); } public void test_equals_null() { DateTimeFields a = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); assertEquals(a.equals(null), false); } // toString() public void test_toString0() { DateTimeFields base = DateTimeFields.EMPTY; String test = base.toString(); assertEquals(test, "{}"); } public void test_toString1() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008); String test = base.toString(); assertEquals(test, "{ISO.Year=2008}"); } public void test_toString2() { DateTimeFields base = DateTimeFields.of(YEAR_RULE, 2008, MOY_RULE, 6); String test = base.toString(); assertEquals(test, "{ISO.Year=2008, ISO.MonthOfYear=6}"); } private void assertFields( DateTimeFields fields, DateTimeFieldRule<?> rule1, Integer value1) { Map<DateTimeFieldRule<?>, Integer> map = fields.toFieldValueMap(); assertEquals(map.size(), 1); assertEquals(map.get(rule1), value1); } private void assertFields( DateTimeFields fields, DateTimeFieldRule<?> rule1, Integer value1, DateTimeFieldRule<?> rule2, Integer value2) { Map<DateTimeFieldRule<?>, Integer> map = fields.toFieldValueMap(); assertEquals(map.size(), 2); assertEquals(map.get(rule1), value1); assertEquals(map.get(rule2), value2); } private void assertFields( DateTimeFields fields, DateTimeFieldRule<?> rule1, Integer value1, DateTimeFieldRule<?> rule2, Integer value2, DateTimeFieldRule<?> rule3, Integer value3) { Map<DateTimeFieldRule<?>, Integer> map = fields.toFieldValueMap(); assertEquals(map.size(), 3); assertEquals(map.get(rule1), value1); assertEquals(map.get(rule2), value2); assertEquals(map.get(rule3), value3); } // private void assertFields( // DateTimeFields fields, // DateTimeFieldRule<?> rule1, Integer value1, // DateTimeFieldRule<?> rule2, Integer value2, // DateTimeFieldRule<?> rule3, Integer value3, // DateTimeFieldRule<?> rule4, Integer value4) { // Map<DateTimeFieldRule<?>, Integer> map = fields.toFieldValueMap(); // assertEquals(map.size(), 4); // assertEquals(map.get(rule1), value1); // assertEquals(map.get(rule2), value2); // assertEquals(map.get(rule3), value3); // assertEquals(map.get(rule4), value4); // private void assertFields( // DateTimeFields fields, // DateTimeFieldRule<?> rule1, Integer value1, // DateTimeFieldRule<?> rule2, Integer value2, // DateTimeFieldRule<?> rule3, Integer value3, // DateTimeFieldRule<?> rule4, Integer value4, // DateTimeFieldRule<?> rule5, Integer value5) { // Map<DateTimeFieldRule<?>, Integer> map = fields.toFieldValueMap(); // assertEquals(map.size(), 5); // assertEquals(map.get(rule1), value1); // assertEquals(map.get(rule2), value2); // assertEquals(map.get(rule3), value3); // assertEquals(map.get(rule4), value4); // assertEquals(map.get(rule5), value5); // private void assertCalendrical( // Calendrical test, // DateTimeFields fields, // LocalDate date, // LocalTime time, // ZoneOffset offset, // TimeZone zone) { // assertEquals(test.getFields(), fields); // assertEquals(test.getDate(), date); // assertEquals(test.getTime(), time); // assertEquals(test.getOffset(), offset); // assertEquals(test.getZone(), zone); // assertEquals(test.toLocalDate(), date); // assertEquals(test.toLocalTime(), time); }
package jp.hashiwa.accountbook; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.nio.charset.Charset; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class ApplicationTest { private static final MediaType TEXT_HTML_UTF8 = new MediaType(MediaType.TEXT_HTML, Charset.forName("utf-8")); @Autowired private MockMvc mockMvc; @Test public void shouldReturnDefaultMessage() throws Exception { this.mockMvc.perform(get("/")) .andDo(print()) .andExpect(status().isOk()); //.andExpect(content().string(containsString("List of Applications"))); } @Test public void testTodoListShow() throws Exception { this.mockMvc.perform(get("/accountbook/show")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentType(TEXT_HTML_UTF8)) .andExpect(content().string(containsString("<title>Account Book</title>"))) .andExpect(content().string(containsString("table table-striped"))) .andExpect(content().string(containsString("Date"))) .andExpect(content().string(containsString("Amount"))) .andExpect(content().string(containsString("Name"))) .andExpect(content().string(containsString("Type"))) .andExpect(content().string(containsString("Description"))) .andExpect(content().string(containsString("Remarks"))); } @Test public void testTodoListCreate() throws Exception { this.mockMvc.perform(get("/accountbook/create")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentType(TEXT_HTML_UTF8)) .andExpect(content().string(containsString("<title>Account Book</title>"))) .andExpect(content().string(containsString("<form action=\"/accountbook/create\" method=\"post\">"))) .andExpect(content().string(containsString("<label for=\"inputDate\">Date</label>"))) .andExpect(content().string(containsString("<label for=\"inputAmount\">Amount</label>"))) .andExpect(content().string(containsString("<label for=\"inputName\">Name</label>"))) .andExpect(content().string(containsString("<label for=\"inputType\">Type</label>"))) .andExpect(content().string(containsString("<label for=\"inputDesc\">Description</label>"))) .andExpect(content().string(containsString("<label for=\"inputRemarks\">Remarks</label>"))); } }
package org.codehaus.mojo.build; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import org.apache.maven.scm.ScmBranch; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.ScmFileSet; import org.apache.maven.scm.ScmVersion; import org.apache.maven.scm.command.add.AddScmResult; import org.apache.maven.scm.command.blame.BlameScmRequest; import org.apache.maven.scm.command.blame.BlameScmResult; import org.apache.maven.scm.command.branch.BranchScmResult; import org.apache.maven.scm.command.changelog.ChangeLogScmRequest; import org.apache.maven.scm.command.changelog.ChangeLogScmResult; import org.apache.maven.scm.command.checkin.CheckInScmResult; import org.apache.maven.scm.command.checkout.CheckOutScmResult; import org.apache.maven.scm.command.diff.DiffScmResult; import org.apache.maven.scm.command.edit.EditScmResult; import org.apache.maven.scm.command.export.ExportScmResult; import org.apache.maven.scm.command.list.ListScmResult; import org.apache.maven.scm.command.mkdir.MkdirScmResult; import org.apache.maven.scm.command.remove.RemoveScmResult; import org.apache.maven.scm.command.status.StatusScmResult; import org.apache.maven.scm.command.tag.TagScmResult; import org.apache.maven.scm.command.unedit.UnEditScmResult; import org.apache.maven.scm.command.update.UpdateScmResult; import org.apache.maven.scm.manager.NoSuchScmProviderException; import org.apache.maven.scm.manager.ScmManager; import org.apache.maven.scm.provider.ScmProvider; import org.apache.maven.scm.repository.ScmRepository; import org.apache.maven.scm.repository.ScmRepositoryException; import org.apache.maven.scm.repository.UnknownRepositoryStructure; import org.codehaus.plexus.PlexusTestCase; public class TestCreateMojo extends PlexusTestCase { protected void setUp() throws Exception { // without this, locale test fails intermittenly depending timezone System.setProperty( "user.timezone", "UTC" ); super.setUp(); } public void testMessageFormat() throws Exception { CreateMojo mojo = new CreateMojo(); mojo.setFormat( "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}." ); mojo.setItems( Arrays.asList( new Object[] { new Integer( 7 ), "timestamp", "a disturbance in the Force" } ) ); Locale currentLocale = Locale.getDefault(); try { Locale.setDefault( Locale.US ); mojo.execute(); String rev = mojo.getRevision(); System.out.println( "rev = " + rev ); assertTrue( "Format didn't match.", rev.matches( "^At (\\d{1,2}:?){3} (AM|PM) on \\w{3} \\d{1,2}, \\d{4}, there was a disturbance in the Force on planet 7." ) ); } finally { Locale.setDefault( currentLocale ); } } /** * Test that dates are correctly formatted for different locales. */ public void testLocale() throws Exception { Date date = new Date( 0 ); // the epoch CreateMojo mojo = new CreateMojo(); mojo.setFormat( "{0,date}" ); mojo.setItems( Arrays.asList( new Object[] { date } ) ); mojo.execute(); assertEquals( DateFormat.getDateInstance( DateFormat.DEFAULT ).format( date ), mojo.getRevision() ); mojo.setLocale( "en" ); mojo.execute(); SimpleDateFormat dateFormat = new SimpleDateFormat( "MMM dd, yyyy"); dateFormat.parse( mojo.getRevision() ); //assertEquals( "Jan 1, 1970", mojo.getRevision() ); mojo.setLocale( "fi" ); mojo.execute(); dateFormat = new SimpleDateFormat( "dd.mm.yyyy"); dateFormat.parse( mojo.getRevision() ); //assertEquals( "1.1.1970", mojo.getRevision() ); mojo.setLocale( "de" ); mojo.execute(); dateFormat = new SimpleDateFormat( "dd.mm.yyyy"); dateFormat.parse( mojo.getRevision() ); //assertEquals( "01.01.1970", mojo.getRevision() ); } public void testSequenceFormat() throws Exception { CreateMojo mojo = new CreateMojo(); mojo.setBuildNumberPropertiesFileLocation( new File( getBasedir(), "target/buildNumber.properties" ) ); mojo.setFormat( "{0,number}.{1,number}.{2,number}" ); mojo.setItems( Arrays.asList( new Object[] { "buildNumber0", "buildNumber1", "buildNumber2" } ) ); File file = new File( getBasedir(), "target/buildNumber.properties" ); file.delete(); mojo.execute(); String rev = mojo.getRevision(); System.out.println( "rev = " + rev ); assertTrue( "Format didn't match.", rev.matches( "(\\d+\\.?){3}" ) ); assertTrue( file.exists() ); // for tests, we don't want this hanging around file.delete(); } public void testFilterBranchFromScmUrl() { CreateMojo mojo = new CreateMojo(); String scmUrlTrunk = "https://mifos.dev.java.net/svn/mifos/trunk"; assertEquals( "trunk", mojo.filterBranchFromScmUrl( scmUrlTrunk ) ); String scmUrlBranch = "https://mifos.dev.java.net/svn/mifos/branches/v1.2.x"; assertEquals( "branches/v1.2.x", mojo.filterBranchFromScmUrl( scmUrlBranch ) ); String scmUrlTag = "https://mifos.dev.java.net/svn/mifos/tags/v1.2.1"; assertEquals( "tags/v1.2.1", mojo.filterBranchFromScmUrl( scmUrlTag ) ); } public void testSpecialItemScmVersion() throws Exception { CreateMojo mojo = new CreateMojo(); mojo.setBuildNumberPropertiesFileLocation( new File( getBasedir(), "target/buildNumber.properties" ) ); mojo.setFormat( "{0}-{1}-{2}" ); mojo.setItems( Arrays.asList( "buildNumber0", "scmVersion", "buildNumber0" ) ); File file = new File( getBasedir(), "target/buildNumber.properties" ); file.delete(); mojo.setRevisionOnScmFailure( "scmrevision" ); mojo.setScmManager( new ScmManager() { public ScmRepository makeScmRepository( String string ) throws ScmRepositoryException, NoSuchScmProviderException { throw new ScmRepositoryException( "No SCM for testing." ); } public ScmRepository makeProviderScmRepository( String string, File file ) throws ScmRepositoryException, UnknownRepositoryStructure, NoSuchScmProviderException { throw new ScmRepositoryException( "No SCM for testing." ); } public List<String> validateScmRepository( String string ) { throw new UnsupportedOperationException( "Not supported yet." ); } public ScmProvider getProviderByUrl( String string ) throws ScmRepositoryException, NoSuchScmProviderException { throw new ScmRepositoryException( "No SCM for testing." ); } public ScmProvider getProviderByType( String string ) throws NoSuchScmProviderException { throw new NoSuchScmProviderException( "No SCM for testing." ); } public ScmProvider getProviderByRepository( ScmRepository sr ) throws NoSuchScmProviderException { throw new UnsupportedOperationException( "Not supported yet." ); } public void setScmProvider( String string, ScmProvider sp ) { throw new UnsupportedOperationException( "Not supported yet." ); } public void setScmProviderImplementation( String string, String string1 ) { throw new UnsupportedOperationException( "Not supported yet." ); } public AddScmResult add( ScmRepository sr, ScmFileSet sfs ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public AddScmResult add( ScmRepository sr, ScmFileSet sfs, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public BranchScmResult branch( ScmRepository sr, ScmFileSet sfs, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public BranchScmResult branch( ScmRepository sr, ScmFileSet sfs, String string, String string1 ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public ChangeLogScmResult changeLog( ScmRepository sr, ScmFileSet sfs, Date date, Date date1, int i, ScmBranch sb ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public ChangeLogScmResult changeLog( ScmRepository sr, ScmFileSet sfs, Date date, Date date1, int i, ScmBranch sb, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public ChangeLogScmResult changeLog( ChangeLogScmRequest changeLogScmRequest ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public ChangeLogScmResult changeLog( ScmRepository sr, ScmFileSet sfs, ScmVersion sv, ScmVersion sv1 ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public ChangeLogScmResult changeLog( ScmRepository sr, ScmFileSet sfs, ScmVersion sv, ScmVersion sv1, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public CheckInScmResult checkIn( ScmRepository sr, ScmFileSet sfs, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public CheckInScmResult checkIn( ScmRepository sr, ScmFileSet sfs, ScmVersion sv, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public CheckOutScmResult checkOut( ScmRepository sr, ScmFileSet sfs ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public CheckOutScmResult checkOut( ScmRepository sr, ScmFileSet sfs, ScmVersion sv ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public CheckOutScmResult checkOut( ScmRepository sr, ScmFileSet sfs, boolean bln ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public CheckOutScmResult checkOut( ScmRepository sr, ScmFileSet sfs, ScmVersion sv, boolean bln ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public DiffScmResult diff( ScmRepository sr, ScmFileSet sfs, ScmVersion sv, ScmVersion sv1 ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public EditScmResult edit( ScmRepository sr, ScmFileSet sfs ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public ExportScmResult export( ScmRepository sr, ScmFileSet sfs ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public ExportScmResult export( ScmRepository sr, ScmFileSet sfs, ScmVersion sv ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public ExportScmResult export( ScmRepository sr, ScmFileSet sfs, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public ExportScmResult export( ScmRepository sr, ScmFileSet sfs, ScmVersion sv, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public ListScmResult list( ScmRepository sr, ScmFileSet sfs, boolean bln, ScmVersion sv ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public MkdirScmResult mkdir( ScmRepository sr, ScmFileSet sfs, String string, boolean bln ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public RemoveScmResult remove( ScmRepository sr, ScmFileSet sfs, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public StatusScmResult status( ScmRepository sr, ScmFileSet sfs ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public TagScmResult tag( ScmRepository sr, ScmFileSet sfs, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public TagScmResult tag( ScmRepository sr, ScmFileSet sfs, String string, String string1 ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UnEditScmResult unedit( ScmRepository sr, ScmFileSet sfs ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UpdateScmResult update( ScmRepository sr, ScmFileSet sfs ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UpdateScmResult update( ScmRepository sr, ScmFileSet sfs, ScmVersion sv ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UpdateScmResult update( ScmRepository sr, ScmFileSet sfs, boolean bln ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UpdateScmResult update( ScmRepository sr, ScmFileSet sfs, ScmVersion sv, boolean bln ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UpdateScmResult update( ScmRepository sr, ScmFileSet sfs, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UpdateScmResult update( ScmRepository sr, ScmFileSet sfs, ScmVersion sv, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UpdateScmResult update( ScmRepository sr, ScmFileSet sfs, Date date ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UpdateScmResult update( ScmRepository sr, ScmFileSet sfs, ScmVersion sv, Date date ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UpdateScmResult update( ScmRepository sr, ScmFileSet sfs, Date date, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public UpdateScmResult update( ScmRepository sr, ScmFileSet sfs, ScmVersion sv, Date date, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public BlameScmResult blame( ScmRepository sr, ScmFileSet sfs, String string ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } public BlameScmResult blame( BlameScmRequest blameScmRequest ) throws ScmException { throw new UnsupportedOperationException( "Not supported yet." ); } } ); mojo.setUrlScm( "http://nonexistent" ); mojo.execute(); String rev = mojo.getRevision(); System.out.println( "rev = " + rev ); assertEquals( "1-scmrevision-2", rev ); // String result = mojo.getRevision() + "-" + } }
package org.cojen.tupl.rows; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import org.junit.*; import static org.junit.Assert.*; import org.cojen.tupl.*; /** * * * @author Brian S O'Neill */ public class ScanControllerTest { public static void main(String[] args) throws Exception { org.junit.runner.JUnitCore.main(ScanControllerTest.class.getName()); } @Test public void comparisons() throws Exception { byte[] a = "aaaa".getBytes(); byte[] b = "bbbb".getBytes(); byte[] c = "cccc".getBytes(); byte[] d = "dddd".getBytes(); byte[] e = "eeee".getBytes(); var c0 = new TestController(b, false, d, false); assertTrue(c0.isTooLow(a)); assertTrue(c0.isTooLow(b)); assertFalse(c0.isTooLow(c)); assertFalse(c0.isTooLow(d)); assertFalse(c0.isTooLow(e)); assertFalse(c0.isTooHigh(a)); assertFalse(c0.isTooHigh(b)); assertFalse(c0.isTooHigh(c)); assertTrue(c0.isTooHigh(d)); assertTrue(c0.isTooHigh(e)); var c1 = new TestController(b, false, d, true); assertTrue(c1.isTooLow(a)); assertTrue(c1.isTooLow(b)); assertFalse(c1.isTooLow(c)); assertFalse(c1.isTooLow(d)); assertFalse(c1.isTooLow(e)); assertFalse(c1.isTooHigh(a)); assertFalse(c1.isTooHigh(b)); assertFalse(c1.isTooHigh(c)); assertFalse(c1.isTooHigh(d)); assertTrue(c1.isTooHigh(e)); var c2 = new TestController(b, true, d, false); assertTrue(c2.isTooLow(a)); assertFalse(c2.isTooLow(b)); assertFalse(c2.isTooLow(c)); assertFalse(c2.isTooLow(d)); assertFalse(c2.isTooLow(e)); assertFalse(c2.isTooHigh(a)); assertFalse(c2.isTooHigh(b)); assertFalse(c2.isTooHigh(c)); assertTrue(c2.isTooHigh(d)); assertTrue(c2.isTooHigh(e)); var c3 = new TestController(b, true, d, true); assertTrue(c3.isTooLow(a)); assertFalse(c3.isTooLow(b)); assertFalse(c3.isTooLow(c)); assertFalse(c3.isTooLow(d)); assertFalse(c3.isTooLow(e)); assertFalse(c3.isTooHigh(a)); assertFalse(c3.isTooHigh(b)); assertFalse(c3.isTooHigh(c)); assertFalse(c3.isTooHigh(d)); assertTrue(c3.isTooHigh(e)); assertEquals(0, c0.compareLow(c1)); assertEquals(0, c1.compareLow(c0)); assertEquals(0, c2.compareLow(c3)); assertEquals(0, c3.compareLow(c2)); assertEquals(0, c0.compareHigh(c2)); assertEquals(0, c2.compareHigh(c0)); assertEquals(0, c1.compareHigh(c3)); assertEquals(0, c3.compareHigh(c1)); assertEquals(1, c0.compareLow(c2)); assertEquals(-1, c2.compareLow(c0)); assertEquals(-1, c0.compareHigh(c1)); assertEquals(1, c1.compareHigh(c0)); var c4 = new TestController(a, false, e, false); assertEquals(-1, c4.compareLow(c0)); assertEquals(1, c0.compareLow(c4)); assertEquals(1, c4.compareHigh(c0)); assertEquals(-1, c0.compareHigh(c4)); var c5 = new TestController(null, false, null, false); assertEquals(-1, c5.compareLow(c0)); assertEquals(1, c0.compareLow(c5)); assertEquals(1, c5.compareHigh(c0)); assertEquals(-1, c0.compareHigh(c5)); assertEquals(0, c5.compareLow(c5)); assertEquals(0, c5.compareHigh(c5)); } static class TestController extends SingleScanController<Object> { TestController(byte[] lowBound, boolean lowInclusive, byte[] highBound, boolean highInclusive) { super(lowBound, lowInclusive, highBound, highInclusive, false); } @Override public Object evalRow(Cursor c, LockResult result, Object row) { throw new UnsupportedOperationException(); } @Override public byte[] updateKey(Object row, byte[] original) { throw new UnsupportedOperationException(); } @Override public byte[] updateValue(Object row, byte[] original) { throw new UnsupportedOperationException(); } } @Test public void mergedScans() throws Exception { Database db = Database.open(new DatabaseConfig().directPageAccess(false)); Table<MyRow> table = db.openTable(MyRow.class); Table<MyRow2> table2 = db.openTable(MyRow2.class); for (int a=0; a<10; a++) { for (int b=0; b<10; b++) { { var row = table.newRow(); row.a(a); row.b(b); table.insert(null, row); } { var row = table2.newRow(); row.id(a * 1000 + b); row.a(a); row.b(b); table2.insert(null, row); } } } var rnd = new Random(0xcafebabe); var bob = new StringBuilder(64); for (int i=0; i<64; i++) { bob.append("(a ").append(op(">=", "> ", i, 0)) .append(" ? && a ").append(op("< ", "<=", i, 1)) .append(" ? && b ").append(op("==", "!=", i, 2)) .append(" ?) || (a ").append(op(">=", "> ", i, 3)) .append(" ? && a ").append(op("< ", "<=", i, 4)) .append(" ? && b ").append(op("==", "!=", i, 5)) .append(" ?)"); String filter = bob.toString(); bob.setLength(0); int total = 0; for (int j=0; j<10; j++) { total += mergedScans(rnd, table, table2, filter); } assertTrue(total > 0); } } private int mergedScans(Random rnd, Table<MyRow> table, Table<MyRow2> table2, String filter) throws Exception { var args = new Object[6]; for (int i=0; i<args.length; i++) { args[i] = rnd.nextInt(10); } var expect = new HashMap<Integer, MyRow2>(); { var scanner = table2.newRowScanner(null, filter, args); for (var row = scanner.row(); row != null; row = scanner.step()) { assertNull(expect.put(row.id(), row)); } } var scanner = (BasicRowScanner<MyRow>) table.newRowScanner(null, filter, args); var actual = new HashSet<MyRow>(); for (var row = scanner.row(); row != null; row = scanner.step()) { assertTrue(actual.add(row)); } assertEquals(expect.size(), actual.size()); for (MyRow row : actual) { assertNotNull(expect.remove(row.a() * 1000 + row.b())); } assertTrue(expect.isEmpty()); return actual.size(); } private static String op(String a, String b, int i, int shift) { return ((i >> shift) & 1) == 0 ? a : b; } @PrimaryKey({"a", "b"}) public interface MyRow { int a(); void a(int a); int b(); void b(int b); } @PrimaryKey("id") public interface MyRow2 { int id(); void id(int id); int a(); void a(int a); int b(); void b(int b); } }
package org.osiam.client; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import org.junit.Test; import org.junit.runner.RunWith; import org.osiam.client.connector.OsiamConnector; import org.osiam.client.exception.ConnectionInitializationException; import org.osiam.client.oauth.AccessToken; import org.osiam.client.oauth.GrantType; import org.osiam.client.oauth.Scope; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import static org.junit.Assert.fail; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/context.xml") @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class}) @DatabaseSetup(value = "/database_seed_activation.xml") @DatabaseTearDown(value = "/database_seed_activation.xml", type = DatabaseOperation.DELETE_ALL) public class UserActivationLoginIT extends AbstractIntegrationTestBase { @Test(expected = ConnectionInitializationException.class) public void log_in_as_an_deactivated_user_is_impossible() { getAccessToken("hsimpson", "koala"); fail("Exception expected"); } private AccessToken getAccessToken(String userName, String password) { return new OsiamConnector.Builder() .setAuthServiceEndpoint(AUTH_ENDPOINT_ADDRESS) .setResourceEndpoint(RESOURCE_ENDPOINT_ADDRESS) .setClientId("example-client") .setClientSecret("secret") .setGrantType(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS) .setUserName(userName) .setPassword(password) .setScope(Scope.ALL) .build() .retrieveAccessToken(); } }
package org.yaml.snakeyaml.javabeans; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import junit.framework.TestCase; import org.yaml.snakeyaml.JavaBeanDumper; import org.yaml.snakeyaml.JavaBeanLoader; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; public class HouseTest extends TestCase { /** * no root global tag */ public void testDump1() { House house = new House(); FrontDoor frontDoor = new FrontDoor("qaz1", 5); frontDoor.setKeytype("qwerty123"); house.setFrontDoor(frontDoor); List<Room> rooms = new LinkedList<Room>(); rooms.add(new Room("Hall")); rooms.add(new Room("Kitchen")); house.setRooms(rooms); Map<String, String> reminders = new TreeMap<String, String>(); reminders.put("today", "do nothig"); reminders.put("tomorrow", "go shoping"); house.setReminders(reminders); house.setNumber(1); house.setStreet("Wall Street"); JavaBeanDumper beanDumper = new JavaBeanDumper(); String yaml = beanDumper.dump(house); String etalon = Util.getLocalResource("javabeans/house-dump1.yaml"); assertEquals(etalon, yaml); // false is default beanDumper = new JavaBeanDumper(false); String output2 = beanDumper.dump(house); assertEquals(etalon, output2); // load JavaBeanLoader<House> beanLoader = new JavaBeanLoader<House>(House.class); House loadedHouse = beanLoader.load(yaml); assertNotNull(loadedHouse); assertEquals("Wall Street", loadedHouse.getStreet()); // dump again String yaml3 = beanDumper.dump(loadedHouse); assertEquals(yaml, yaml3); } /** * with global root class tag (global tag should be avoided) */ public void testDump3() { House house = new House(); FrontDoor frontDoor = new FrontDoor("qaz1", 5); frontDoor.setKeytype("qwerty123"); house.setFrontDoor(frontDoor); List<Room> rooms = new LinkedList<Room>(); rooms.add(new Room("Hall")); rooms.add(new Room("Kitchen")); house.setRooms(rooms); Map<String, String> reminders = new TreeMap<String, String>(); reminders.put("today", "do nothig"); reminders.put("tomorrow", "go shoping"); house.setReminders(reminders); house.setNumber(1); house.setStreet("Wall Street"); JavaBeanDumper beanDumper = new JavaBeanDumper(); beanDumper.setMapTagForBean(Room.class); String yaml = beanDumper.dump(house); String etalon = Util.getLocalResource("javabeans/house-dump3.yaml"); assertEquals(etalon, yaml); // load TypeDescription description = new TypeDescription(House.class); description.putListPropertyType("rooms", Room.class); JavaBeanLoader<House> beanLoader = new JavaBeanLoader<House>(description); House loadedHouse = beanLoader.load(yaml); assertNotNull(loadedHouse); assertEquals("Wall Street", loadedHouse.getStreet()); assertEquals(1, loadedHouse.getNumber()); FrontDoor fdoor = loadedHouse.getFrontDoor(); assertEquals(frontDoor.getId(), fdoor.getId()); assertEquals(frontDoor.getHeight(), fdoor.getHeight()); assertEquals(frontDoor.getKeytype(), fdoor.getKeytype()); assertEquals(frontDoor, fdoor); assertEquals(reminders, loadedHouse.getReminders()); List<Room> loadedRooms = loadedHouse.getRooms(); assertEquals(rooms, loadedRooms); // dump again String yaml3 = beanDumper.dump(loadedHouse); assertEquals(yaml, yaml3); } /** * with global root class tag (global tag should be avoided) */ public void testDump2() { House house = new House(); FrontDoor frontDoor = new FrontDoor("qaz1", 5); frontDoor.setKeytype("qwerty123"); house.setFrontDoor(frontDoor); List<Room> rooms = new LinkedList<Room>(); rooms.add(new Room("Hall")); rooms.add(new Room("Kitchen")); house.setRooms(rooms); Map<String, String> reminders = new TreeMap<String, String>(); reminders.put("today", "do nothig"); reminders.put("tomorrow", "go shoping"); house.setReminders(reminders); house.setNumber(1); house.setStreet("Wall Street"); JavaBeanDumper beanDumper = new JavaBeanDumper(true); String yaml = beanDumper.dump(house); String etalon = Util.getLocalResource("javabeans/house-dump2.yaml"); assertEquals(etalon, yaml); // load JavaBeanLoader<House> beanLoader = new JavaBeanLoader<House>(House.class); House loadedHouse = beanLoader.load(yaml); assertNotNull(loadedHouse); assertEquals("Wall Street", loadedHouse.getStreet()); // dump again String yaml3 = beanDumper.dump(loadedHouse); assertEquals(yaml, yaml3); } }
package us.kbase.narrativemethodstore.db.github; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import us.kbase.narrativemethodstore.db.MethodSpecDB; import us.kbase.narrativemethodstore.db.NarrativeMethodData; public class GitHubDB implements MethodSpecDB { public static final String GITHUB_API_URL_DEFAULT = "https://api.github.com"; public static final String GITHUB_RAW_CONTENT_URL_DEFAULT = "https://raw.githubusercontent.com"; private final ObjectMapper mapper = new ObjectMapper(); private final Yaml yaml = new Yaml(); // github config variables private String GITHUB_API_URL; private String GITHUB_RAW_CONTENT_URL; protected String owner; protected String repo; protected String branch; protected String latest_sha; protected File repoRootDir = new File("../narrative_method_specs"); public GitHubDB(String owner, String repo, String branch) throws JsonProcessingException, IOException { this.initalize(owner, repo, branch, GITHUB_API_URL_DEFAULT, GITHUB_RAW_CONTENT_URL_DEFAULT); } public GitHubDB(String owner, String repo, String branch, String githubApiUrl, String githubResourceUrl) throws JsonProcessingException, IOException { this.initalize(owner, repo, branch, githubApiUrl, githubResourceUrl); } protected void initalize(String owner, String repo, String branch, String githubApiUrl, String githubResourceUrl) { this.GITHUB_API_URL = githubApiUrl; this.GITHUB_RAW_CONTENT_URL = githubResourceUrl; this.owner = owner; this.repo = repo; this.branch = branch; this.latest_sha = ""; /*try { URL repoInfoUrl = new URL(GITHUB_API_URL + "/repos/" + owner + "/" + repo + "/git/refs/heads/" + branch); JsonNode repoInfo = getAsJson(repoInfoUrl); latest_sha = repoInfo.get("object").get("sha").textValue(); System.out.println(latest_sha); } catch (IOException e) { }*/ } /** returns true if the latest commit we have does not match the head commit, false otherwise; if we cannot * connect to github, then we just report that new data is not available */ /*protected boolean newDataAvailable() { URL repoInfoUrl; try { repoInfoUrl = new URL(GITHUB_API_URL + "/repos/" + owner + "/" + repo + "/git/refs/heads/" + branch); JsonNode repoInfo = getAsJson(repoInfoUrl); if(!latest_sha.equals(repoInfo.get("object").get("sha").textValue())) { return true; } else { return false; } } catch (IOException e) { return false; } }*/ protected JsonNode methodIndex; /*protected void refreshMethodIndex() throws JsonProcessingException, IOException { URL methodIndexUrl = new URL(GITHUB_RAW_CONTENT_URL + "/" + owner + "/" + repo + "/"+branch+"/methods/index.json"); JsonNode methodIndex = getAsJson(methodIndexUrl); System.out.println(methodIndex); }*/ protected File getMethodsDir() { return new File(repoRootDir, "methods"); } public List<String> listMethodIds() throws IOException { //JsonNode methodListJson = getAsJson(new URL(GITHUB_API_URL + "/repos/" + owner + "/" + repo + "/contents/methods?ref=" + branch)); List <String> methodList = new ArrayList<String>(); //methodListJson.size()); /*for(int m=0; m<methodListJson.size(); m++) { if(methodListJson.get(m).get("type").asText().equals("dir")) { methodList.add(methodListJson.get(m).get("name").asText()); } }*/ for (File sub : getMethodsDir().listFiles()) { if (sub.isDirectory()) methodList.add(sub.getName()); } System.out.println("method list:"); for(String id : methodList) { System.out.println(" } return methodList; } public NarrativeMethodData loadMethodData(String methodId) throws JsonProcessingException, IOException { // Fetch the resources needed JsonNode spec = getResourceAsJson("methods/"+methodId+"/spec.json"); Map<String,Object> display = getResourceAsYamlMap("methods/"+methodId+"/display.yaml"); // Initialize the actual data NarrativeMethodData data = new NarrativeMethodData(methodId, spec, display); return data; } protected JsonNode getResourceAsJson(String path) throws JsonProcessingException, IOException { File f = new File(repoRootDir, path); return getAsJson(f); } protected String getResource(String path) throws IOException { File f = new File(repoRootDir, path); return get(f); } protected Map<String,Object> getResourceAsYamlMap(String path) throws IOException { File f = new File(repoRootDir, path); String document = get(f); @SuppressWarnings("unchecked") Map<String,Object> data = (Map<String, Object>) yaml.load(document); //System.out.println("fetched yaml ("+url+"):\n"+yaml.dump(data)); return data; } protected JsonNode getAsJson(File f) throws JsonProcessingException, IOException { return mapper.readTree(get(f)); } protected String get(URL url) throws IOException { return get(url.openStream()); } protected String get(File f) throws IOException { return get(new FileInputStream(f)); } protected String get(InputStream is) throws IOException { StringBuilder response = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String line; while ((line = in.readLine()) != null) response.append(line+"\n"); in.close(); return response.toString(); } public static void main(String[] args) throws JsonProcessingException, IOException { System.out.println("testing github db"); GitHubDB githubDB = new GitHubDB("msneddon","narrative_method_specs","master"); String mId = githubDB.listMethodIds().get(0); NarrativeMethodData data = githubDB.loadMethodData(mId); System.out.println(mId + ", " + data.getMethodFullInfo().getDescription()); return; } }
package com.stripe.android.model; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.Size; import android.support.annotation.StringDef; import com.stripe.android.util.StripeJsonUtils; import org.json.JSONException; import org.json.JSONObject; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.HashMap; import java.util.Map; import static com.stripe.android.util.StripeJsonUtils.optLong; import static com.stripe.android.util.StripeJsonUtils.optString; import static com.stripe.android.util.StripeJsonUtils.mapToJsonObject; import static com.stripe.android.util.StripeJsonUtils.putStringIfNotNull; import static com.stripe.android.util.StripeNetworkUtils.removeNullParams; public class Source extends StripeJsonModel { @Retention(RetentionPolicy.SOURCE) @StringDef({ BITCOIN, CARD, THREE_D_SECURE, GIROPAY, SEPA_DEBIT, IDEAL, SOFORT, BANCONTACT }) public @interface SourceType { } public static final String BITCOIN = "bitcoin"; public static final String CARD = "card"; public static final String THREE_D_SECURE = "three_d_secure"; public static final String GIROPAY = "giropay"; public static final String SEPA_DEBIT = "sepa_debit"; public static final String IDEAL = "ideal"; public static final String SOFORT = "sofort"; public static final String BANCONTACT = "bancontact"; @Retention(RetentionPolicy.SOURCE) @StringDef({ PENDING, CHARGEABLE, CONSUMED, CANCELED }) public @interface SourceStatus { } public static final String PENDING = "pending"; public static final String CHARGEABLE = "chargeable"; public static final String CONSUMED = "consumed"; public static final String CANCELED = "canceled"; @Retention(RetentionPolicy.SOURCE) @StringDef({ REUSABLE, SINGLE_USE }) public @interface Usage { } public static final String REUSABLE = "reusable"; public static final String SINGLE_USE = "single_use"; @Retention(RetentionPolicy.SOURCE) @StringDef({ REDIRECT, RECEIVER, CODE_VERIFICATION, NONE }) public @interface SourceFlow { } public static final String REDIRECT = "redirect"; public static final String RECEIVER = "receiver"; public static final String CODE_VERIFICATION = "code_verification"; public static final String NONE = "none"; static final String EURO = "eur"; static final String USD = "usd"; static final String VALUE_SOURCE = "source"; static final String FIELD_ID = "id"; static final String FIELD_OBJECT = "object"; static final String FIELD_AMOUNT = "amount"; static final String FIELD_CLIENT_SECRET = "client_secret"; static final String FIELD_CODE_VERIFICATION = "code_verification"; static final String FIELD_CREATED = "created"; static final String FIELD_CURRENCY = "currency"; static final String FIELD_FLOW = "flow"; static final String FIELD_LIVEMODE = "livemode"; static final String FIELD_METADATA = "metadata"; static final String FIELD_OWNER = "owner"; static final String FIELD_RECEIVER = "receiver"; static final String FIELD_REDIRECT = "redirect"; static final String FIELD_STATUS = "status"; static final String FIELD_TYPE = "type"; static final String FIELD_USAGE = "usage"; private String mId; private Long mAmount; private String mClientSecret; private SourceCodeVerification mCodeVerification; private Long mCreated; private String mCurrency; private @SourceFlow String mFlow; private Boolean mLiveMode; private Map<String, Object> mMetaData; private SourceOwner mOwner; private SourceReceiver mReceiver; private SourceRedirect mRedirect; private @SourceStatus String mStatus; private Map<String, Object> mSourceTypeData; private @SourceType String mType; private @Usage String mUsage; Source( String id, Long amount, String clientSecret, SourceCodeVerification codeVerification, Long created, String currency, @SourceFlow String flow, Boolean liveMode, Map<String, Object> metaData, SourceOwner owner, SourceReceiver receiver, SourceRedirect redirect, @SourceStatus String status, Map<String, Object> sourceTypeData, @SourceType String type, @Usage String usage ) { mId = id; mAmount = amount; mClientSecret = clientSecret; mCodeVerification = codeVerification; mCreated = created; mCurrency = currency; mFlow = flow; mLiveMode = liveMode; mMetaData = metaData; mOwner = owner; mReceiver = receiver; mRedirect = redirect; mStatus = status; mSourceTypeData = sourceTypeData; mType = type; mUsage = usage; } public String getId() { return mId; } public Long getAmount() { return mAmount; } public String getClientSecret() { return mClientSecret; } public SourceCodeVerification getCodeVerification() { return mCodeVerification; } public Long getCreated() { return mCreated; } public String getCurrency() { return mCurrency; } @SourceFlow public String getFlow() { return mFlow; } public Boolean isLiveMode() { return mLiveMode; } public Map<String, Object> getMetaData() { return mMetaData; } public SourceOwner getOwner() { return mOwner; } public SourceReceiver getReceiver() { return mReceiver; } public SourceRedirect getRedirect() { return mRedirect; } @SourceStatus public String getStatus() { return mStatus; } public Map<String, Object> getSourceTypeData() { return mSourceTypeData; } @SourceType public String getType() { return mType; } @Usage public String getUsage() { return mUsage; } public void setId(String id) { mId = id; } public void setAmount(long amount) { mAmount = amount; } public void setClientSecret(String clientSecret) { mClientSecret = clientSecret; } public void setCodeVerification(SourceCodeVerification codeVerification) { mCodeVerification = codeVerification; } public void setCreated(long created) { mCreated = created; } public void setCurrency(String currency) { mCurrency = currency; } public void setFlow(@SourceFlow String flow) { mFlow = flow; } public void setLiveMode(boolean liveMode) { mLiveMode = liveMode; } public void setMetaData(Map<String, Object> metaData) { mMetaData = metaData; } public void setOwner(SourceOwner owner) { mOwner = owner; } public void setReceiver(SourceReceiver receiver) { mReceiver = receiver; } public void setRedirect(SourceRedirect redirect) { mRedirect = redirect; } public void setStatus(@SourceStatus String status) { mStatus = status; } public void setSourceTypeData(Map<String, Object> sourceTypeData) { mSourceTypeData = sourceTypeData; } public void setType(@SourceType String type) { mType = type; } public void setUsage(@Usage String usage) { mUsage = usage; } @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_ID, mId); hashMap.put(FIELD_AMOUNT, mAmount); hashMap.put(FIELD_CLIENT_SECRET, mClientSecret); putStripeJsonModelMapIfNotNull(hashMap, FIELD_CODE_VERIFICATION, mCodeVerification); hashMap.put(FIELD_CREATED, mCreated); hashMap.put(FIELD_CURRENCY, mCurrency); hashMap.put(FIELD_FLOW, mFlow); hashMap.put(FIELD_LIVEMODE, mLiveMode); hashMap.put(FIELD_METADATA, mMetaData); putStripeJsonModelMapIfNotNull(hashMap, FIELD_OWNER, mOwner); putStripeJsonModelMapIfNotNull(hashMap, FIELD_RECEIVER, mReceiver); putStripeJsonModelMapIfNotNull(hashMap, FIELD_REDIRECT, mRedirect); if (mType != null) { hashMap.put(mType, mSourceTypeData); } hashMap.put(FIELD_STATUS, mStatus); hashMap.put(FIELD_TYPE, mType); hashMap.put(FIELD_USAGE, mUsage); removeNullParams(hashMap); return hashMap; } @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try { putStringIfNotNull(jsonObject, FIELD_ID, mId); jsonObject.put(FIELD_OBJECT, VALUE_SOURCE); jsonObject.put(FIELD_AMOUNT, mAmount); putStringIfNotNull(jsonObject, FIELD_CLIENT_SECRET, mClientSecret); putStripeJsonModelIfNotNull(jsonObject, FIELD_CODE_VERIFICATION, mCodeVerification); jsonObject.put(FIELD_CREATED, mCreated); putStringIfNotNull(jsonObject, FIELD_CURRENCY, mCurrency); putStringIfNotNull(jsonObject, FIELD_FLOW, mFlow); jsonObject.put(FIELD_LIVEMODE, mLiveMode); JSONObject metaDataObject = StripeJsonUtils.mapToJsonObject(mMetaData); if (metaDataObject != null) { jsonObject.put(FIELD_METADATA, metaDataObject); } JSONObject sourceTypeJsonObject = mapToJsonObject(mSourceTypeData); if (mType != null && sourceTypeJsonObject != null) { jsonObject.put(mType, sourceTypeJsonObject); } putStripeJsonModelIfNotNull(jsonObject, FIELD_OWNER, mOwner); putStripeJsonModelIfNotNull(jsonObject, FIELD_RECEIVER, mReceiver); putStripeJsonModelIfNotNull(jsonObject, FIELD_REDIRECT, mRedirect); putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); putStringIfNotNull(jsonObject, FIELD_TYPE, mType); putStringIfNotNull(jsonObject, FIELD_USAGE, mUsage); } catch (JSONException ignored) { } return jsonObject; } @Nullable public static Source fromString(@Nullable String jsonString) { try { return fromJson(new JSONObject(jsonString)); } catch (JSONException ignored) { return null; } } @Nullable public static Source fromJson(@Nullable JSONObject jsonObject) { if (jsonObject == null || !VALUE_SOURCE.equals(jsonObject.optString(FIELD_OBJECT))) { return null; } String id = optString(jsonObject, FIELD_ID); Long amount = optLong(jsonObject, FIELD_AMOUNT); String clientSecret = optString(jsonObject, FIELD_CLIENT_SECRET); SourceCodeVerification codeVerification = optStripeJsonModel( jsonObject, FIELD_CODE_VERIFICATION, SourceCodeVerification.class); Long created = optLong(jsonObject, FIELD_CREATED); String currency = optString(jsonObject, FIELD_CURRENCY); @SourceFlow String flow = asSourceFlow(optString(jsonObject, FIELD_FLOW)); Boolean liveMode = jsonObject.optBoolean(FIELD_LIVEMODE); Map<String, Object> metadata = StripeJsonUtils.jsonObjectToMap(jsonObject.optJSONObject(FIELD_METADATA)); SourceOwner owner = optStripeJsonModel(jsonObject, FIELD_OWNER, SourceOwner.class); SourceReceiver receiver = optStripeJsonModel( jsonObject, FIELD_RECEIVER, SourceReceiver.class); SourceRedirect redirect = optStripeJsonModel( jsonObject, FIELD_REDIRECT, SourceRedirect.class); @SourceStatus String status = asSourceStatus(optString(jsonObject, FIELD_STATUS)); @SourceType String type = asSourceType(optString(jsonObject, FIELD_TYPE)); Map<String, Object> sourceTypeData = StripeJsonUtils.jsonObjectToMap(jsonObject.optJSONObject(type)); @Usage String usage = asUsage(optString(jsonObject, FIELD_USAGE)); return new Source( id, amount, clientSecret, codeVerification, created, currency, flow, liveMode, metadata, owner, receiver, redirect, status, sourceTypeData, type, usage); } @Nullable static <T extends StripeJsonModel> T optStripeJsonModel( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String key, Class<T> type) { if (!jsonObject.has(key)) { return null; } switch (key) { case FIELD_CODE_VERIFICATION: return type.cast( SourceCodeVerification.fromJson( jsonObject.optJSONObject(FIELD_CODE_VERIFICATION))); case FIELD_OWNER: return type.cast( SourceOwner.fromJson(jsonObject.optJSONObject(FIELD_OWNER))); case FIELD_RECEIVER: return type.cast( SourceReceiver.fromJson(jsonObject.optJSONObject(FIELD_RECEIVER))); case FIELD_REDIRECT: return type.cast( SourceRedirect.fromJson(jsonObject.optJSONObject(FIELD_REDIRECT))); default: return null; } } @Nullable @SourceStatus static String asSourceStatus(@Nullable String sourceStatus) { if (PENDING.equals(sourceStatus)) { return PENDING; } else if (CHARGEABLE.equals(sourceStatus)) { return CHARGEABLE; } else if (CONSUMED.equals(sourceStatus)) { return CONSUMED; } else if (CANCELED.equals(sourceStatus)) { return CANCELED; } return null; } @Nullable @SourceType static String asSourceType(@Nullable String sourceType) { if (BITCOIN.equals(sourceType)) { return BITCOIN; } else if (CARD.equals(sourceType)) { return CARD; } else if (THREE_D_SECURE.equals(sourceType)) { return THREE_D_SECURE; } else if (GIROPAY.equals(sourceType)) { return GIROPAY; } else if (SEPA_DEBIT.equals(sourceType)) { return SEPA_DEBIT; } else if (IDEAL.equals(sourceType)) { return IDEAL; } else if (SOFORT.equals(sourceType)) { return SOFORT; } else if (BANCONTACT.equals(sourceType)) { return BANCONTACT; } return null; } @Nullable @Usage static String asUsage(@Nullable String usage) { if (REUSABLE.equals(usage)) { return REUSABLE; } else if (SINGLE_USE.equals(usage)) { return SINGLE_USE; } return null; } @Nullable @SourceFlow static String asSourceFlow(@Nullable String sourceFlow) { if (REDIRECT.equals(sourceFlow)) { return REDIRECT; } else if (RECEIVER.equals(sourceFlow)) { return RECEIVER; } else if (CODE_VERIFICATION.equals(sourceFlow)) { return CODE_VERIFICATION; } else if (NONE.equals(sourceFlow)) { return NONE; } return null; } }
package org.vast.util; public class TimeExtent { public final static double NOW_ACCURACY = 1000; public final static double UNKNOWN = Double.MAX_VALUE; public final static double NOW = Double.MIN_VALUE; protected double baseTime = Double.NaN; protected double timeBias = 0; protected double timeStep = 0; protected double leadTimeDelta = 0; protected double lagTimeDelta = 0; protected boolean baseAtNow = false; // if true baseTime is associated to machine clock protected boolean endNow = false; // if true stopTime is associated to machine clock protected boolean beginNow = false; // if true startTime is associated to machine clock protected int timeZone = 0; public static TimeExtent getNowInstant() { TimeExtent time = new TimeExtent(); time.setBaseAtNow(true); return time; } public TimeExtent() { } public TimeExtent(double baseJulianTime) { this.baseTime = baseJulianTime; } public TimeExtent(double startTime, double stopTime) { setStartTime(startTime); setStopTime(stopTime); } public TimeExtent copy() { TimeExtent timeExtent = new TimeExtent(); timeExtent.baseTime = this.getBaseTime(); timeExtent.timeBias = this.timeBias; timeExtent.timeStep = this.timeStep; timeExtent.leadTimeDelta = this.leadTimeDelta; timeExtent.lagTimeDelta = this.lagTimeDelta; timeExtent.baseAtNow = this.baseAtNow; timeExtent.endNow = this.endNow; timeExtent.beginNow = this.beginNow; return timeExtent; } public TimeExtent(double baseJulianTime, double timeBiasSeconds, double timeStepSeconds, double leadTimeDeltaSeconds, double lagTimeDeltaSeconds) { this.baseTime = baseJulianTime; this.timeBias = timeBiasSeconds; this.timeStep = timeStepSeconds; this.leadTimeDelta = Math.abs(leadTimeDeltaSeconds); this.lagTimeDelta = Math.abs(lagTimeDeltaSeconds); } public void setBaseTime(double baseJulianTime) { this.baseTime = baseJulianTime; } public void setTimeBias(double seconds) { this.timeBias = seconds; } public void setTimeStep(double seconds) { this.timeStep = seconds; } public void setLeadTimeDelta(double seconds) { this.leadTimeDelta = Math.abs(seconds); } public void setLagTimeDelta(double seconds) { this.lagTimeDelta = Math.abs(seconds); } public void setDeltaTimes(double leadDeltaSeconds, double lagDeltaSeconds) { this.leadTimeDelta = Math.abs(leadDeltaSeconds); this.lagTimeDelta = Math.abs(lagDeltaSeconds); } /** * To get baseTime without bias applied. * If baseAtNow is set, this retrieves the system's current time * @return base time as julian time in seconds (1970 based) */ public double getBaseTime() { if (baseAtNow) return getNow(); else return baseTime; } /** * To get baseTime or absTime with bias applied * @return base time + bias as julian time in seconds (1970 based) */ public double getAdjustedTime() { return (getBaseTime() + timeBias); } public double getTimeBias() { return timeBias; } public double getTimeStep() { return timeStep; } public double getLeadTimeDelta() { return leadTimeDelta; } public double getLagTimeDelta() { return lagTimeDelta; } public double getTimeRange() { return (getAdjustedLeadTime() - getAdjustedLagTime()); } public double getAdjustedLeadTime() { if (endNow) return getNow() + timeBias; else return (getBaseTime() + timeBias + leadTimeDelta); } public double getAdjustedLagTime() { if (beginNow) return getNow() + timeBias; else return (getBaseTime() + timeBias - lagTimeDelta); } public boolean isBaseAtNow() { return baseAtNow; } public void setBaseAtNow(boolean baseAtNow) { this.baseAtNow = baseAtNow; } public boolean isBeginNow() { return beginNow; } public void setBeginNow(boolean beginNow) { this.beginNow = beginNow; } public boolean isEndNow() { return endNow; } public void setEndNow(boolean endNow) { this.endNow = endNow; } /** * @return number of full time steps */ public int getNumberOfSteps() { if (timeStep == 0.0) return 1; else return (int) ((getAdjustedLeadTime() - getAdjustedLagTime()) / timeStep); } /** * Calculates times based on current time settings, always assuring * that both endpoints are included even if an uneven time step occurs * at the end * @return time grid spliting the time period evenly */ public double[] getTimes() { double time = getAdjustedLeadTime(); double lagTime = getAdjustedLagTime(); // if step is 0 returns two extreme points if (timeStep == 0.0) { return new double[] {time, lagTime}; } double timeRange = Math.abs(time - lagTime); double remainder = timeRange % timeStep; int steps = (int) (timeRange / timeStep) + 1; double[] times; if (remainder != 0.0) { times = new double[steps + 1]; times[steps] = lagTime; } else times = new double[steps]; for (int i = 0; i < steps; i++) times[i] = time - i * timeStep; return times; } public String toString() { String tString = new String("TimeExtent:"); tString += "\n baseTime = " + (baseAtNow ? "now" : baseTime); tString += "\n timeBias = " + timeBias; tString += "\n timeStep = " + timeStep; tString += "\n leadTimeDelta = " + leadTimeDelta; tString += "\n lagTimeDelta = " + lagTimeDelta; return tString; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof TimeExtent)) return false; return equals((TimeExtent)obj); } /** * Checks if time extents are equal (no null check) * (i.e. stop=stop AND start=start) * @param timeExtent * @return true if time extents are equal */ public boolean equals(TimeExtent timeExtent) { if (!baseAtNow) { if (( this.getAdjustedLagTime() != timeExtent.getAdjustedLagTime() ) && !( this.isBeginNow() && timeExtent.isBeginNow() )) return false; if (( this.getAdjustedLeadTime() != timeExtent.getAdjustedLeadTime() ) && !( this.isEndNow() && timeExtent.isEndNow() )) return false; } else { if (!timeExtent.isBaseAtNow()) return false; if (this.getLagTimeDelta() != timeExtent.getLagTimeDelta()) return false; if (this.getLeadTimeDelta() != timeExtent.getLeadTimeDelta()) return false; } return true; } /** * Checks if this TimeExtent contains the given time * @param time * @return true if it contains the given time point */ public boolean contains(double time) { double thisLag = this.getAdjustedLagTime(); double thisLead = this.getAdjustedLeadTime(); if (time < thisLag) return false; if (time > thisLead) return false; return true; } /** * Checks if this TimeExtent contains the given TimeExtent * @param timeExtent * @return true if it contains the given TimeExtent */ public boolean contains(TimeExtent timeExtent) { double thisLag = this.getAdjustedLagTime(); double thisLead = this.getAdjustedLeadTime(); double otherLag = timeExtent.getAdjustedLagTime(); double otherLead = timeExtent.getAdjustedLeadTime(); if (otherLag < thisLag) return false; if (otherLag > thisLead) return false; if (otherLead < thisLag) return false; if (otherLead > thisLead) return false; return true; } /** * Checks if this timeExtent intersects the given timeExtent * @param timeExtent * @return true if both TimeExtents intersects */ public boolean intersects(TimeExtent timeExtent) { double thisLag = this.getAdjustedLagTime(); double thisLead = this.getAdjustedLeadTime(); double otherLag = timeExtent.getAdjustedLagTime(); double otherLead = timeExtent.getAdjustedLeadTime(); if (otherLag > thisLag && otherLag < thisLead) return true; if (otherLead > thisLag && otherLead < thisLead) return true; if (otherLag <= thisLag && otherLead >= thisLead) return true; return false; } /** * Check if time is null (i.e. baseTime is not set) * @return true if no base time has been set */ public boolean isNull() { return (Double.isNaN(baseTime) && !baseAtNow); } /** * Check if this is a single point in time * @return true if this is a time instant */ public boolean isTimeInstant() { if (leadTimeDelta != 0) return false; if (lagTimeDelta != 0) return false; if (beginNow != endNow) return false; return true; } /** * Resets all variables so that extent is null (i.e. unset) */ public void nullify() { baseTime = Double.NaN; timeBias = 0; timeStep = 0; leadTimeDelta = 0; lagTimeDelta = 0; baseAtNow = false; endNow = false; beginNow = false; } /** * Resizes this extent so that it contains the given time value * @param t time value (MUST be in same reference frame as the extent) */ public void resizeToContain(double t) { if (isNull()) { baseTime = t; timeBias = 0; return; } double adjBaseTime = getAdjustedTime(); if (t > getAdjustedLeadTime()) leadTimeDelta = t - adjBaseTime; else if (t < getAdjustedLagTime()) lagTimeDelta = adjBaseTime - t; } /** * Return latest value for now. This would return a new 'now' value * only if previous call was made more than NOW_ACCURACY second ago. */ private double now = 0; private double getNow() { double exactNow = System.currentTimeMillis()/1000; if (exactNow - now > NOW_ACCURACY) now = exactNow; return now; } /** * Helper method to get start time * @return start time as julian time in seconds (1970 based) */ public double getStartTime() { return getAdjustedLagTime(); } /** * Helper method to set start time * @param startTime start time as julian time in seconds (1970 based) */ public void setStartTime(double startTime) { beginNow = false; if (Double.isNaN(baseTime) || baseAtNow) { baseTime = startTime; lagTimeDelta = 0.0; baseAtNow = false; } else if (startTime > baseTime) { double stopTime = baseTime + leadTimeDelta; baseTime = startTime; leadTimeDelta = Math.max(0.0, stopTime - baseTime); lagTimeDelta = 0.0; } else { lagTimeDelta = baseTime - startTime; } } /** * Helper method to get stop time * @return stop time as julian time in seconds (1970 based) */ public double getStopTime() { return getAdjustedLeadTime(); } /** * Helper method to set stop time * @param stopTime stop time as julian time in seconds (1970 based) */ public void setStopTime(double stopTime) { endNow = false; if (Double.isNaN(baseTime) || baseAtNow) { baseTime = stopTime; leadTimeDelta = 0.0; baseAtNow = false; } else if (stopTime < baseTime) { double startTime = baseTime - lagTimeDelta; baseTime = stopTime; lagTimeDelta = Math.max(0.0, baseTime - startTime); leadTimeDelta = 0.0; } else { leadTimeDelta = stopTime - baseTime; } } public String getIsoString(int zone) { DateTimeFormat timeFormat = new DateTimeFormat(); if (baseAtNow) { String start = beginNow ? "now" : "unknown"; String stop = endNow ? "now" : "unknown"; String duration = timeFormat.formatIsoPeriod(getTimeRange()); return start + "/" + stop + "/" + duration; } else { String start = beginNow ? "now" : timeFormat.formatIso(getStartTime(), zone); String stop = endNow ? "now" : timeFormat.formatIso(getStopTime(), zone); return start + "/" + stop; } } public int getTimeZone() { return timeZone; } public void setTimeZone(int timeZone) { this.timeZone = timeZone; } }
package com.adeptj.modules.mvc; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.Bundle; import org.osgi.framework.BundleEvent; import org.osgi.util.tracker.BundleTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.trimou.engine.MustacheEngine; import org.trimou.engine.locator.PathTemplateLocator; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.lang.invoke.MethodHandles; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PropertyResourceBundle; import java.util.Set; import static com.adeptj.modules.mvc.TemplateEngineConstants.I18N_HEADER; import static com.adeptj.modules.mvc.TemplateEngineConstants.TEMPLATE_HEADER; public class BundleTemplateLocator extends PathTemplateLocator<String> implements BundleTrackerCustomizer<Object> { private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final List<Bundle> templateBundles; private final Map<Long, List<String>> bundleTemplatesMapping; private final DelegatingResourceBundleHelper resourceBundleHelper; private MustacheEngine mustacheEngine; public BundleTemplateLocator(int priority, String rootPath, String suffix) { super(priority, rootPath, suffix); this.resourceBundleHelper = new DelegatingResourceBundleHelper(); this.templateBundles = new ArrayList<>(); this.bundleTemplatesMapping = new HashMap<>(); } public DelegatingResourceBundleHelper getResourceBundleHelper() { return resourceBundleHelper; } public void setMustacheEngine(MustacheEngine mustacheEngine) { this.mustacheEngine = mustacheEngine; } @Override protected String constructVirtualPath(String source) { throw new UnsupportedOperationException(); } @Override public Set<String> getAllIdentifiers() { return Collections.emptySet(); } @Override public Reader locate(String name) { for (Bundle bundle : this.templateBundles) { Enumeration<URL> entries = bundle.findEntries(bundle.getHeaders().get(TEMPLATE_HEADER), "*.html", true); if (entries != null) { while (entries.hasMoreElements()) { URL template = entries.nextElement(); if (StringUtils.endsWith(template.getPath(), name + "." + this.getSuffix())) { this.bundleTemplatesMapping.computeIfAbsent(bundle.getBundleId(), k -> new ArrayList<>()) .add(name); try { return IOUtils.buffer(new InputStreamReader(template.openStream(), this.getDefaultFileEncoding())); } catch (IOException ex) { LOGGER.error(ex.getMessage(), ex); } } } } } return null; } @Override public Object addingBundle(Bundle bundle, BundleEvent event) { String templatesLocation = bundle.getHeaders().get(TEMPLATE_HEADER); if (StringUtils.isNotEmpty(templatesLocation)) { LOGGER.info("Bundle: {} has provided templates under path: {}", bundle, templatesLocation); this.templateBundles.add(bundle); String resourceBundlesLocation = bundle.getHeaders().get(I18N_HEADER); if (StringUtils.isNotEmpty(resourceBundlesLocation)) { LOGGER.info("Bundle: {} has provided ResourceBundle(s) under path: {}", bundle, resourceBundlesLocation); Enumeration<URL> entries = bundle.findEntries(resourceBundlesLocation, "*.properties", true); if (entries != null) { while (entries.hasMoreElements()) { try (BufferedInputStream bis = IOUtils.buffer(entries.nextElement().openStream())) { PropertyResourceBundle resourceBundle = new PropertyResourceBundle(bis); ResourceBundleWrapper wrapper = new ResourceBundleWrapper(resourceBundle, bundle.getBundleId()); this.resourceBundleHelper.addResourceBundleWrapper(wrapper); } catch (IOException ex) { LOGGER.error(ex.getMessage(), ex); } } } } return bundle; } return null; } @Override public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) { // NOP } @Override public void removedBundle(Bundle bundle, BundleEvent event, Object object) { this.templateBundles.removeIf(b -> b.getBundleId() == bundle.getBundleId()); this.resourceBundleHelper.removeResourceBundleWrapper(bundle.getBundleId()); List<String> templates = this.bundleTemplatesMapping.get(bundle.getBundleId()); if (templates != null) { for (String template : templates) { this.mustacheEngine.invalidateTemplateCache(name -> StringUtils.equals(template, name)); } } } }
package name.abuchen.portfolio.money; import java.math.BigDecimal; import java.text.DecimalFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; public abstract class Values<E> { public static final class MoneyValues extends Values<Money> { private MoneyValues() { super("#,##0.00", 100D, 100); //$NON-NLS-1$ } @Override public String format(Money amount) { return String.format("%s %,.2f", amount.getCurrencyCode(), amount.getAmount() / divider()); //$NON-NLS-1$ } public String format(Money amount, String skipCurrencyCode) { if (skipCurrencyCode.equals(amount.getCurrencyCode())) return String.format("%,.2f", amount.getAmount() / divider()); //$NON-NLS-1$ else return format(amount); } @Override public String formatNonZero(Money amount) { return amount.isZero() ? null : format(amount); } @Override public String formatNonZero(Money amount, double threshold) { boolean isNotZero = Math.abs(amount.getAmount()) >= threshold; return isNotZero ? format(amount) : null; } public String formatNonZero(Money amount, String skipCurrencyCode) { return amount.isZero() ? null : format(amount, skipCurrencyCode); } } public static final class QuoteValues extends Values<Long> { private static final String QUOTE_PATTERN = "#,##0.00##"; //$NON-NLS-1$ private static final ThreadLocal<DecimalFormat> QUOTE_FORMAT = new ThreadLocal<DecimalFormat>() { @Override protected DecimalFormat initialValue() { return new DecimalFormat(QUOTE_PATTERN); } }; private QuoteValues() { super(QUOTE_PATTERN, 10000D, 10000); } @Override public String format(Long quote) { return QUOTE_FORMAT.get().format(quote / divider()); } public String format(String currencyCode, long quote, String skipCurrency) { if (currencyCode == null || skipCurrency.equals(currencyCode)) return format(quote); else return format(currencyCode, quote); } public String format(String currencyCode, long quote) { return currencyCode + " " + format(quote); //$NON-NLS-1$ } public String format(Quote quote) { return format(quote.getCurrencyCode(), quote.getAmount()); } public String format(Quote quote, String skipCurrency) { return format(quote.getCurrencyCode(), quote.getAmount(), skipCurrency); } /** * Factor by which to multiply a monetary amount to convert it into a * quote amount. Monetary amounts have 2 decimal digits while quotes * have 4 digits. */ public int factorToMoney() { return factor() / Values.Money.factor(); } /** * Divider by which to divide a quote amount to convert it into a * monetary amount. Monetary amounts have 2 decimal digits while quotes * have 4 digits. */ public double dividerToMoney() { return divider() / Values.Money.divider(); } } public static final Values<Long> Amount = new Values<Long>("#,##0.00", 100D, 100) //$NON-NLS-1$ { @Override public String format(Long amount) { return String.format("%,.2f", amount / divider()); //$NON-NLS-1$ } }; public static final MoneyValues Money = new MoneyValues(); public static final Values<Long> AmountFraction = new Values<Long>(" { private final DecimalFormat format = new DecimalFormat(pattern()); @Override public String format(Long share) { return format.format(share / divider()); } }; /** * Optionally format values without decimal places. Currently used only for * attributes attached to the security. */ public static final Values<Long> AmountPlain = new Values<Long>("#,##0.##", 100D, 100) //$NON-NLS-1$ { private final DecimalFormat format = new DecimalFormat(pattern()); @Override public String format(Long amount) { return format.format(amount / divider()); } }; public static final Values<Long> Share = new Values<Long>(" { private final DecimalFormat format = new DecimalFormat(pattern()); @Override public String format(Long share) { return format.format(share / divider()); } }; public static final QuoteValues Quote = new QuoteValues(); public static final Values<BigDecimal> ExchangeRate = new Values<BigDecimal>("#,##0.0000", 1D, 1)//$NON-NLS-1$ { @Override public String format(BigDecimal exchangeRate) { return String.format("%,.4f", exchangeRate); //$NON-NLS-1$ } }; public static final Values<Integer> Index = new Values<Integer>("#,##0.00", 100D, 100) //$NON-NLS-1$ { @Override public String format(Integer index) { return String.format("%,.2f", index / divider()); //$NON-NLS-1$ } }; public static final Values<LocalDate> Date = new Values<LocalDate>("yyyy-MM-dd", 1D, 1) //$NON-NLS-1$ { DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); @Override public String format(LocalDate date) { return formatter.format(date); } }; public static final Values<Double> Percent = new Values<Double>("0.00%", 1D, 1) //$NON-NLS-1$ { @Override public String format(Double percent) { return String.format("%,.2f", percent * 100); //$NON-NLS-1$ } }; public static final Values<Double> PercentShort = new Values<Double>("0.00%", 1D, 1) //$NON-NLS-1$ { @Override public String format(Double percent) { return String.format("%,.1f", percent * 100); //$NON-NLS-1$ } }; public static final Values<Double> PercentPlain = new Values<Double>("0.00", 1D, 1) //$NON-NLS-1$ { @Override public String format(Double percent) { return String.format("%,.2f", percent); //$NON-NLS-1$ } }; public static final Values<Integer> Weight = new Values<Integer>("#,##0.00", 100D, 100) //$NON-NLS-1$ { @Override public String format(Integer weight) { return String.format("%,.2f", weight / divider()); //$NON-NLS-1$ } }; public static final Values<Double> Percent2 = new Values<Double>("0.00%", 1D, 1) //$NON-NLS-1$ { @Override public String format(Double percent) { return String.format("%,.2f%%", percent * 100); //$NON-NLS-1$ } }; public static final Values<Double> Percent5 = new Values<Double>("0.00000%", 1D, 1) //$NON-NLS-1$ { @Override public String format(Double percent) { return String.format("%,.5f%%", percent * 100); //$NON-NLS-1$ } }; public static final Values<Integer> Id = new Values<Integer>("#,##0", 1D, 1) //$NON-NLS-1$ { @Override public String format(Integer amount) { return String.format("%,.0f", amount / divider()); //$NON-NLS-1$ } }; public static final Values<Integer> Year = new Values<Integer>("0", 1D, 1) //$NON-NLS-1$ { @Override public String format(Integer amount) { return String.valueOf(amount); } }; private final String pattern; private final double divider; private final int factor; private Values(String pattern, double divider, int factor) { this.pattern = pattern; this.divider = divider; this.factor = factor; } public String pattern() { return pattern; } public double divider() { return divider; } public int factor() { return factor; } public long factorize(double value) { return Math.round(value * factor); } public abstract String format(E amount); public String formatNonZero(E amount) { if (amount instanceof Double) { Double d = (Double) amount; if (d.isNaN()) return null; else if (d.doubleValue() == 0d) return null; else return format(amount); } else if (amount instanceof Number) { boolean isNotZero = ((Number) amount).longValue() != 0; return isNotZero ? format(amount) : null; } throw new UnsupportedOperationException(); } public String formatNonZero(E amount, double threshold) { if (amount instanceof Double) { boolean isNotZero = Math.abs(((Double) amount).doubleValue()) >= threshold; return isNotZero ? format(amount) : null; } throw new UnsupportedOperationException(); } }
package com.bigbluecup.android; import javax.microedition.khronos.egl.EGL10; import com.bigbluecup.android.AgsEngine; import android.content.pm.ActivityInfo; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.Bundle; import android.os.Message; import android.view.Display; public class EngineGlue extends Thread implements CustomGlSurfaceView.Renderer { public static final int MSG_SWITCH_TO_INGAME = 1; public static final int MSG_SHOW_MESSAGE = 2; public static final int MSG_SHOW_TOAST = 3; public static final int MSG_SET_ORIENTATION = 4; public static final int MSG_ENABLE_LONGCLICK = 5; public static final int MOUSE_CLICK_LEFT = 1; public static final int MOUSE_CLICK_RIGHT = 2; public static final int MOUSE_HOLD_LEFT = 10; public int keyboardKeycode = 0; public short mouseMoveX = 0; public short mouseMoveY = 0; public short mouseRelativeMoveX = 0; public short mouseRelativeMoveY = 0; public int mouseClick = 0; private int screenPhysicalWidth = 480; private int screenPhysicalHeight = 320; private int screenVirtualWidth = 320; private int screenVirtualHeight = 200; private int screenOffsetX = 0; private int screenOffsetY = 0; private boolean paused = false; private AudioTrack audioTrack; private byte[] audioBuffer; private int bufferSize = 0; private AgsEngine activity; private String gameFilename = ""; private String baseDirectory = ""; private String appDirectory = ""; private boolean loadLastSave = false; public native void nativeInitializeRenderer(int width, int height); public native void shutdownEngine(); private native boolean startEngine(Object object, String filename, String directory, String appDirectory, boolean loadLastSave); private native void pauseEngine(); private native void resumeEngine(); public EngineGlue(AgsEngine activity, String filename, String directory, String appDirectory, boolean loadLastSave) { this.activity = activity; gameFilename = filename; baseDirectory = directory; this.appDirectory = appDirectory; this.loadLastSave = loadLastSave; System.loadLibrary("agsengine"); } public void run() { startEngine(this, gameFilename, baseDirectory, appDirectory, loadLastSave); } public void pauseGame() { paused = true; if (audioTrack != null) audioTrack.pause(); pauseEngine(); } public void resumeGame() { if (audioTrack != null) audioTrack.play(); resumeEngine(); paused = false; } public void moveMouse(float relativeX, float relativeY, float x, float y) { mouseMoveX = (short)(x - screenOffsetX); mouseMoveY = (short)(y - screenOffsetY); if (mouseMoveX < 0) mouseMoveX = 0; if (mouseMoveY < 0) mouseMoveY = 0; mouseRelativeMoveX = (short)relativeX; mouseRelativeMoveY = (short)relativeY; } public void clickMouse(int button) { mouseClick = button; } public void keyboardEvent(int keycode, int character, boolean shiftPressed) { keyboardKeycode = keycode | (character << 16) | ((shiftPressed ? 1 : 0) << 30); } private void showMessage(String message) { Bundle data = new Bundle(); data.putString("message", message); sendMessageToActivity(MSG_SHOW_MESSAGE, data); } private void showToast(String message) { Bundle data = new Bundle(); data.putString("message", message); sendMessageToActivity(MSG_SHOW_TOAST, data); } private void sendMessageToActivity(int messageId, Bundle data) { Message m = activity.handler.obtainMessage(); m.what = messageId; if (data != null) m.setData(data); activity.handler.sendMessage(m); } private void createScreen(int width, int height, int color_depth) { screenVirtualWidth = width; screenVirtualHeight = height; sendMessageToActivity(MSG_SWITCH_TO_INGAME, null); int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; while (!activity.isInGame || (activity.surfaceView == null) || !activity.surfaceView.created) { try { Thread.sleep(100, 0); } catch (InterruptedException e) {} } activity.surfaceView.initialize(configSpec, this); // Make sure the mouse starts in the center of the screen mouseMoveX = (short)(activity.surfaceView.getWidth() / 2); mouseMoveY = (short)(activity.surfaceView.getHeight() / 2); } private void swapBuffers() { activity.surfaceView.swapBuffers(); } public void onSurfaceChanged(int width, int height) { Display display = activity.getWindowManager().getDefaultDisplay(); screenOffsetX = display.getWidth() - width; screenOffsetY = display.getHeight() - height; setPhysicalScreenResolution(width, height); nativeInitializeRenderer(width, height); } // Called from Allegro private int pollKeyboard() { int result = keyboardKeycode; keyboardKeycode = 0; return result; } private int pollMouseAbsolute() { return mouseMoveX | ((int)(mouseMoveY & 0xFFFF) << 16); } private int pollMouseRelative() { int result = (mouseRelativeMoveX & 0xFFFF) | ((int)(mouseRelativeMoveY & 0xFFFF) << 16); mouseRelativeMoveX = 0; mouseRelativeMoveY = 0; return result; } private int pollMouseButtons() { int result = mouseClick; mouseClick = 0; return result; } private void blockExecution() { while (paused) { try { Thread.sleep(100, 0); } catch (InterruptedException e) {} } } private void setRotation(int orientation) { Bundle data = new Bundle(); if (orientation == 1) data.putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); else if (orientation == 2) data.putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); sendMessageToActivity(MSG_SET_ORIENTATION, data); } private void enableLongclick() { sendMessageToActivity(MSG_ENABLE_LONGCLICK, null); } // Called from Allegro, the buffer is allocated in native code public void initializeSound(byte[] buffer, int bufferSize) { audioBuffer = buffer; this.bufferSize = bufferSize; int sampleRate = 44100; int minBufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT); if (minBufferSize < bufferSize * 4) minBufferSize = bufferSize * 4; audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM); float audioVolume = AudioTrack.getMaxVolume(); audioTrack.setStereoVolume(audioVolume, audioVolume); audioTrack.play(); } public void updateSound() { audioTrack.write(audioBuffer, 0, bufferSize); } public void setPhysicalScreenResolution(int width, int height) { screenPhysicalWidth = width; screenPhysicalHeight = height; } }
package am.app.mappingEngine; import java.util.EnumSet; import java.util.Enumeration; import java.util.Iterator; import am.app.feedback.FeedbackLoop; import am.app.feedback.InitialMatchers; import am.app.mapEngine.instance.BaseInstanceMatcher; import am.app.mapEngine.instance.InstanceBasedPropMatcher; import am.app.mappingEngine.AbstractMatcher.alignType; import am.app.mappingEngine.Combination.CombinationMatcher; import am.app.mappingEngine.LexicalMatcherJAWS.LexicalMatcherJAWS; import am.app.mappingEngine.LexicalMatcherJWNL.LexicalMatcherJWNL; import am.app.mappingEngine.LexicalSynonymMatcher.LexicalSynonymMatcher; //import am.app.mappingEngine.LexicalMatcherUMLS.LexicalMatcherUMLS; import am.app.mappingEngine.PRAMatcher.OldPRAMatcher; import am.app.mappingEngine.PRAMatcher.PRAMatcher; import am.app.mappingEngine.PRAMatcher.PRAMatcher2; import am.app.mappingEngine.PRAintegration.PRAintegrationMatcher; import am.app.mappingEngine.baseSimilarity.BaseSimilarityMatcher; import am.app.mappingEngine.basicStructureSelector.BasicStructuralSelectorMatcher; import am.app.mappingEngine.conceptMatcher.ConceptMatcher; import am.app.mappingEngine.dsi.DescendantsSimilarityInheritanceMatcher; import am.app.mappingEngine.dsi.OldDescendantsSimilarityInheritanceMatcher; import am.app.mappingEngine.manualMatcher.UserManualMatcher; import am.app.mappingEngine.multiWords.MultiWordsMatcher; import am.app.mappingEngine.oaei2009.OAEI2009matcher; import am.app.mappingEngine.parametricStringMatcher.ParametricStringMatcher; import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentMatcher; import am.app.mappingEngine.ssc.SiblingsSimilarityContributionMatcher; import am.app.mappingEngine.testMatchers.AllOneMatcher; import am.app.mappingEngine.testMatchers.AllZeroMatcher; import am.app.mappingEngine.testMatchers.CopyMatcher; import am.app.mappingEngine.testMatchers.EqualsMatcher; import am.app.mappingEngine.testMatchers.RandomMatcher; //import am.app.mappingEngine.LexicalMatcherUMLS.LexicalMatcherUMLS; import am.extension.AnatomySynonymExtractor; import am.extension.IndividualLister; /** * Enum for keeping the current list of matchers in the system, and their class references */ public enum MatchersRegistry { /** * This is where you add your own MATCHER. * * To add your matcher, add a definition to the enum, using this format * * EnumName ( "Short Name", MatcherClass.class ) * * For example, to add MySuperMatcher, you would add something like this (assuming the class name is MySuperMatcher): * * SuperMatcher ( "My Super Matcher", MySuperMatcher.class ), * * And so, if your matcher is has no code errors, it will be incorporated into the AgreementMaker. - Cosmin */ AdvancedSimilarity ( "Advances Similarity Matcher", am.app.mappingEngine.baseSimilarity.advancedSimilarity.AdvancedSimilarityMatcher.class), GroupFinder ( "GroupFinder", am.app.mappingEngine.groupFinder.GroupFinderMatcher.class), FCM ( "Federico Caimi Matcher", am.app.mappingEngine.FedericoCaimiMatcher.FedericoMatcher.class), LSM ( "Lexical Synonym Matcher", LexicalSynonymMatcher.class ), //ShashiMatcher ( "Shashi Matcher", am.extension.shashi.ShashiMatcher.class), IndiLister ( "Individual Lister", IndividualLister.class ), AnatomySyn ( "Anatomy Synonym Extractor", AnatomySynonymExtractor.class ), //OFFICIAL MATCHERS LexicalJAWS ( "Lexical Matcher: JAWS", LexicalMatcherJAWS.class ), BaseSimilarity ( "Base Similarity Matcher (BSM)", BaseSimilarityMatcher.class ), ParametricString ( "Parametric String Matcher (PSM)", ParametricStringMatcher.class ), BaseInstance ("Base Instance-based Matcher (BIM)", BaseInstanceMatcher.class), MultiWords ("Vector-based Multi-Words Matcher (VMM)", MultiWordsMatcher.class), WordNetLexical ("Lexical Matcher: WordNet", LexicalMatcherJWNL.class), DSI ( "Descendant's Similarity Inheritance (DSI)", DescendantsSimilarityInheritanceMatcher.class ), BSS ( "Basic Structure Selector Matcher (BSS)", BasicStructuralSelectorMatcher.class ), SSC ( "Sibling's Similarity Contribution (SSC)", SiblingsSimilarityContributionMatcher.class ), Combination ( "Linear Weighted Combination (LWC)", CombinationMatcher.class ), ConceptSimilarity ( "Concept Similarity", ConceptMatcher.class, false), OAEI2009 ( "OAEI2009 Matcher", OAEI2009matcher.class), //UMLSKSLexical ("Lexical Matcher: UMLSKS", LexicalMatcherUMLS.class, false), //it requires internet connection and the IP to be registered //Auxiliary matchers created for specific purposes InitialMatcher ("Initial Matcher: LWC (PSM+VMM+BSM)", InitialMatchers.class, true), PRAintegration ( "PRA Integration", PRAintegrationMatcher.class, false), //this works fine PRAMatcher ("PRA Matcher", PRAMatcher.class, false), PRAMatcher2 ("PRA Matcher2", PRAMatcher2.class, false), OldPRAMAtcher ("Old PRA Matcher", OldPRAMatcher.class, false), //WORK IN PROGRESS InstanceBasedProp ("Instance-based Property Matcher (IPM)", InstanceBasedPropMatcher.class), //MATCHERS USED BY THE SYSTEM, usually not shown UserManual ( "User Manual Matching", UserManualMatcher.class, false), UniqueMatchings ( "Unique Matchings", ReferenceAlignmentMatcher.class, false), // this is used by the "Remove Duplicate Alignments" UIMenu entry ImportAlignment ( "Import Alignments", ReferenceAlignmentMatcher.class, true), //TEST MATCHERS Equals ( "Local Name Equivalence Comparison", EqualsMatcher.class , false), AllOne ( "(Test) All One Similarities", AllOneMatcher.class, true ), AllZero ( "(Test) All Zero Similarities", AllZeroMatcher.class, true ), Copy ( "Copy Matcher", CopyMatcher.class,false ), Random ( "(Test) Random Similarities", RandomMatcher.class, true ), DSI2 ( "OLD Descendant's Similarity Inheritance (DSI)", OldDescendantsSimilarityInheritanceMatcher.class, false ), UserFeedBackLoop ("User Feedback Loop", FeedbackLoop.class, false ); /* Don't change anything below this line .. unless you intend to. */ private boolean showInControlPanel; private String name; private String className; MatchersRegistry( String n, Class<?> matcherClass ) { name = n; className = matcherClass.getName(); showInControlPanel = true;} MatchersRegistry( String n, Class<?> matcherClass, boolean shown) { name = n; className = matcherClass.getName(); showInControlPanel = shown; } public String getMatcherName() { return name; } public String getMatcherClass() { return className; } public boolean isShown() { return showInControlPanel; } public String toString() { return name; } /** * Returns the matcher with the given name. * @param matcherName The name of the matcher. * @return The MatchersRegistry representation of the matcher (used with MatcherFactory). */ /* // This method duplicates MatcherFactory.getMatchersRegistryEntry( matcherName ) public static MatchersRegistry getMatcherByName( String matcherName ) { EnumSet<MatchersRegistry> matchers = EnumSet.allOf(MatchersRegistry.class); Iterator<MatchersRegistry> entryIter = matchers.iterator(); while( entryIter.hasNext() ) { MatchersRegistry currentEntry = entryIter.next(); if( currentEntry.getMatcherName().equals(matcherName) ) return currentEntry; } return null; } */ }
package com.shealevy.android.model; import java.util.HashMap; import com.shealevy.android.model.injection.ClassDelegate; import android.content.ContentResolver; import android.database.Cursor; public class AndroidModel<T extends TableDelegate> { private HashMap<TableDelegateField<T,?>, Object> params = new HashMap<TableDelegateField<T,?>, Object>(); private T tableDelegate; public AndroidModel(Class<T> tableDelegateClass) { this(new ClassDelegate<T>(tableDelegateClass)); } public AndroidModel(ClassDelegate<T> tableDelegateClass) { constructTableDelegate(tableDelegateClass); } private void constructTableDelegate(ClassDelegate<T> tableDelegateClass) { try { setTableDelegate(tableDelegateClass.newInstance()); } catch (IllegalAccessException e) { // The class doesn't have a public constructor. Wrap as runtime exception, hope this never happens // Commented out until a feature can be written for this // throw new RuntimeException(e); } catch (InstantiationException e) { // The class is abstract or an interface. Wrap as runtime exception, hope this never happens // Commented out until a feature can be written for this //throw new RuntimeException(e); } } public AndroidModel(T tableDelegate) { setTableDelegate(tableDelegate); } public void setTableDelegate(T tableDelegate) { this.tableDelegate = tableDelegate; } public T getTableDelegate() { return tableDelegate; } @SuppressWarnings("unchecked") public <U> U get(TableDelegateField<T, U> field) { if(params.containsKey(field)) { return (U) params.get(field); } return field.defaultValue(); } public <U> void set(TableDelegateField<T, U> field, U value) { params.put(field, value); } @SuppressWarnings("unchecked") public void load(ContentResolver cr) { String where = "_id = 2"; TableDelegateField<T, ?>[] fields = params.keySet().iterator().next().getFields(); String[] projection = new String[fields.length]; int index = 0; for(TableDelegateField<T, ?> field:fields) { projection[index] = field.name(); index++; } Cursor cursor = tableDelegate.query(cr, projection, where, null, null); cursor.moveToFirst(); index = 0; for(TableDelegateField<T, ?> field:fields) { if(field.type().getName().equals("java.lang.String")) { set((TableDelegateField<T,String>)field, "SecondTest"); } } } }
package org.gluu.oxauth.client; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.gluu.oxauth.model.common.AuthenticationMethod; import org.gluu.oxauth.model.common.GrantType; import org.gluu.oxauth.model.crypto.AbstractCryptoProvider; import org.gluu.oxauth.model.crypto.signature.ECDSAPrivateKey; import org.gluu.oxauth.model.crypto.signature.RSAPrivateKey; import org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm; import org.gluu.oxauth.model.exception.InvalidJwtException; import org.gluu.oxauth.model.jwt.Jwt; import org.gluu.oxauth.model.jwt.JwtType; import org.gluu.oxauth.model.token.ClientAssertionType; import org.gluu.oxauth.model.uma.UmaScopeType; import javax.ws.rs.core.MediaType; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; /** * Represents a token request to send to the authorization server. * * @author Javier Rojas Blum * @version June 28, 2017 */ public class TokenRequest extends BaseRequest { private static final Logger LOG = Logger.getLogger(TokenRequest.class); public static class Builder { private GrantType grantType; private String scope; public Builder grantType(GrantType grantType) { this.grantType = grantType; return this; } public Builder scope(String scope) { this.scope = scope; return this; } public Builder pat(String... scopeArray) { String scope = UmaScopeType.PROTECTION.getValue(); if (scopeArray != null && scopeArray.length > 0) { for (String s : scopeArray) { scope = scope + " " + s; } } return scope(scope); } public TokenRequest build() { final TokenRequest request = new TokenRequest(grantType); request.setScope(scope); return request; } } private GrantType grantType; private String code; private String redirectUri; private String username; private String password; private String scope; private String assertion; private String refreshToken; private String audience; private String codeVerifier; private SignatureAlgorithm algorithm; private String sharedKey; private RSAPrivateKey rsaPrivateKey; private ECDSAPrivateKey ecPrivateKey; private AbstractCryptoProvider cryptoProvider; private String keyId; /** * Constructs a token request. * * @param grantType The grant type is mandatory and could be: * <code>authorization_code</code>, <code>password</code>, * <code>client_credentials</code>, <code>refresh_token</code>. */ public TokenRequest(GrantType grantType) { super(); this.grantType = grantType; setContentType(MediaType.APPLICATION_FORM_URLENCODED); setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC); } public static Builder builder() { return new Builder(); } public static Builder umaBuilder() { return new Builder().grantType(GrantType.CLIENT_CREDENTIALS); } /** * Returns the grant type. * * @return The grant type. */ public GrantType getGrantType() { return grantType; } /** * Sets the grant type. * * @param grantType The grant type. */ public void setGrantType(GrantType grantType) { this.grantType = grantType; } /** * Returns the authorization code. * * @return The authorization code. */ public String getCode() { return code; } /** * Sets the authorization code. * * @param code The authorization code. */ public void setCode(String code) { this.code = code; } /** * Gets PKCE code verifier. * * @return code verifier */ public String getCodeVerifier() { return codeVerifier; } /** * Sets PKCE code verifier. * * @param codeVerifier code verifier */ public void setCodeVerifier(String codeVerifier) { this.codeVerifier = codeVerifier; } /** * Returns the redirect URI. * * @return The redirect URI. */ public String getRedirectUri() { return redirectUri; } /** * Sets the redirect URI. * * @param redirectUri The redirect URI. */ public void setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; } /** * Returns the username. * * @return The username. */ public String getUsername() { return username; } /** * Sets the username. * * @param username The username. */ public void setUsername(String username) { this.username = username; } /** * Returns the password. * * @return The password. */ public String getPassword() { return password; } /** * Sets the password. * * @param password The password. */ public void setPassword(String password) { this.password = password; } /** * Returns the scope. * * @return The scope. */ public String getScope() { return scope; } /** * Sets the scope. * * @param scope The scope. */ public void setScope(String scope) { this.scope = scope; } /** * Returns the assertion. * * @return The assertion. */ public String getAssertion() { return assertion; } /** * Sets the assertion. * * @param assertion The assertion. */ public void setAssertion(String assertion) { this.assertion = assertion; } /** * Returns the refresh token. * * @return The refresh token. */ public String getRefreshToken() { return refreshToken; } /** * Sets the refresh token. * * @param refreshToken The refresh token. */ public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } public void setAudience(String audience) { this.audience = audience; } public void setAlgorithm(SignatureAlgorithm algorithm) { this.algorithm = algorithm; } public void setSharedKey(String sharedKey) { this.sharedKey = sharedKey; } @Deprecated public void setRsaPrivateKey(RSAPrivateKey rsaPrivateKey) { this.rsaPrivateKey = rsaPrivateKey; } @Deprecated public void setEcPrivateKey(ECDSAPrivateKey ecPrivateKey) { this.ecPrivateKey = ecPrivateKey; } public void setCryptoProvider(AbstractCryptoProvider cryptoProvider) { this.cryptoProvider = cryptoProvider; } public String getKeyId() { return keyId; } public void setKeyId(String keyId) { this.keyId = keyId; } public String getClientAssertion() { if (cryptoProvider == null) { LOG.error("Crypto provider is not specified"); return null; } Jwt clientAssertion = new Jwt(); if (algorithm == null) { algorithm = SignatureAlgorithm.HS256; } GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); Date issuedAt = calendar.getTime(); calendar.add(Calendar.MINUTE, 5); Date expirationTime = calendar.getTime(); // Header clientAssertion.getHeader().setType(JwtType.JWT); clientAssertion.getHeader().setAlgorithm(algorithm); if (StringUtils.isNotBlank(keyId)) { clientAssertion.getHeader().setKeyId(keyId); } // Claims clientAssertion.getClaims().setIssuer(getAuthUsername()); clientAssertion.getClaims().setSubjectIdentifier(getAuthUsername()); clientAssertion.getClaims().setAudience(audience); clientAssertion.getClaims().setJwtId(UUID.randomUUID()); clientAssertion.getClaims().setExpirationTime(expirationTime); clientAssertion.getClaims().setIssuedAt(issuedAt); // Signature try { if (sharedKey == null) { sharedKey = getAuthPassword(); } String signature = cryptoProvider.sign(clientAssertion.getSigningInput(), keyId, sharedKey, algorithm); clientAssertion.setEncodedSignature(signature); } catch (InvalidJwtException e) { LOG.error(e.getMessage(), e); } catch (Exception e) { LOG.error(e.getMessage(), e); } return clientAssertion.toString(); } /** * Returns a query string with the parameters of the authorization request. * Any <code>null</code> or empty parameter will be omitted. * * @return A query string of parameters. */ @Override public String getQueryString() { StringBuilder queryStringBuilder = new StringBuilder(); try { if (grantType != null) { queryStringBuilder.append("grant_type=").append(grantType.toString()); } if (code != null && !code.isEmpty()) { queryStringBuilder.append("&"); queryStringBuilder.append("code=").append(code); } if (redirectUri != null && !redirectUri.isEmpty()) { queryStringBuilder.append("&"); queryStringBuilder.append("redirect_uri=").append( URLEncoder.encode(redirectUri, "UTF-8")); } if (scope != null && !scope.isEmpty()) { queryStringBuilder.append("&"); queryStringBuilder.append("scope=").append( URLEncoder.encode(scope, "UTF-8")); } if (username != null && !username.isEmpty()) { queryStringBuilder.append("&"); queryStringBuilder.append("username=").append(username); } if (password != null && !password.isEmpty()) { queryStringBuilder.append("&"); queryStringBuilder.append("password=").append(password); } if (assertion != null && !assertion.isEmpty()) { queryStringBuilder.append("&"); queryStringBuilder.append("assertion=").append(assertion); } if (refreshToken != null && !refreshToken.isEmpty()) { queryStringBuilder.append("&"); queryStringBuilder.append("refresh_token=").append(refreshToken); } if (getAuthenticationMethod() == AuthenticationMethod.CLIENT_SECRET_POST) { if (getAuthUsername() != null && !getAuthUsername().isEmpty()) { queryStringBuilder.append("&"); queryStringBuilder.append("client_id=").append( URLEncoder.encode(getAuthUsername(), "UTF-8")); } if (getAuthPassword() != null && !getAuthPassword().isEmpty()) { queryStringBuilder.append("&"); queryStringBuilder.append("client_secret=").append( URLEncoder.encode(getAuthPassword(), "UTF-8")); } } else if (getAuthenticationMethod() == AuthenticationMethod.CLIENT_SECRET_JWT || getAuthenticationMethod() == AuthenticationMethod.PRIVATE_KEY_JWT) { queryStringBuilder.append("&client_assertion_type=").append( URLEncoder.encode(ClientAssertionType.JWT_BEARER.toString(), "UTF-8")); queryStringBuilder.append("&"); queryStringBuilder.append("client_assertion=").append(getClientAssertion()); } for (String key : getCustomParameters().keySet()) { queryStringBuilder.append("&"); queryStringBuilder.append(key).append("=").append(getCustomParameters().get(key)); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return queryStringBuilder.toString(); } /** * Returns a collection of parameters of the token request. Any * <code>null</code> or empty parameter will be omitted. * * @return A collection of parameters. */ public Map<String, String> getParameters() { Map<String, String> parameters = new HashMap<String, String>(); if (grantType != null) { parameters.put("grant_type", grantType.toString()); } if (code != null && !code.isEmpty()) { parameters.put("code", code); } if (redirectUri != null && !redirectUri.isEmpty()) { parameters.put("redirect_uri", redirectUri); } if (username != null && !username.isEmpty()) { parameters.put("username", username); } if (password != null && !password.isEmpty()) { parameters.put("password", password); } if (scope != null && !scope.isEmpty()) { parameters.put("scope", scope); } if (assertion != null && !assertion.isEmpty()) { parameters.put("assertion", assertion); } if (refreshToken != null && !refreshToken.isEmpty()) { parameters.put("refresh_token", refreshToken); } if (getAuthenticationMethod() == AuthenticationMethod.CLIENT_SECRET_POST) { if (getAuthUsername() != null && !getAuthUsername().isEmpty()) { parameters.put("client_id", getAuthUsername()); } if (getAuthPassword() != null && !getAuthPassword().isEmpty()) { parameters.put("client_secret", getAuthPassword()); } } else if (getAuthenticationMethod() == AuthenticationMethod.CLIENT_SECRET_JWT || getAuthenticationMethod() == AuthenticationMethod.PRIVATE_KEY_JWT) { parameters.put("client_assertion_type", ClientAssertionType.JWT_BEARER.toString()); parameters.put("client_assertion", getClientAssertion()); } for (String key : getCustomParameters().keySet()) { parameters.put(key, getCustomParameters().get(key)); } return parameters; } }
package RestaurantProject; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.*; public class UnitTestRestaurantProject implements Food { public UnitTestRestaurantProject() { } public String getName() { return " "; } public int getNum() { return 0; } public void setNum(int x) { } public double getPrice() { return 0.0; } @Before//sets up test fixture public void setUp() { } @After//tears down test fixture public void tearDown() { } @Test public void testSolidFoodprice() { SolidFood s1=new SolidFood("Burger",1); assertEquals(5,s1.getPrice(),0.1); } @Test public void testgetNum() { SolidFood s2= new SolidFood("Sandwich",1); assertEquals(1,s2.getNum()); } @Test public void testsetNum() { SolidFood s3=new SolidFood("Sandwich",1); s3.setNum(3); assertEquals(3,s3.getNum()); } @Test public void testDrinkprice() { Drink d1=new Drink("Soda", 1); assertEquals(1,d1.getPrice(),0.1); } @Test public void testOrder() { Order order1=new Order(); SolidFood s1= new SolidFood("Burger",1); SolidFood s2= new SolidFood("Sandwich",1); SolidFood s3= new SolidFood("Sandwich", 1); Drink d1 =new Drink("Soda",1); order1.add(s1); order1.add(s2); order1.add(d1); List<Food>test=new ArrayList<Food>(); test.add(s1); test.add(s2); test.add(d1); Food f1= order1.getOrder().get(0); assertEquals(s1,f1); } @Test public void testCustomerGetNumber() { Customer c1= new Customer(); Customer c2=new Customer(); Customer c3=new Customer(); assertEquals(3,Customer.getNumber()); } @Test public void testFoodDrawings() { } @Test public void testFoodDrawingsRunner() { } }
package kong.unirest; import kong.unirest.apache.ApacheAsyncClient; import kong.unirest.apache.ApacheClient; import org.apache.http.HttpRequestInterceptor; import org.apache.http.client.HttpClient; import org.apache.http.nio.client.HttpAsyncClient; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; public class Config { public static final int DEFAULT_CONNECTION_TIMEOUT = 10000; public static final int DEFAULT_MAX_CONNECTIONS = 200; public static final int DEFAULT_MAX_PER_ROUTE = 20; public static final int DEFAULT_CONNECT_TIMEOUT = 10000; public static final int DEFAULT_SOCKET_TIMEOUT = 60000; private Optional<Client> client = Optional.empty(); private Optional<AsyncClient> asyncClient = Optional.empty(); private Optional<ObjectMapper> objectMapper = Optional.empty(); private List<HttpRequestInterceptor> interceptors = new ArrayList<>(); private Headers headers; private Proxy proxy; private int connectionTimeout; private int socketTimeout; private int maxTotal; private int maxPerRoute; private boolean followRedirects; private boolean cookieManagement; private boolean useSystemProperties; private String defaultResponseEncoding = StandardCharsets.UTF_8.name(); private Function<Config, AsyncClient> asyncBuilder = ApacheAsyncClient::new; private Function<Config, Client> clientBuilder = ApacheClient::new; private boolean requestCompressionOn = true; private boolean automaticRetries; private boolean verifySsl = true; private boolean addShutdownHook = false; private KeyStore keystore; private String keystorePassword; private String cookieSpec; private UniMetric metrics = new NoopMetric(); public Config() { setDefaults(); } private void setDefaults() { interceptors.clear(); proxy = null; headers = new Headers(); connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; socketTimeout = DEFAULT_SOCKET_TIMEOUT; maxTotal = DEFAULT_MAX_CONNECTIONS; maxPerRoute = DEFAULT_MAX_PER_ROUTE; followRedirects = true; cookieManagement = true; requestCompressionOn = true; automaticRetries = true; verifySsl = true; keystore = null; keystorePassword = null; } /** * Set the HttpClient implementation to use for every synchronous request * * @param httpClient Custom httpClient implementation * @return this config object */ public Config httpClient(HttpClient httpClient) { client = Optional.of(new ApacheClient(httpClient, this, null, null)); return this; } /** * Set the HttpClient implementation to use for every synchronous request * * @param httpClient Custom httpClient implementation * @return this config object */ public Config httpClient(Client httpClient) { client = Optional.of(httpClient); return this; } /** * Provide a builder for a client * * @param httpClient Custom httpClient implementation * @return this config object */ public Config httpClient(Function<Config, Client> httpClient) { clientBuilder = httpClient; return this; } /** * Set the asynchronous AbstractHttpAsyncClient implementation to use for every asynchronous request * * @param value Custom CloseableHttpAsyncClient implementation * @return this config object */ public Config asyncClient(HttpAsyncClient value) { this.asyncClient = Optional.of(new ApacheAsyncClient(value, this, null, null)); return this; } /** * Set the full async configuration including monitors. These will be shutDown on a Unirest.shudown() * * @param value Custom AsyncConfig class. The actual AsyncHttpClient is required. * @return this config object */ public Config asyncClient(AsyncClient value) { asyncClient = Optional.of(value); return this; } /** * Set the full async configuration including monitors. These will be shutDown on a Unirest.shudown() * * @param asyncClientBuilder A builder function for creating a AsyncClient * @return this config object */ public Config asyncClient(Function<Config, AsyncClient> asyncClientBuilder) { this.asyncBuilder = asyncClientBuilder; return this; } /** * Set a proxy * * @param value Proxy settings object. * @return this config object */ public Config proxy(Proxy value) { validateClientsNotRunning(); this.proxy = value; return this; } /** * Set a proxy * * @param host the hostname of the proxy server. * @param port the port of the proxy server * @return this config object */ public Config proxy(String host, int port) { return proxy(new Proxy(host, port)); } /** * Set an authenticated proxy * * @param host the hostname of the proxy server. * @param port the port of the proxy server * @param username username for authenticated proxy * @param password password for authenticated proxy * @return this config object */ public Config proxy(String host, int port, String username, String password) { return proxy(new Proxy(host, port, username, password)); } /** * Set the ObjectMapper implementation to use for Response to Object binding * * @param om Custom implementation of ObjectMapper interface * @return this config object */ public Config setObjectMapper(ObjectMapper om) { this.objectMapper = Optional.ofNullable(om); return this; } /** * Set a custom keystore * * @param store the keystore to use for a custom ssl context * @param password the password for the store * @return this config object */ public Config clientCertificateStore(KeyStore store, String password) { this.keystore = store; this.keystorePassword = password; return this; } /** * Set a custom keystore via a file path. Must be a valid PKCS12 file * * @param fileLocation the path keystore to use for a custom ssl context * @param password the password for the store * @return this config object */ public Config clientCertificateStore(String fileLocation, String password) { try (InputStream keyStoreStream = Util.getFileInputStream(fileLocation)) { this.keystorePassword = password; this.keystore = KeyStore.getInstance("PKCS12"); this.keystore.load(keyStoreStream, keystorePassword.toCharArray()); } catch (Exception e) { throw new UnirestConfigException(e); } return this; } /** * Set the connection timeout * * @param inMillies The timeout until a connection with the server is established (in milliseconds). Default is 10000. Set to zero to disable the timeout. * @return this config object */ public Config connectTimeout(int inMillies) { validateClientsNotRunning(); this.connectionTimeout = inMillies; return this; } /** * Set the socket timeout * * @param inMillies The timeout to receive data (in milliseconds). Default is 60000. Set to zero to disable the timeout. * @return this config object */ public Config socketTimeout(int inMillies) { validateClientsNotRunning(); this.socketTimeout = inMillies; return this; } /** * Set the concurrency levels * * @param total Defines the overall connection limit for a connection pool. Default is 200. * @param perRoute Defines a connection limit per one HTTP route (this can be considered a per target host limit). Default is 20. * @return this config object */ public Config concurrency(int total, int perRoute) { validateClientsNotRunning(); this.maxTotal = total; this.maxPerRoute = perRoute; return this; } /** * Clear default headers * @return this config object */ public Config clearDefaultHeaders() { headers.clear(); return this; } /** * Default basic auth credentials * @param username the username * @param password the password * @return this config object */ public Config setDefaultBasicAuth(String username, String password) { headers.replace("Authorization", Util.toBasicAuthValue(username, password)); return this; } /** * Set default header to appear on all requests * * @param name The name of the header. * @param value The value of the header. * @return this config object */ public Config setDefaultHeader(String name, String value) { headers.replace(name, value); return this; } /** * Set default header to appear on all requests, value is through a Supplier * This is useful for adding tracing elements to requests. * * @param name The name of the header. * @param value a supplier that will get called as part of the request. * @return this config object */ public Config setDefaultHeader(String name, Supplier<String> value) { headers.add(name, value); return this; } /** * Add default header to appear on all requests * * @param name The name of the header. * @param value The value of the header. * @return this config object */ public Config addDefaultHeader(String name, String value) { headers.add(name, value); return this; } /** * Add a metric object for instrumentation * @param metric a UniMetric object * @return this config object */ public Config instrumentWith(UniMetric metric) { this.metrics = metric; return this; } public Config addInterceptor(HttpRequestInterceptor interceptor) { validateClientsNotRunning(); interceptors.add(interceptor); return this; } /** * Allow the client to follow redirects. Defaults to TRUE * * @param enable The name of the header. * @return this config object */ public Config followRedirects(boolean enable) { validateClientsNotRunning(); this.followRedirects = enable; return this; } /** * Allow the client to manage cookies. Defaults to TRUE * * @param enable The name of the header. * @return this config object */ public Config enableCookieManagement(boolean enable) { validateClientsNotRunning(); this.cookieManagement = enable; return this; } /** * Toggle verifying SSL/TLS certificates. Defaults to TRUE * * @param value a bool is its true or not. * @return this config object */ public Config verifySsl(boolean value) { this.verifySsl = value; return this; } /** * Tell the HttpClients to use the system properties for things like proxies * * @param value a bool is its true or not. * @return this config object */ public Config useSystemProperties(boolean value) { this.useSystemProperties = value; return this; } /** * Turn on or off requesting all content as compressed. (GZIP encoded) * Default is true * * @param value a bool is its true or not. * @return this config object */ public Config requestCompression(boolean value) { this.requestCompressionOn = value; return this; } /** * Automaticly retry certain recoverable errors like socket timeouts. Up to 4 times * Note that currently this only works on synchronous calls. * Default is true * * @param value a bool is its true or not. * @return this config object */ public Config automaticRetries(boolean value) { automaticRetries = value; return this; } /** * Sets a cookie policy * Acceptable values: * 'default' (same as Netscape), * 'netscape', * 'ignoreCookies', * 'standard' (RFC 6265 interoprability profile) , * 'standard-strict' (RFC 6265 strict profile) * * @param policy: the policy for cookies to follow * @return this config object */ public Config cookieSpec(String policy) { this.cookieSpec = policy; return this; } /** * Set the default encoding that will be used for serialization into Strings. * The default-default is UTF-8 * * @param value a bool is its true or not. * @return this config object */ public Config setDefaultResponseEncoding(String value) { Objects.requireNonNull(value, "Encoding cannot be null"); this.defaultResponseEncoding = value; return this; } /** * Register the client with a system shutdown hook. Note that this creates up to two threads * (depending on if you use both sync and async clients). default is false * * @param value a bool is its true or not. * @return this config object */ public Config addShutdownHook(boolean value) { this.addShutdownHook = value; if (value) { client.ifPresent(Client::registerShutdownHook); asyncClient.ifPresent(AsyncClient::registerShutdownHook); } return this; } /** * Return default headers that are added to every request * * @return Headers */ public Headers getDefaultHeaders() { return headers; } /** * Does the config have currently running clients? Find out here. * * @return boolean */ public boolean isRunning() { return client.isPresent() || asyncClient.isPresent(); } /** * Shutdown the current config and re-init. * * @return this config */ public Config reset() { shutDown(false); return this; } /** * Shut down the configuration and its clients. * The config can be re-initialized with its settings * * @param clearOptions should the current non-client settings be retained. */ public void shutDown(boolean clearOptions) { List<Exception> ex = Stream.concat( client.map(Client::close).orElseGet(Stream::empty), asyncClient.map(AsyncClient::close).orElseGet(Stream::empty) ).collect(Collectors.toList()); client = Optional.empty(); asyncClient = Optional.empty(); if (clearOptions) { setDefaults(); } if (!ex.isEmpty()) { throw new UnirestException(ex); } } /** * Return the current Client. One will be build if it does * not yet exist. * * @return A synchronous Client */ public Client getClient() { if (!client.isPresent()) { buildClient(); } return client.get(); } private synchronized void buildClient() { if (!client.isPresent()) { client = Optional.of(clientBuilder.apply(this)); } } /** * Return the current HttpAsyncClient. One will be build if it does * not yet exist. * * @return Apache HttpAsyncClient */ public AsyncClient getAsyncClient() { if (!asyncClientIsReady()) { buildAsyncClient(); } return asyncClient.get(); } private boolean asyncClientIsReady() { return asyncClient .map(AsyncClient::isRunning) .orElse(false); } private synchronized void buildAsyncClient() { if (!asyncClientIsReady()) { AsyncClient value = asyncBuilder.apply(this); verifyIsOn(value); asyncClient = Optional.of(value); } } private void verifyIsOn(AsyncClient value) { if (!value.isRunning()) { throw new UnirestConfigException("Attempted to get a new async client but it was not started. Please ensure it is"); } } // Accessors for unirest. /** * @return if cookie management should be enabled. * default: true */ public boolean getEnabledCookieManagement() { return cookieManagement; } /** * @return if the clients should follow redirects * default: true */ public boolean getFollowRedirects() { return followRedirects; } /** * @return the maximum number of connections the clients for this config will manage at once * default: 200 */ public int getMaxConnections() { return maxTotal; } /** * @return the maximum number of connections per route the clients for this config will manage at once * default: 20 */ public int getMaxPerRoutes() { return maxPerRoute; } /** * @return the connection timeout in milliseconds * default: 10000 */ public int getConnectionTimeout() { return connectionTimeout; } /** * @return socket timeout in milliseconds * default: 60000 */ public int getSocketTimeout() { return socketTimeout; } /** * @return a security keystore if one has been provided */ public KeyStore getKeystore() { return this.keystore; } /** * @return The password for the keystore if provided */ public String getKeyStorePassword() { return this.keystorePassword; } /** * @return a configured object mapper * @throws UnirestException if none has been configured. */ public ObjectMapper getObjectMapper() { return objectMapper.orElseThrow(() -> new UnirestException("No Object Mapper Configured. Please config one with Unirest.config().setObjectMapper")); } private void validateClientsNotRunning() { if (client.isPresent() || asyncClient.isPresent()) { throw new UnirestConfigException( "Http Clients are already built in order to build a new config execute Unirest.config().reset() before changing settings. \n" + "This should be done rarely." ); } } public List<HttpRequestInterceptor> getInterceptors() { return interceptors; } public Proxy getProxy() { return proxy; } public boolean useSystemProperties() { return this.useSystemProperties; } public String getDefaultResponseEncoding() { return defaultResponseEncoding; } public boolean isRequestCompressionOn() { return requestCompressionOn; } public boolean isAutomaticRetries() { return automaticRetries; } public boolean isVerifySsl() { return verifySsl; } public boolean shouldAddShutdownHook() { return addShutdownHook; } public String getCookieSpec() { return cookieSpec; } public UniMetric getMetric() { return metrics; } }
package edu.umd.cs.findbugs; import java.io.IOException; import edu.umd.cs.findbugs.xml.OutputStreamXMLOutput; /** * Report warnings as an XML document. * * @author David Hovemeyer */ public class XMLBugReporter extends BugCollectionBugReporter { public XMLBugReporter(Project project) { super(project); } public void setAddMessages(boolean enable) { getBugCollection().setWithMessages(enable); } @Override public void finish() { try { Project project = getProject(); if (project == null) throw new NullPointerException("No project"); getBugCollection().writeXML(outputStream, project); } catch (IOException e) { throw new FatalException("Error writing XML output", e); } } } // vim:ts=4
package edu.umd.cs.findbugs.detect; import java.util.HashSet; import java.util.Set; import org.apache.bcel.Repository; import org.apache.bcel.classfile.JavaClass; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ch.Subtypes; public class Analyze { static private JavaClass serializable; static private JavaClass collection; static private JavaClass map; static private ClassNotFoundException storedException; static { try { serializable = Repository.lookupClass("java.io.Serializable"); collection = Repository.lookupClass("java.util.Collection"); map = Repository.lookupClass("java.util.Map"); } catch (ClassNotFoundException e) { storedException = e; } } private static boolean containsConcreteClasses(Set<JavaClass> s) { for (JavaClass c : s) if (!c.isInterface() && !c.isAbstract()) return true; return false; } public static double isDeepSerializable(String refSig) throws ClassNotFoundException { if (storedException != null) throw storedException; if (isPrimitiveComponentClass(refSig)) return 0.99; String refName = getComponentClass(refSig); if (refName.equals("java.lang.Object")) return 0.99; JavaClass refJavaClass = Repository.lookupClass(refName); return isDeepSerializable(refJavaClass); } private static boolean isPrimitiveComponentClass(String refSig) { int c = 0; while (refSig.charAt(c++) == '[') {} return refSig.charAt(c) != 'L'; } public static String getComponentClass(String refSig) { while (refSig.charAt(0) == '[') refSig = refSig.substring(1); //TODO: This method now returns primitive type signatures, is this ok? if (refSig.charAt(0) == 'L') return refSig.substring(1, refSig.length() - 1).replace('/', '.'); return refSig; } public static double isDeepSerializable(JavaClass x) throws ClassNotFoundException { if (storedException != null) throw storedException; double result = deepInstanceOf(x, serializable); if (result >= 0.9) return result; result = Math.max(result, deepInstanceOf(x, collection)); if (result >= 0.9) return result; result = Math.max(result, deepInstanceOf(x, map)); return result; } /** * Given two JavaClasses, try to estimate the probability that an reference * of type x is also an instance of type y. Will return 0 only if it is * impossiblem and 1 only if it is guaranteed. * * @param x * Known type of object * @param y * Type queried about * @return 0 - 1 value indicating probablility */ public static double deepInstanceOf(JavaClass x, JavaClass y) throws ClassNotFoundException { if (x.equals(y)) return 1.0; boolean xIsSubtypeOfY = Repository.instanceOf(x, y); if (xIsSubtypeOfY) return 1.0; boolean yIsSubtypeOfX = Repository.instanceOf(y, x); if (!yIsSubtypeOfX) { if (x.isFinal() || y.isFinal()) return 0.0; if (!x.isInterface() && !y.isInterface()) return 0.0; } Subtypes subtypes = AnalysisContext.currentAnalysisContext() .getSubtypes(); subtypes.addClass(x); subtypes.addClass(y); Set<JavaClass> xSubtypes = subtypes.getTransitiveSubtypes(x); Set<JavaClass> ySubtypes = subtypes.getTransitiveSubtypes(y); Set<JavaClass> both = new HashSet<JavaClass>(xSubtypes); both.retainAll(ySubtypes); Set<JavaClass> xButNotY = new HashSet<JavaClass>(xSubtypes); xButNotY.removeAll(ySubtypes); if (false && yIsSubtypeOfX && both.isEmpty()) { System.out.println("Strange: y is subtype of x, but no classes in both"); System.out.println("X : " + x.getClassName()); System.out.println("Immediate subtypes:"); for(JavaClass c : subtypes.getImmediateSubtypes(x)) System.out.println(" " + c.getClassName()); System.out.println("transitive subtypes:"); for(JavaClass c : xSubtypes) System.out.println(" " + c.getClassName()); System.out.println("Y : " + y.getClassName()); System.out.println("Immediate subtypes:"); for(JavaClass c : subtypes.getImmediateSubtypes(y)) System.out.println(" " + c.getClassName()); System.out.println("transitive subtypes:"); for(JavaClass c : ySubtypes) System.out.println(" " + c.getClassName()); } boolean concreteClassesInXButNotY = containsConcreteClasses(xButNotY); if (both.isEmpty()) { if (concreteClassesInXButNotY) { return 0.1; } return 0.3; } // exist classes that are both X and Y if (!concreteClassesInXButNotY) { // only abstract/interfaces that are X but not Y return 0.99; } // Concrete classes in X but not Y return 0.7; } }
package edu.umd.cs.findbugs.gui2; import java.io.File; enum SaveType {NOT_KNOWN, PROJECT, XML_ANALYSIS, FBP_FILE, FBA_FILE; public FindBugsFileFilter getFilter() { switch (this) { case PROJECT: return FindBugsProjectFileFilter.INSTANCE; case XML_ANALYSIS: return FindBugsAnalysisFileFilter.INSTANCE; case FBP_FILE: return FindBugsFBPFileFilter.INSTANCE; case FBA_FILE: return FindBugsFBAFileFilter.INSTANCE; default: throw new IllegalArgumentException("No filter for type NOT_UNKNOWN"); } } public boolean isValid(File f) { if (this == PROJECT) { return OriginalGUI2ProjectFile.isValid(f); } if (f.isDirectory()) return false; FindBugsFileFilter filter = getFilter(); return filter.accept(f); } public String getFileExtension() { switch (this) { case PROJECT: return ""; case XML_ANALYSIS: return ".xml"; case FBP_FILE: return ".fbp"; case FBA_FILE: return ".fba"; default: throw new IllegalArgumentException("No filter for type NOT_UNKNOWN"); } } private static String getFileExtension(File f) { String name = f.getName(); int lastDot = name.lastIndexOf('.'); if (lastDot == -1) return ""; return name.substring(lastDot+1).toLowerCase(); } public static SaveType forFile(File f) { String extension = getFileExtension(f); if (OriginalGUI2ProjectFile.isValid(f)) return PROJECT; if (extension.equals("fbp")) return FBP_FILE; if (extension.equals("fba")) return FBA_FILE; if (extension.equals("xml")) return XML_ANALYSIS; return NOT_KNOWN; } }
package nucleus.presenter; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import java.util.concurrent.CopyOnWriteArrayList; /** * This is a base class for all presenters. Subclasses can override * {@link #onCreate}, {@link #onDestroy}, {@link #onSave}, * {@link #onTakeView}, {@link #onDropView}. * <p/> * {@link Presenter.OnDestroyListener} can also be used by external classes * to be notified about the need of freeing resources. * * @param <View> a type of view to return with {@link #getView()}. */ public class Presenter<View> { @Nullable private View view; private CopyOnWriteArrayList<OnDestroyListener> onDestroyListeners = new CopyOnWriteArrayList<>(); /** * This method is called after presenter construction. * * This method is intended for overriding. * * @param savedState If the presenter is being re-instantiated after a process restart then this Bundle * contains the data it supplied in {@link #onSave}. */ protected void onCreate(@Nullable Bundle savedState) { } /** * This method is being called when a user leaves view. * * This method is intended for overriding. */ protected void onDestroy() { } /** * A returned state is the state that will be passed to {@link #onCreate} for a new presenter instance after a process restart. * * This method is intended for overriding. * * @param state a non-null bundle which should be used to put presenter's state into. */ protected void onSave(Bundle state) { } /** * This method is being called when a view gets attached to it. * Normally this happens during {@link Activity#onResume()}, {@link android.app.Fragment#onResume()} * and {@link android.view.View#onAttachedToWindow()}. * * This method is intended for overriding. * * @param view a view that should be taken */ protected void onTakeView(View view) { } /** * This method is being called when a view gets detached from the presenter. * Normally this happens during {@link Activity#onPause()} ()}, {@link Fragment#onPause()} ()} * and {@link android.view.View#onDetachedFromWindow()}. * * This method is intended for overriding. */ protected void onDropView() { } /** * A callback to be invoked when a presenter is about to be destroyed. */ public interface OnDestroyListener { /** * Called before {@link Presenter#onDestroy()}. */ void onDestroy(); } /** * Adds a listener observing {@link #onDestroy}. * * @param listener a listener to add. */ public void addOnDestroyListener(OnDestroyListener listener) { onDestroyListeners.add(listener); } /** * Removed a listener observing {@link #onDestroy}. * * @param listener a listener to remove. */ public void removeOnDestroyListener(OnDestroyListener listener) { onDestroyListeners.remove(listener); } /** * Returns a current view attached to the presenter or null. * * View is normally available between * {@link Activity#onResume()} and {@link Activity#onPause()}, * {@link Fragment#onResume()} and {@link Fragment#onPause()}, * {@link android.view.View#onAttachedToWindow()} and {@link android.view.View#onDetachedFromWindow()}. * * Calls outside of these ranges will return null. * Notice here that {@link Activity#onActivityResult(int, int, Intent)} is called *before* {@link Activity#onResume()} * so you can't use this method as a callback. * * @return a current attached view. */ @Nullable public View getView() { return view; } /** * Initializes the presenter. */ public void create(Bundle bundle) { onCreate(bundle); } /** * Destroys the presenter, calling all {@link Presenter.OnDestroyListener} callbacks. */ public void destroy() { for (OnDestroyListener listener : onDestroyListeners) listener.onDestroy(); onDestroy(); } /** * Saves the presenter. */ public void save(Bundle state) { onSave(state); } /** * Attaches a view to the presenter. * * @param view a view to attach. */ public void takeView(View view) { this.view = view; onTakeView(view); } /** * Detaches the presenter from a view. */ public void dropView() { onDropView(); this.view = null; } }
package com.ikasoa.rpc.utils; import java.util.Base64; /** * * * @author <a href="mailto:larry7696@gmail.com">Larry</a> * @version 0.1 */ public class Base64Util { /** * * * @param bstr * * @return String */ public static String encode(byte[] bstr) { return Base64.getEncoder().encodeToString(bstr); } /** * * * @param str * * @return byte[] */ public static byte[] decode(String str) { return Base64.getDecoder().decode(str); } }
package com.ibm.sk.ff.gui.client; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ibm.sk.ff.gui.common.GUIOperations; import com.ibm.sk.ff.gui.common.events.GuiEvent; import com.ibm.sk.ff.gui.common.events.GuiEventListener; import com.ibm.sk.ff.gui.common.mapper.Mapper; import com.ibm.sk.ff.gui.common.objects.gui.GAntFoodObject; import com.ibm.sk.ff.gui.common.objects.gui.GAntObject; import com.ibm.sk.ff.gui.common.objects.gui.GFoodObject; import com.ibm.sk.ff.gui.common.objects.gui.GHillObject; import com.ibm.sk.ff.gui.common.objects.gui.GUIObject; import com.ibm.sk.ff.gui.common.objects.gui.GUIObjectCrate; import com.ibm.sk.ff.gui.common.objects.gui.GUIObjectTypes; import com.ibm.sk.ff.gui.common.objects.operations.CloseData; import com.ibm.sk.ff.gui.common.objects.operations.CreateGameData; import com.ibm.sk.ff.gui.common.objects.operations.InitMenuData; import com.ibm.sk.ff.gui.common.objects.operations.ResultData; import com.ibm.sk.ff.gui.common.objects.operations.ScoreData; public class GUIFacade { private final Client CLIENT; private final List<GuiEventListener> guiEventListeners = new ArrayList<>(); private final List<GAntFoodObject> antFoodObjects = new ArrayList<>(); private final Map<GAntObject, GAntFoodObject> notRenderedYet = new HashMap<>(); public GUIFacade() { this.CLIENT = new Client(); new Thread(new Runnable() { @Override public void run() { final int sleepTime = Integer.parseInt(Config.SERVER_POLL_INTERVAL.toString()); while (true) { try { Thread.sleep(sleepTime); checkEvents(); } catch (final Exception e) { e.printStackTrace(); } } } }).start(); } public void set(final GUIObject object) { set(new GUIObject[] {object}); } public void set(final GUIObject[] o) { if (o != null && o.length > 0) { GUIObject [] objects = map(o); final GUIObjectCrate crate = new GUIObjectCrate(); for (final GUIObject guiObject : objects) { if (guiObject instanceof GHillObject) { final GHillObject hill = (GHillObject) guiObject; crate.getHills().add(hill); } if (guiObject instanceof GAntObject) { final GAntObject ant = (GAntObject) guiObject; crate.getAnts().add(ant); } if (guiObject instanceof GFoodObject) { final GFoodObject food = (GFoodObject) guiObject; crate.getFoods().add(food); } if (guiObject instanceof GAntFoodObject) { final GAntFoodObject antFood = (GAntFoodObject) guiObject; crate.getAntFoods().add(antFood); } } this.CLIENT.postMessage(GUIOperations.SET.toString(), Mapper.INSTANCE.pojoToJson(crate)); } sendNotYetRenderedData(o); } private void sendNotYetRenderedData(GUIObject[] o) { if (notRenderedYet.size() > 0) { List<GAntObject> antsToRemove = new ArrayList<>(); List<GFoodObject> foodsToRemove = new ArrayList<>(); notRenderedYet.values().stream().forEach(af -> { antsToRemove.add(af.getAnt()); foodsToRemove.add(af.getFood()); } ); remove(antsToRemove.stream().toArray(GAntObject[]::new)); remove(foodsToRemove.stream().toArray(GFoodObject[]::new)); this.CLIENT.postMessage( GUIOperations.SET.toString() + "/" + GUIObjectTypes.ANT_FOOD.toString(), Mapper.INSTANCE.pojoToJson(mapNotYetRendered(o)) ); } } private GAntFoodObject[] mapNotYetRendered(GUIObject[] o) { List<GAntFoodObject> ret = new ArrayList<>(); for (GUIObject it : o) { if (it.getType() == GUIObjectTypes.ANT) { GAntObject swp = (GAntObject)it; if (notRenderedYet.containsKey(swp)) { GAntFoodObject toAdd = notRenderedYet.remove(swp); toAdd.setLocation(swp.getLocation()); ret.add(toAdd); } } } return ret.stream().toArray(GAntFoodObject[]::new); } private GUIObject[] map(GUIObject[] orig) { List<GUIObject> ret = new ArrayList<>(orig.length); for (GUIObject it : orig) { if (it.getType() == GUIObjectTypes.ANT) { GAntFoodObject mapped = getMapped((GAntObject)it); if (mapped != null && !notRenderedYet.containsValue(mapped)) { mapped.setLocation(it.getLocation()); ret.add(mapped); } else { ret.add(it); } } else { ret.add(it); } } return ret.stream().toArray(GUIObject[]::new); } private GAntFoodObject getMapped(GAntObject ant) { return antFoodObjects.stream().filter(af -> af.getAnt().equals(ant)).findFirst().orElse(null); } public GAntFoodObject join(GAntObject ant, GFoodObject food) { GAntFoodObject gafo = getMapped(ant); if (!antFoodObjects.contains(gafo)) { gafo = new GAntFoodObject(); gafo.setAnt(ant); gafo.setFood(food); antFoodObjects.add(gafo); notRenderedYet.put(ant, gafo); } return gafo; } public GUIObject[] separate(GAntObject ant) { List<GUIObject> retList = new ArrayList<>(); GAntFoodObject gafo = getMapped(ant); if (antFoodObjects.contains(gafo)) { antFoodObjects.stream() .filter(afo -> afo.getAnt().equals(ant)) .forEach(afo -> retList.add(afo.getFood())); antFoodObjects.remove(gafo); remove(gafo); set(ant); } return retList.stream().toArray(GUIObject[]::new); } public void separate(GFoodObject food) { //TODO } public void separate(GAntObject ant, GFoodObject food) { //TODO } public void remove(final GUIObject data) { remove(new GUIObject [] {data}); } public void remove(final GUIObject[] data) { if (data.length > 0) { this.CLIENT.postMessage(GUIOperations.REMOVE.toString() + "/" + data[0].getType().toString(), Mapper.INSTANCE.pojoToJson(data)); } } public void showScore(final ScoreData data) { this.CLIENT.postMessage(GUIOperations.SCORE.toString(), Mapper.INSTANCE.pojoToJson(data)); } // Operations public void showInitMenu(final InitMenuData data) { this.CLIENT.postMessage(GUIOperations.SHOW_INIT_MENU.toString(), Mapper.INSTANCE.pojoToJson(data)); } public void createGame(final CreateGameData data) { this.CLIENT.postMessage(GUIOperations.CREATE_GAME.toString(), Mapper.INSTANCE.pojoToJson(data)); } public void showResult(final ResultData data) { this.CLIENT.postMessage(GUIOperations.SHOW_RESULT.toString(), Mapper.INSTANCE.pojoToJson(data)); } public void close(final CloseData data) { this.CLIENT.postMessage(GUIOperations.CLOSE.toString(), Mapper.INSTANCE.pojoToJson(data)); } // Poll for events private void checkEvents() { final String events = this.CLIENT.getMessage(GUIOperations.EVENT_POLL.toString()); if (events != null && events.length() > 0) { final GuiEvent[] swp = Mapper.INSTANCE.jsonToPojo(events, GuiEvent[].class); castEvent(swp); } } // EVENTS public void addGuiEventListener(final GuiEventListener listener) { this.guiEventListeners.add(listener); } public void removeGuiEventListener(final GuiEventListener listener) { this.guiEventListeners.remove(listener); } private void castEvent(final GuiEvent[] event) { for (final GuiEvent it : event) { this.guiEventListeners.stream().forEach(l -> l.actionPerformed(it)); } } }
package edu.upenn.cis.pennapps.pollio; import java.util.Locale; import android.app.Activity; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.NavUtils; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void newPoll(View view) { Intent i = new Intent(this, MultipleChoicePoll.class); startActivity(i); } public void TakePollio(View view) { } public void ShowMyPollio(View view) { } }
package org.neo4j.kernel.ha; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; public class ToFileStoreWriter implements StoreWriter { private final File basePath; public ToFileStoreWriter( String graphDbStoreDir ) { this.basePath = new File( graphDbStoreDir ); } public void write( String path, ReadableByteChannel data, boolean hasData ) throws IOException { try { File file = new File( basePath, path ); RandomAccessFile randomAccessFile = null; try { file.getParentFile().mkdirs(); randomAccessFile = new RandomAccessFile( file, "rw" ); if ( hasData ) { ByteBuffer intermediateBuffer = ByteBuffer.allocateDirect( 1024 ); FileChannel channel = randomAccessFile.getChannel(); while ( data.read( intermediateBuffer ) >= 0 ) { intermediateBuffer.flip(); channel.write( intermediateBuffer ); intermediateBuffer.clear(); } } } finally { if ( randomAccessFile != null ) { randomAccessFile.close(); } } } catch ( Throwable t ) { t.printStackTrace(); throw new IOException( t ); } } public void done() { // Do nothing } }
package whelk.export.servlet; import org.junit.Assert; import org.junit.*; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.File; import java.io.StringReader; public class ApiTest { /** * These tests are based on the assumption that the test data (see /librisxl-tools/scripts/example_records.tsv) is * loaded into a database, and the secrets.properties file correctly addresses this database. */ private static Server s_jettyServer; @BeforeClass public static void setUp() throws Exception { // Start the OAI-PMH servlet in an embedded jetty container s_jettyServer = new Server(TestCommon.port); ServletHandler servletHandler = new ServletHandler(); s_jettyServer.setHandler(servletHandler);
package controllers; import com.mashape.unirest.http.exceptions.UnirestException; import factories.BidirectionalLoginDataCustomFactory; import factories.BidirectionalPendingPasswordResetFactory; import factories.BidirectionalUserFactory; import funWebMailer.FunWebMailer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import pojos.LoginDataCustom; import pojos.PendingPasswordReset; import pojos.User; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Controller @SessionAttributes(value = "username") public class MainController { User loggedInUser = null; @RequestMapping(value ="statistics", method = RequestMethod.GET) public String getStatistics(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return "error"; } return "statistics"; } @RequestMapping(value = "/register", method = RequestMethod.GET) public String getRegisterPage(HttpServletRequest request) { return "register"; } @RequestMapping(value = "/change_password", method = RequestMethod.GET) public String getChangePassword(HttpServletRequest request) { return "change_password"; } @RequestMapping(value = "/change_password", method = RequestMethod.POST) public ModelAndView postChangePassword( @RequestParam(name = "current_password") String current_passsword, @RequestParam(name = "new_password") String new_password, @RequestParam(name = "new_password2") String new_password2, HttpServletRequest request) { User user = null; try { user = BidirectionalUserFactory.newInstance((String) request.getSession().getAttribute("username")); } catch (UnirestException e) { e.printStackTrace(); } String loginDataCustomPassword = null; try { loginDataCustomPassword = BidirectionalLoginDataCustomFactory.getPassword(user.getId()); } catch (UnirestException e) { e.printStackTrace(); } if (!String.valueOf(new_password2.hashCode()).equals(loginDataCustomPassword)) { return new ModelAndView("redirect:/error"); } if (!new_password.equals(new_password2)) { return new ModelAndView("redirect:/error"); } return new ModelAndView("success_recover"); } @RequestMapping(value = "/recover_password", method = RequestMethod.GET) public String getRecoverPasswordPage() { return "recover_password"; } @RequestMapping( value = "/recoverPassword", method = RequestMethod.POST ) public ModelAndView postRecoverPassword( @RequestParam(name = "username") String username) { User user = null; try { user = BidirectionalUserFactory.newInstance(username); } catch (UnirestException e) { e.printStackTrace(); } String recoverUrlToken = UUID.randomUUID().toString(); // send mail with reset link for the password String recoverUrl = String.format("localhost:8089/reset_password/%s", recoverUrlToken); PendingPasswordReset pendingPasswordReset = new PendingPasswordReset(); pendingPasswordReset.setId(0l); // Dummy pendingPasswordReset.setToken(recoverUrlToken); pendingPasswordReset.setUsername(user.getName()); try { BidirectionalPendingPasswordResetFactory.persist(pendingPasswordReset); } catch (UnirestException e) { e.printStackTrace(); } FunWebMailer.setResetPasswordLink(user.getName(), user.getEmail(), recoverUrl); return new ModelAndView("success_recover"); } @RequestMapping(value = "reset_password/{token}", method = RequestMethod.GET) public ModelAndView getResetPassword(@PathVariable String token) { PendingPasswordReset pendingPasswordReset = null; try { pendingPasswordReset = BidirectionalPendingPasswordResetFactory.newInstance(token); } catch (UnirestException e) { e.printStackTrace(); } if (pendingPasswordReset == null) { return null; // some error page } return new ModelAndView("reset_password"); } @RequestMapping(value = "reset_password/{token}", method = RequestMethod.POST) public ModelAndView postResetPassword( @PathVariable String token, @RequestParam(name = "new_password1") String newPassword1, @RequestParam(name = "new_password2") String newPassword2) { if (!newPassword1.equals(newPassword2)) { return null; } PendingPasswordReset pendingPasswordReset = null; try { pendingPasswordReset = BidirectionalPendingPasswordResetFactory.newInstance(token); } catch (UnirestException e) { e.printStackTrace(); } User user = null; try { user = BidirectionalUserFactory.newInstance(pendingPasswordReset.getUsername()); } catch (UnirestException e) { e.printStackTrace(); } try { BidirectionalLoginDataCustomFactory.update(user.getId(), String.valueOf(newPassword1.hashCode())); } catch (UnirestException e) { e.printStackTrace(); } return new ModelAndView("reset_password_success"); } @RequestMapping(value = "/login", method = RequestMethod.POST) public ModelAndView doLogin( HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "username") String username, @RequestParam(name = "password") String password) { User user = null; try { user = BidirectionalUserFactory.newInstance(username); } catch (UnirestException e) { e.printStackTrace(); } String actualPassword = null; // That's not the way it supposed to be try { actualPassword = BidirectionalLoginDataCustomFactory.getPassword(user.getId()); } catch (UnirestException e) { e.printStackTrace(); } if (String.valueOf(password.hashCode()).equals(actualPassword)) { request.getSession().setAttribute("loggedIn", Boolean.TRUE); request.getSession().setAttribute("username", user.getName()); } return new ModelAndView("redirect:/main_menu"); } @RequestMapping(value="/pvp", method = RequestMethod.GET) public ModelAndView getPvpPage(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("username", request.getSession().getAttribute("username")); return modelAndView; } @RequestMapping(value="/main_menu", method = RequestMethod.GET) public String getMainMenuPage(HttpServletRequest request){ String username = (String) request.getSession().getAttribute("username"); if (username == null) { return "error"; } return "main_menu"; } @RequestMapping(value="/chat_room", method = RequestMethod.GET) public String getChatRoomPage(HttpServletRequest request){ String username = (String) request.getSession().getAttribute("username"); if (request.getSession().getAttribute("username").equals("")) { return "error"; } return "chat_room"; } @RequestMapping(value="/add_question", method = RequestMethod.GET) public String getAddQuestionPage(HttpServletRequest request) { if (request.getSession().getAttribute("username").equals("")) { return "error"; } return "add_question"; } @ResponseBody @RequestMapping(value = "/checkUsernameAvailable", method = RequestMethod.POST) public String checkValidUsername(@RequestParam String username) { // JSONObject json = new JSONObject(); // JSONArray jsonArray = new JSONArray(); // String suggestion = dao.checkIfValidUsername(username); // if (suggestion != null) { // try { // json.put("status", "taken"); // json.put("suggestion", suggestion); // } catch (JSONException e) { // e.printStackTrace(); // return json.toString(); // } else { // try { // json.put("status", "ok"); // } catch (JSONException e) { // e.printStackTrace(); // return json.toString(); return null; } @ResponseBody @RequestMapping(value = "/checkPasswordStrength", method = RequestMethod.POST) public String checkPasswordStrength(@RequestParam String password) { // JSONObject json = new JSONObject(); // int strength = dao.checkPasswordStrengthness(password); // try { // json.put("strength", strength); // } catch (JSONException e) { // e.printStackTrace(); // return json.toString(); return null; } @RequestMapping(value = "/validateRegistration", method = RequestMethod.POST) public ModelAndView validateRegistration( @RequestParam(name = "email") String email, @RequestParam(name = "username") String username, @RequestParam(name = "password") String password) { if (email.equals("") || username.equals("") || password.equals("")) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Invalid credentials"); return modelAndView; } FunWebMailer.sendTextRegisterNotification(username, email); try { if (BidirectionalUserFactory.newInstance(username) == null) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Username already taken"); return modelAndView; } } catch (UnirestException e) { e.printStackTrace(); } User user = new User(); user.setName(username); user.setUserRole("user"); user.setEmail(email); user.setLoginType("custom"); user.setLevel(0); user.setHintsLeft(0); user.setGoldLeft(0); user.setAvatarPath("/home"); user.setId(0l); try { BidirectionalUserFactory.persist(user); } catch (UnirestException e) { e.printStackTrace(); ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Error storing the new user"); } try { user = BidirectionalUserFactory.newInstance(username); } catch (UnirestException e) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Error accessing the db service"); e.printStackTrace(); } LoginDataCustom loginDataCustom = new LoginDataCustom(); loginDataCustom.setPassword(String.valueOf(password.hashCode())); loginDataCustom.setId(0l); loginDataCustom.setUserId(user.getId()); try { BidirectionalLoginDataCustomFactory.persist(loginDataCustom); } catch (UnirestException e) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Error accesing the db service"); e.printStackTrace(); } return new ModelAndView("redirect:/"); } @ResponseBody @RequestMapping(value = "/weakestChapter", method = RequestMethod.POST) public String getWeakestChapter() { // JSONObject json = new JSONObject(); // try { // json.put("weakestChapter", dao.weakestChapter((int) loggedInUser.getId())); // } catch (JSONException e) { // e.printStackTrace(); // return json.toString(); return null; } @ResponseBody @RequestMapping(value = "/isRelevant", method = RequestMethod.POST) public String getRelevance(@RequestParam(name ="id") Long id){ // JSONObject json = new JSONObject(); // try{ // json.put("relevance", qDao.isRelevant(id)); // if (qDao.getError() != null) { // json.put("error", "yes"); // json.put("errorMessage", qDao.getError()); // } else { // json.put("error", "no"); // } catch (JSONException e){ // e.printStackTrace(); // return json.toString(); return null; } @RequestMapping(value = "/adminPanel", method = RequestMethod.GET) public ModelAndView getAdminPannel(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } return new ModelAndView("admin"); } @RequestMapping(value = "/logout", method = RequestMethod.GET) public ModelAndView logout(HttpServletRequest request) { request.getSession().removeAttribute("username"); return new ModelAndView("register"); } @ResponseBody @RequestMapping(value="/getUsersList" , method = RequestMethod.POST) public String getUsersList(){ JSONArray jsonArray = new JSONArray(); List<String> users = new ArrayList<String>(); try { users = BidirectionalUserFactory.getAll(); } catch (UnirestException e) { e.printStackTrace(); } for (String user : users) { JSONObject jsonUser = new JSONObject(); try { jsonUser.put("username", user); jsonArray.put(jsonUser); } catch (JSONException e) { e.printStackTrace(); } } return jsonArray.toString(); } @ResponseBody @RequestMapping(value="/banUser" , method = RequestMethod.POST) public String banUser(@RequestParam(name = "username") String username) { User toBan = new User(); toBan.setName(username); System.out.println(toBan.getName()); try { BidirectionalUserFactory.remove(toBan); } catch (UnirestException e) { e.printStackTrace(); } return null; } @ResponseBody @RequestMapping(value = "/updatePassword", method = RequestMethod.POST) public String updatePassword(@RequestParam(name = "newPassword") String newPassword) { // JSONObject json = new JSONObject(); // dao.updateUserPassword(loggedInUser, newPassword); // try { // json.put("status", "success"); // } catch (JSONException e) { // e.printStackTrace(); // return json.toString(); return null; } @ResponseBody @RequestMapping(value = "/checkAlreadyReceived", method = RequestMethod.POST) public String checkAlreadyReceived(@RequestParam(name = "id") String id) { JSONObject json = new JSONObject(); try { json.put("receivedStatus", null); } catch (JSONException e) { e.printStackTrace(); } return null; } @RequestMapping(value = "/arena", method = RequestMethod.GET) public ModelAndView getArena(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } return new ModelAndView("arena"); } @RequestMapping(value = "/quick_chat", method = RequestMethod.GET) public ModelAndView quickChatPage(HttpServletRequest request, HttpServletResponse response) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } ModelAndView modelAndView = new ModelAndView("quick_chat"); modelAndView.addObject("username", username); return modelAndView; } }
package net.fasolato.jfmigrate; import net.fasolato.jfmigrate.builders.Change; import net.fasolato.jfmigrate.builders.Data; import net.fasolato.jfmigrate.internal.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.sql.*; import java.util.*; /** * Main class to manage JFMigrate */ public class JFMigrate { private static Logger log = LogManager.getLogger(JFMigrate.class); private List<String> packages; private SqlDialect dialect; private String schema; /** * Constructor that bootstraps JFMigrate. * * It basically reads a jfmigrate.properties file in the classpath and configures the library (database dialcet, connection string...) */ public JFMigrate() { Properties properties = new Properties(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream stream = loader.getResourceAsStream("jfmigrate.properties"); try { properties.load(stream); String configDialect = properties.getProperty("jfmigrate.db.dialect"); dialect = SqlDialect.H2; if (configDialect.equalsIgnoreCase("h2")) { dialect = SqlDialect.H2; } else if (configDialect.equalsIgnoreCase("sqlserver")) { dialect = SqlDialect.SQL_SERVER; } else if (configDialect.equalsIgnoreCase("pgsql")) { dialect = SqlDialect.PGSQL; } else if (configDialect.equalsIgnoreCase("mysql")) { dialect = SqlDialect.MYSQL; } else if (configDialect.equalsIgnoreCase("oracle")) { dialect = SqlDialect.ORACLE; } else if (configDialect.equalsIgnoreCase("sqlite")) { dialect = SqlDialect.SQLITE; } } catch (IOException e) { log.error(e); throw new JFException("Error reading properties file", e); } packages = new ArrayList<String>(); } /** * Registers a package by name as a source of migration classes * @param pkg The package name */ public void registerPackage(String... pkg) { for(String p: pkg) { packages.add(p); } } /** * Registers a package from a class object as a source of migration classes. * @param clazz The class belonging to the package to use as a source */ public void registerPackage(Class<?>... clazz) { for(Class<?> c : clazz) { packages.add(c.getPackage().getName()); } } private IDialectHelper getDialectHelper() { switch (dialect) { case SQL_SERVER: return new SqlServerDialectHelper(); case H2: return new H2DialectHelper(); case PGSQL: return new PGSqlDialectHelper(); case MYSQL: return new MysqlDialectHelper(schema); case ORACLE: return new OracleDialectHelper(); case SQLITE: return new SqliteDialectHelper(); default: throw new NotImplementedException(); } } private long getDatabaseVersion(IDialectHelper helper, Connection conn) throws SQLException { String versionTableExistence = helper.getDatabaseVersionTableExistenceCommand(); boolean exists = true; ResultSet rs = null; PreparedStatement st = new LoggablePreparedStatement(conn, versionTableExistence); log.info("Executing{}{}", System.lineSeparator(), st); try { rs = st.executeQuery(); if (!rs.next()) { exists = false; } else { if (rs.getInt(1) == 0) { exists = false; } } } catch (SQLSyntaxErrorException oracleException) { if (oracleException.getMessage().startsWith("ORA-00942:")) { exists = false; } else { throw oracleException; } } finally { try { rs.close(); st.close(); } catch(Exception ex) { log.error("Error closing resultset/ststement", ex); } } if (!exists) { createVersionTable(helper, conn); return -1; } String currentVersionCommand = helper.getDatabaseVersionCommand(); long dbVersion = -1; st = new LoggablePreparedStatement(conn, currentVersionCommand); log.info("Executing{}{}", System.lineSeparator(), st); rs = st.executeQuery(); if (rs.next()) { dbVersion = rs.getLong(1); } rs.close(); st.close(); return dbVersion; } private void createVersionTable(IDialectHelper helper, Connection conn) throws SQLException { String createCommand = helper.getVersionTableCreationCommand(); PreparedStatement st = new LoggablePreparedStatement(conn, createCommand); log.info("Executing{}{}", System.lineSeparator(), st); st.execute(); } /** * Method to start an UP migration running against a real database engine. * @throws Exception */ public void migrateUp() throws Exception { migrateUp(-1, null, false); } /** * Method to start an UP migration with a Writer output (to write for example an output file). * @param out The Writer to write the SQL code to * @throws Exception */ public void migrateUp(Writer out) throws Exception { migrateUp(-1, out, false); } /** * Method to start an UP migration with a Writer output (to write for example an output file). * @param out The Writer to write the SQL code to * @param createVersionInfoTable Flag to decide whether to create the migration history table if missing * @throws Exception */ public void migrateUp(Writer out, boolean createVersionInfoTable) throws Exception { migrateUp(-1, out, createVersionInfoTable); } /** * Method to start an UP migration with a Writer output (to write for example an output file). * @param startMigrationNumber Force JFMigrate to start from this migration (the existence of this migration is tested anyway) * @param out The Writer to write the SQL code to * @param createVersionInfoTable Flag to decide whether to create the migration history table if missing * @throws Exception */ public void migrateUp(int startMigrationNumber, Writer out, boolean createVersionInfoTable) throws Exception { IDialectHelper helper = getDialectHelper(); DatabaseHelper dbHelper = new DatabaseHelper(); Connection conn = null; try { conn = dbHelper.getConnection(); conn.setAutoCommit(false); long dbVersion = 0; if (out == null) { dbVersion = getDatabaseVersion(helper, conn); } else if (createVersionInfoTable) { out.write("-- Version table"); out.write(System.lineSeparator()); out.write(System.lineSeparator()); out.write(helper.getVersionTableCreationCommand()); out.write(System.lineSeparator()); out.write(System.lineSeparator()); out.write(" out.write(System.lineSeparator()); out.write(System.lineSeparator()); out.write(System.lineSeparator()); } log.info("Current database version: {}", dbVersion); for (String p : packages) { log.debug("Migrating up from package {}", p); List<JFMigrationClass> migrations = ReflectionHelper.getAllMigrations(p); Collections.sort(migrations, new Comparator<JFMigrationClass>() { public int compare(JFMigrationClass jfMigrationClass, JFMigrationClass t1) { return Long.compare(jfMigrationClass.getMigrationNumber(), t1.getMigrationNumber()); } }); for (JFMigrationClass m : migrations) { if (m.executeForDialect(dialect) && (m.getMigrationNumber() > dbVersion && (startMigrationNumber == -1 || m.getMigrationNumber() >= startMigrationNumber))) { log.debug("Applying migration UP {}({})", m.getMigrationName(), m.getMigrationNumber()); m.up(); String[] scriptVersionCheck = null; if (out != null) { out.write(String.format("-- Migration %s(%s)", m.getMigrationName(), m.getMigrationNumber())); out.write(System.lineSeparator()); out.write(System.lineSeparator()); scriptVersionCheck = helper.getScriptCheckMigrationUpVersionCommand(); if (scriptVersionCheck != null && scriptVersionCheck.length != 0) { out.write(scriptVersionCheck[0].replaceAll("\\?", String.valueOf(m.getMigrationNumber()))); out.write(System.lineSeparator()); } } PreparedStatement st; for (Change c : m.migration.getChanges()) { if (Data.class.isAssignableFrom(c.getClass())) { Data d = (Data) c; for (Pair<String, Object[]> commands : d.getSqlCommand(helper)) { st = new LoggablePreparedStatement(conn, commands.getA()); for (int iv = 0; iv < commands.getB().length; iv++) { st.setObject(iv + 1, commands.getB()[iv]); } log.info("Executing{}{}", System.lineSeparator(), st); if (out == null) { st.execute(); } else { out.write(st.toString().trim()); out.write(System.lineSeparator()); out.write(System.lineSeparator()); } } } else { for (Pair<String, Object[]> commands : c.getSqlCommand(helper)) { st = new LoggablePreparedStatement(conn, commands.getA()); if (commands.getB() != null) { for (int iv = 0; iv < commands.getB().length; iv++) { st.setObject(iv + 1, commands.getB()[iv]); } } log.info("Executing{}{}", System.lineSeparator(), st); if (out == null) { st.execute(); } else { out.write(st.toString().trim()); out.write(System.lineSeparator()); out.write(System.lineSeparator()); } } } } String migrationVersionCommand = helper.getInsertNewVersionCommand(); st = new LoggablePreparedStatement(conn, migrationVersionCommand); st.setLong(1, m.getMigrationNumber()); st.setString(2, m.getMigrationName()); log.info("Executing{}{}", System.lineSeparator(), st); if (out == null) { st.execute(); } else { out.write(st.toString().trim()); out.write(System.lineSeparator()); out.write(System.lineSeparator()); } if (out != null) { if (scriptVersionCheck != null) { out.write(scriptVersionCheck[1]); out.write(System.lineSeparator()); } out.write(" out.write(System.lineSeparator()); out.write(System.lineSeparator()); out.write(System.lineSeparator()); } log.debug("Applied migration {}", m.getClass().getSimpleName()); } else { if(!m.executeForDialect(dialect)) { log.info("Skipping migration {} because DB dialect {} is explicitly skipped", m.getMigrationNumber(), dialect); } else if (m.getMigrationNumber() <= dbVersion) { log.info("Skipping migration {} because DB is newer", m.getMigrationNumber()); } else { log.info("Skipping migration {} because lower than selected start migration number ({})", m.getMigrationNumber(), startMigrationNumber); } } } } if (conn != null) { conn.commit(); } } catch (Exception e) { if (conn != null) { try { conn.rollback(); log.error("Connection rolled back"); } catch (Exception ex) { log.error("Error while rolling back transaction", ex); } } log.error("Error executing query", e); throw e; } finally { try { if (conn != null) { conn.close(); } } catch (Exception ex) { log.error(ex); } } } /** * Method to start an DOWN migration running against a true database engine. JFMigrate starts from the current DB migration and executes DOWN migrations until it reaches targetMigration. * @param targetMigration The migration number where to stop. The initial database state is migration 0. * @throws Exception */ public void migrateDown(int targetMigration) throws Exception { migrateDown(targetMigration, null); } /** * Method to start an DOWN migration with a Writer output (to write for example an output file). JFMigrate starts from the current DB migration and executes DOWN migrations until it reaches targetMigration. * @param targetMigration The migration number where to stop. The initial database state is migration 0. * @param out The Writer to write the SQL code to * @throws Exception */ public void migrateDown(int targetMigration, Writer out) throws Exception { IDialectHelper helper = getDialectHelper(); DatabaseHelper dbHelper = new DatabaseHelper(); Connection conn = null; try { conn = dbHelper.getConnection(); conn.setAutoCommit(false); long dbVersion = Long.MAX_VALUE; if (out == null) { dbVersion = getDatabaseVersion(helper, conn); } log.info("Current database version: {}", dbVersion); if (dbVersion <= 0) { //No migration table or DB is at first migration, nothing to be done return; } for (String p : packages) { log.debug("Migrating down from package {}", p); List<JFMigrationClass> migrations = ReflectionHelper.getAllMigrations(p); Collections.sort(migrations, new Comparator<JFMigrationClass>() { public int compare(JFMigrationClass jfMigrationClass, JFMigrationClass t1) { return -1 * Long.compare(jfMigrationClass.getMigrationNumber(), t1.getMigrationNumber()); } }); for (JFMigrationClass m : migrations) { if (m.executeForDialect(dialect) && (m.getMigrationNumber() <= dbVersion && m.getMigrationNumber() > targetMigration)) { log.debug("Applying migration DOWN {}({})", m.getMigrationName(), m.getMigrationNumber()); m.down(); String[] scriptVersionCheck = null; if (out != null) { out.write(String.format("-- Migration down %s(%s)", m.getMigrationName(), m.getMigrationNumber())); out.write(System.lineSeparator()); out.write(System.lineSeparator()); } scriptVersionCheck = helper.getScriptCheckMigrationDownVersionCommand(); if (out != null && scriptVersionCheck != null) { out.write(scriptVersionCheck[0].replaceAll("\\?", String.valueOf(m.getMigrationNumber()))); out.write(System.lineSeparator()); } PreparedStatement st; if (out == null) { String testVersionSql = helper.getSearchDatabaseVersionCommand(); st = new LoggablePreparedStatement(conn, testVersionSql); st.setLong(1, m.getMigrationNumber()); log.info("Executing{}{}", System.lineSeparator(), st); ResultSet rs = st.executeQuery(); if (!rs.next()) { throw new Exception("Migration " + m.getMigrationNumber() + " not found in table " + JFMigrationConstants.DB_VERSION_TABLE_NAME); } rs.close(); st.close(); } for (Change c : m.migration.getChanges()) { for (Pair<String, Object[]> commands : c.getSqlCommand(helper)) { if (Data.class.isAssignableFrom(c.getClass())) { st = new LoggablePreparedStatement(conn, commands.getA()); if (commands.getB() != null) { for (int i = 0; i < commands.getB().length; i++) { st.setObject(i + 1, commands.getB()[i]); } } log.info("Executing{}{}", System.lineSeparator(), st); if (out == null) { st.execute(); } else { out.write(st.toString().trim()); out.write(System.lineSeparator()); out.write(System.lineSeparator()); } } else { st = new LoggablePreparedStatement(conn, commands.getA()); log.info("Executing{}{}", System.lineSeparator(), st); if (out == null) { st.execute(); } else { out.write(st.toString().trim()); out.write(System.lineSeparator()); out.write(System.lineSeparator()); } } } } String migrationVersionCommand = helper.getDeleteVersionCommand(); st = new LoggablePreparedStatement(conn, migrationVersionCommand); st.setLong(1, m.getMigrationNumber()); log.info("Executing{}{}", System.lineSeparator(), st); if (out == null) { st.execute(); } else { out.write(st.toString().trim()); out.write(System.lineSeparator()); out.write(System.lineSeparator()); } if (out != null) { if (scriptVersionCheck != null) { out.write(scriptVersionCheck[1]); out.write(System.lineSeparator()); } out.write(" out.write(System.lineSeparator()); out.write(System.lineSeparator()); out.write(System.lineSeparator()); } log.debug("Applied migration {}", m.getClass().getSimpleName()); } else { if(!m.executeForDialect(dialect)) { log.info("Skipping migration {} because DB dialect {} is explicitly skipped", m.getMigrationNumber(), dialect); } else if (m.getMigrationNumber() > dbVersion) { log.debug("Skipped migration {}({}) because out of range (db version: {})", m.getMigrationName(), m.getMigrationNumber(), dbVersion, targetMigration); } else { log.debug("Skipped migration {}({}) because out of range (target version: {})", m.getMigrationName(), m.getMigrationNumber(), targetMigration); } } } } if (out == null) { conn.commit(); } } catch (Exception e) { if (conn != null) { try { conn.rollback(); log.error("Connection rolled back"); } catch (Exception ex) { log.error("Error rolling back connection", ex); } } log.error("Error executing query", e); throw e; } finally { try { if (conn != null) { conn.close(); } } catch (Exception ex) { log.error(ex); } } } /** * Retrieves the current schema, if set * @return */ public String getSchema() { return schema; } /** * Sets the database schema to use (if applicable) * @param schema */ public void setSchema(String schema) { this.schema = schema; } }