answer
stringlengths
17
10.2M
package org.jasig.portal; import javax.servlet.*; import javax.servlet.jsp.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.text.*; import java.sql.*; import java.net.*; import com.objectspace.xml.*; import org.jasig.portal.layout.*; import org.jasig.portal.GenericPortalBean; /** * Provides methods associated with subscribing to a channel. * This includes preview, listing all available channels * and placement on a users page. * @author John Laker * @version %I%, %G% */ public class SubscriberBean extends GenericPortalBean{ RdbmServices rdbmService = new RdbmServices (); Connection con = null; public SubscriberBean() { } /** * Retrieves a handle to the channel xml * @param the servlet request object * @return handle to the channel xml */ public IXml getChannelXml (HttpServletRequest req) { IXml channelXml = null; int id = Integer.parseInt(req.getParameter("chan_id")); try { con = rdbmService.getConnection (); Statement stmt = con.createStatement(); String sQuery = "SELECT ID, TITLE, CHANNEL_XML FROM PORTAL_CHANNELS WHERE ID=" + id ; Logger.log (Logger.DEBUG, sQuery); debug(sQuery); ResultSet rs = stmt.executeQuery (sQuery); if (rs.next ()) { String sChannelXml = rs.getString ("CHANNEL_XML"); // Tack on the full path to layout.dtd //int iInsertBefore = sLayoutXml.indexOf (sLayoutDtd); //sChannelXml = sLayoutXml.substring (0, iInsertBefore) + sPathToLayoutDtd + sLayoutXml.substring (iInsertBefore); String xmlFilePackage = "org.jasig.portal.layout"; channelXml = Xml.openDocument (xmlFilePackage, new StringReader (sChannelXml)); } stmt.close (); return channelXml; } catch (Exception e) { Logger.log (Logger.ERROR, e); } finally { rdbmService.releaseConnection (con); } return null; } /** * Returns a channel instance * to be added to user's layout.xml * @param the servlet request object * @return IChannel */ public org.jasig.portal.layout.IChannel getChannel(HttpServletRequest req) { IXml channelXml = getChannelXml (req); org.jasig.portal.layout.IChannel channel = (org.jasig.portal.layout.IChannel) channelXml.getRoot (); return channel; } /** * Method for getting Channel Name * @param the servlet request object * @return String the channel name */ public String getChannelName(HttpServletRequest req) { LayoutBean layoutbean = new LayoutBean(); org.jasig.portal.IChannel ch = layoutbean.getChannelInstance(getChannel(req)); return ch.getName(); } /** * displays a preview of the channel * for the user to see before subscribing * @param the servlet request object */ public void previewChannel(HttpServletRequest req, HttpServletResponse res, JspWriter out) { try{ LayoutBean layoutbean = new LayoutBean(); org.jasig.portal.IChannel ch = layoutbean.getChannelInstance(getChannel(req)); out.println ("<table border=0 cellpadding=1 cellspacing=4 width=100%>"); out.println (" <tr>"); out.println (" <td bgcolor=cccccc>"); // Channel heading IXml layoutXml = layoutbean.getLayoutXml (req, layoutbean.getUserName (req)); ILayout layout = (ILayout) layoutXml.getRoot (); out.println (" <table border=0 cellpadding=0 cellspacing=0 width=100% bgcolor=" + layout.getAttribute ("channelHeadingColor") + ">"); out.println (" <tr>"); out.println (" <td>"); out.println (" <font face=arial color=#000000><b>&nbsp;" + ch.getName() + "</b></font>"); out.println (" </td>"); out.println (" <td nowrap valign=center align=right>"); out.println (" &nbsp;"); // Channel control buttons if (ch.isMinimizable ()) out.println ("<img border=0 width=\"18\" height=\"15\" src=\"images/minimize.gif\" alt=\"Minimize\">"); if (ch.isDetachable ()) out.println ("<img border=0 width=\"18\" height=\"15\" src=\"images/detach.gif\" alt=\"Detach\">"); if (ch.isRemovable ()) out.println ("<img border=0 width=\"18\" height=\"15\" src=\"images/remove.gif\" alt=\"Remove\">"); if (ch.isEditable ()) out.println ("<img border=0 width=\"28\" height=\"15\" src=\"images/edit.gif\" alt=\"Edit\">"); if (ch.hasHelp ()) out.println ("<img border=0 width=\"18\" height=\"15\" src=\"images/help.gif\" alt=\"Help\">"); out.println (" &nbsp;"); out.println (" </td>"); out.println (" </tr>"); out.println (" </table>"); // Channel body out.println (" <table border=0 cellpadding=0 cellspacing=0 width=100%>"); out.println (" <tr>"); out.println (" <td bgcolor=#ffffff>"); out.println (" <table border=0 cellpadding=3 cellspacing=0 width=100% bgcolor=#ffffff>"); out.println (" <tr>"); out.println (" <td valign=top>"); // Render channel contents ch.render (req, res, out); out.println (" </td>"); out.println (" </tr>"); out.println (" </table>"); out.println (" </td>"); out.println (" </tr>"); out.println (" </table>"); out.println (" </td>"); out.println (" </tr>"); out.println ("</table>"); } catch (Exception e){ Logger.log (Logger.ERROR, e); } } /** * Retrieves all available channels * @param the servlet request object * @return ResultSet */ public ResultSet getChannels (HttpServletRequest req) { ResultSet rs = null; Statement stmt = null; try { con = rdbmService.getConnection (); stmt = con.createStatement(); String sQuery = "SELECT ID, TITLE FROM PORTAL_CHANNELS" ; Logger.log (Logger.DEBUG, sQuery); debug(sQuery); rs = stmt.executeQuery (sQuery); return rs; } catch (Exception e) { Logger.log (Logger.ERROR, e); } return null; } /** * method for closing subscribe database connection */ public void close() { rdbmService.releaseConnection(con); } }
package se.z_app.stb; import java.net.InetAddress; public class STB { }
package baum; import java.util.HashSet; import org.apache.lucene.document.Document; /** * * @author Jan Hofmeier * * @param <E> Enum das moegliche Attribute enthaelt * * Wrapper-Klasse des Baums, ermglicht das veraendern und anlegen aus einem anderen Package heraus */ public class Gaertner<E extends Enum<E> & Ordner> { final Knoten<E> root; public Gaertner(BaumStruktur<E> struktur) { if(struktur.statisch) root=new StatischerKnoten<E>(struktur.name, struktur); else root=new VariablerKnoten<E>(struktur.name, struktur); } public boolean add(Document doc) { return root.add(doc); } public void remove(Document doc) { root.remove(doc); } public Knoten<E> gebeWurzel() { return root; } public boolean contains(Document doc) { return root.contains(doc); } public String[] getFileStrings() { HashSet<String> set=new HashSet<String>(); gebeWurzel().getFileStrings(set); String[] a=new String[set.size()]; return set.toArray(a); } }
package de.naoth.rc; import de.naoth.rc.core.dialog.Dialog; import bibliothek.gui.DockUI; import bibliothek.gui.dock.util.laf.Nimbus6u10; import de.naoth.rc.components.preferences.PreferencesDialog; import de.naoth.rc.core.server.ConnectionManager; import de.naoth.rc.core.server.ConnectionStatusEvent; import de.naoth.rc.core.server.ConnectionStatusListener; import de.naoth.rc.core.server.MessageServer; import de.naoth.rc.statusbar.StatusbarPluginImpl; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.*; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Field; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Properties; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.PluginLoaded; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.base.util.uri.ClassURI; /** * * @author thomas */ @PluginImplementation public class RobotControlImpl extends javax.swing.JFrame implements ByteRateUpdateHandler, RobotControl { private static final String USER_CONFIG_DIR = System.getProperty("user.home") + "/.naoth/robotcontrol/"; private final File userLayoutFile = new File(USER_CONFIG_DIR, "layout_df1.1.1.xml"); private final File userConfigFile = new File(USER_CONFIG_DIR, "config"); private final MessageServer messageServer; private final Properties config = new Properties(); private final PreferencesDialog preferencesDialog; private final ConnectionManager connectionManager; private final DialogRegistry dialogRegistry; // remember the window position and size to restore it later private Rectangle defaultWindowBounds = new Rectangle(); private static final Logger logger = Logger.getLogger(RobotControlImpl.class.getName()); private static Logger getLogger() { return logger; } private final GridBagConstraints statusPanelPluginsConstraints = new GridBagConstraints(); private final String RC_TITLE = ""; // HACK: set the path to the native libs static { // load the logger properties InputStream stream = RobotControlImpl.class.getResourceAsStream("logging.properties"); try { LogManager.getLogManager().readConfiguration(stream); } catch (IOException e) { e.printStackTrace(); } try { // we need an absolute path to import native libs // in netbeans we can use the relative execution path File bin = new File("./bin"); if (!bin.isDirectory()) { // with a jar file, we need to determine the correct path relative to the jar file File jar = new File(RobotControlImpl.class.getProtectionDomain().getCodeSource().getLocation().toURI()); // ../bin bin = new File(jar.getParentFile().getParentFile(), "bin"); } String arch = System.getProperty("os.arch").toLowerCase(); String name = System.getProperty("os.name").toLowerCase(); if("linux".equals(name)) { if("amd64".equals(arch)) { addLibraryPath(bin.getAbsolutePath() + "/linux64"); } else { addLibraryPath(bin.getAbsolutePath() + "/linux32"); } } else { if("amd64".equals(arch)) { addLibraryPath(bin.getAbsolutePath() + "/win64"); } else { addLibraryPath(bin.getAbsolutePath() + "/win32"); } addLibraryPath(bin.getAbsolutePath() + "/macos"); } System.getProperties().list(System.out); } catch (Throwable ex) { Logger.getLogger(RobotControlImpl.class.getName()).log(Level.SEVERE, null, ex); } } public static void addLibraryPath(String pathToAdd) throws Throwable { // Define black magic: IMPL_LOOKUP is "trusted" and can access prvae variables. final Lookup original = MethodHandles.lookup(); final Field internal = Lookup.class.getDeclaredField("IMPL_LOOKUP"); internal.setAccessible(true); final Lookup trusted = (Lookup) internal.get(original); // Invoke black magic. Get access to the private field usr_paths MethodHandle set = trusted.findStaticSetter(ClassLoader.class, "usr_paths", String[].class); MethodHandle get = trusted.findStaticGetter(ClassLoader.class, "usr_paths", String[].class); //get array of paths final String[] paths = (String[]) get.invoke(); //check if the path to add is already present for (String path : paths) { if (path.equals(pathToAdd)) { return; } } //add the new path final String[] newPaths = Arrays.copyOf(paths, paths.length + 1); newPaths[newPaths.length - 1] = pathToAdd; set.invoke(newPaths); } /** * Creates new form RobotControlGUI */ public RobotControlImpl() { splashScreenMessage("Welcome to RobotControl"); // load the configuration readConfigFromFile(); try { //UIManager.setLookAndFeel(new PlasticXPLookAndFeel()); UIManager.setLookAndFeel(new CustomNimbusLookAndFeel(RobotControlImpl.this)); // set explicitely the Nimbus colors to be used DockUI.getDefaultDockUI().registerColors("de.naoth.rc.CustomNimbusLookAndFeel", new Nimbus6u10()); } catch(UnsupportedLookAndFeelException ex) { getLogger().log(Level.SEVERE, null, ex); } // icon Image icon = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource("res/RobotControlLogo128.png")); setIconImage(icon); initComponents(); // restore the bounds and the state of the frame from the config defaultWindowBounds = getBounds(); defaultWindowBounds.x = readValueFromConfig("frame.position.x", defaultWindowBounds.x); defaultWindowBounds.y = readValueFromConfig("frame.position.y", defaultWindowBounds.y); defaultWindowBounds.width = readValueFromConfig("frame.width", defaultWindowBounds.width); defaultWindowBounds.height = readValueFromConfig("frame.height", defaultWindowBounds.height); int extendedstate = readValueFromConfig("frame.extendedstate", getExtendedState()); setBounds(defaultWindowBounds); setExtendedState(extendedstate); // remember the bounds of the frame when not maximized this.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent event) { if ((getExtendedState() & JFrame.MAXIMIZED_BOTH) != JFrame.MAXIMIZED_BOTH) { defaultWindowBounds = getBounds(); } } }); // set up a list of all dialogs this.dialogRegistry = new DialogRegistry(this, this.mainMenuBar, this.dialogFastAccessPanel); // initialize the message server this.messageServer = new MessageServer(); this.messageServer.addConnectionStatusListener(new ConnectionStatusListener() { @Override public void connected(ConnectionStatusEvent event) { disconnectMenuItem.setEnabled(true); connectMenuItem.setEnabled(false); } @Override public void disconnected(ConnectionStatusEvent event) { disconnectMenuItem.setEnabled(false); connectMenuItem.setEnabled(true); if(event.getMessage() != null) { connectionManager.showConnectionDialog(event.getMessage()); } } }); this.connectionManager = new ConnectionManager(this, this.messageServer, this.getConfig()); this.disconnectMenuItem.setEnabled(false); // preference dialog this.preferencesDialog = new PreferencesDialog(this, this.getConfig()); this.preferencesDialog.setLocationRelativeTo(this); // set the constraints for the statusbar plugins statusPanelPluginsConstraints.fill = GridBagConstraints.VERTICAL; statusPanelPluginsConstraints.ipadx = 5; // fast dialog access dialogFastAccess.setLocationRelativeTo(this); dialogFastAccess.getRootPane().registerKeyboardAction( (e) -> {dialogFastAccess.setVisible(false); dialogFastAccessPanel.close(); }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW ); // close fast dialog access when RobotControll is in the background dialogFastAccess.addWindowFocusListener(new WindowAdapter() { @Override public void windowLostFocus(WindowEvent e) { dialogFastAccess.setVisible(false); dialogFastAccessPanel.close(); } }); // make fast dialog access visible DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor( (e) -> { if(e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_F && e.getModifiers() == InputEvent.ALT_MASK) { dialogFastAccess.setContentPane(dialogFastAccessPanel); dialogFastAccess.pack(); dialogFastAccess.setLocationRelativeTo(this); dialogFastAccess.setVisible(true); return true; } return false; }); // read & set the userdefined dialog configurations setMenuDialogConfiguration(); }//end constructor private int readValueFromConfig(String key, int default_value) { try { String value = getConfig().getProperty(key); if(value != null) { return Integer.parseInt(value); } } catch(NumberFormatException e){} return default_value; } private void splashScreenMessage(String message) { final SplashScreen splash = SplashScreen.getSplashScreen(); if(splash == null) { return; } Graphics2D g = splash.createGraphics(); if(g == null) { return; } int x = 120; int y = 140; g.setComposite(AlphaComposite.Clear); g.fillRect(x-10,y-10,290,100); g.setPaintMode(); g.setColor(Color.BLACK); g.drawString(message, x, y); splash.update(); } @PluginLoaded public void registerDialog(final Dialog dialog) { splashScreenMessage("Loading dialog " + dialog.getDisplayName() + "..."); this.dialogRegistry.registerDialog(dialog); } @Override public boolean checkConnected() { if(enforceConnection.isSelected() && !messageServer.isConnected()) { // NOTE: this call will block until the dialog is closed //connectionDialog.setVisible(true); this.connectionManager.showConnectionDialog(); return messageServer.isConnected(); } else { return true; } }//end checkConnected /** * Reads all user-defined dialog configurations and creates appropiate menu items. */ private void setMenuDialogConfiguration() { String suffix = "_" + userLayoutFile.getName(); Arrays.asList(userLayoutFile.getParentFile().listFiles((dir, name) -> { return name.endsWith(suffix); })).forEach((f) -> { String name = f.getName().substring(0, f.getName().length()-suffix.length()); createDialogConfigMenuItem(name); }); } /** * Returns the user dialog configuration file for the given configuration name. * * @param configName the name of the dialog configuration * @return the File object of this dialog configuraiton */ private File createUserDialogConfigFile(String configName) { return new File(userLayoutFile.getParent() + "/" + configName + "_" + userLayoutFile.getName()); } /** * Creates a new dialog configuration menu item and adds it to the restore menu. * * @param name the name of the dialog configuration item */ private void createDialogConfigMenuItem(String name) { JMenuItem item = new JMenuItem(name); item.setToolTipText("<html>Restores this dialog layout.<br>Use <i>Ctrl+Click</i> to delete this dialog layout.</html>"); item.addActionListener((e) -> { JMenuItem source = (JMenuItem) e.getSource(); if((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { // delete requested if(JOptionPane.showConfirmDialog(this, "Do you want to remove the dialog layout '"+name+"'?", "Remove dialog layout", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if(createUserDialogConfigFile(name).delete()) { layout.remove(source); } } } else { // restore dialog configuration File f = createUserDialogConfigFile(source.getText()); if(f.isFile()) { try { dialogRegistry.loadFromFile(f); } catch (IOException ex) { Logger.getLogger(RobotControlImpl.class.getName()).log(Level.SEVERE, null, ex); } } else { JOptionPane.showMessageDialog(this, "The '"+source.getText()+"' dialog layout file doesn't exists!?", "Missing layout file", JOptionPane.ERROR_MESSAGE); } } }); layout.add(item); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; dialogFastAccess = new javax.swing.JDialog(); dialogFastAccessPanel = new de.naoth.rc.DialogFastAccessPanel(); statusPanel = new javax.swing.JPanel(); btManager = new javax.swing.JButton(); lblReceivedBytesS = new javax.swing.JLabel(); jSeparator4 = new javax.swing.JSeparator(); lblSentBytesS = new javax.swing.JLabel(); jSeparator5 = new javax.swing.JSeparator(); lblFramesS = new javax.swing.JLabel(); statusPanelPlugins = new javax.swing.JPanel(); statusPanelSpacer = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0)); mainMenuBar = new de.naoth.rc.MainMenuBar(); mainControlMenu = new javax.swing.JMenu(); connectMenuItem = new javax.swing.JMenuItem(); disconnectMenuItem = new javax.swing.JMenuItem(); enforceConnection = new javax.swing.JCheckBoxMenuItem(); layout = new javax.swing.JMenu(); resetLayoutMenuItem = new javax.swing.JMenuItem(); miSaveDialogConfig = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JPopupMenu.Separator(); preferences = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JSeparator(); exitMenuItem = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); aboutMenuItem = new javax.swing.JMenuItem(); dialogFastAccess.setAlwaysOnTop(true); dialogFastAccess.setLocationByPlatform(true); dialogFastAccess.setModal(true); dialogFastAccess.setName("dialogFastAccessDialog"); // NOI18N dialogFastAccess.setUndecorated(true); dialogFastAccess.setPreferredSize(new java.awt.Dimension(600, 300)); dialogFastAccess.getContentPane().add(dialogFastAccessPanel, java.awt.BorderLayout.CENTER); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("RobotControl for NAO v2019"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); statusPanel.setBackground(java.awt.Color.lightGray); statusPanel.setPreferredSize(new java.awt.Dimension(966, 25)); btManager.setText("Running Manager btManager.setToolTipText("Shows the number of currently registered Manager"); btManager.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btManagerActionPerformed(evt); } }); lblReceivedBytesS.setText("Received (byte/s): "); jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL); lblSentBytesS.setText("Sent (byte/s): "); jSeparator5.setOrientation(javax.swing.SwingConstants.VERTICAL); lblFramesS.setText("Update Loop (frame/s):"); statusPanelPlugins.setFocusable(false); statusPanelPlugins.setMaximumSize(new java.awt.Dimension(32767, 24)); statusPanelPlugins.setMinimumSize(new java.awt.Dimension(0, 24)); statusPanelPlugins.setOpaque(false); statusPanelPlugins.setPreferredSize(new java.awt.Dimension(100, 24)); statusPanelPlugins.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; statusPanelPlugins.add(statusPanelSpacer, gridBagConstraints); javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel); statusPanel.setLayout(statusPanelLayout); statusPanelLayout.setHorizontalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(btManager, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblReceivedBytesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 1, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblSentBytesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblFramesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(63, 63, 63) .addComponent(statusPanelPlugins, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)) ); statusPanelLayout.setVerticalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btManager, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblReceivedBytesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSeparator5) .addComponent(lblSentBytesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblFramesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(statusPanelPlugins, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); getContentPane().add(statusPanel, java.awt.BorderLayout.PAGE_END); mainControlMenu.setMnemonic('R'); mainControlMenu.setText("Main"); connectMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, java.awt.event.InputEvent.CTRL_MASK)); connectMenuItem.setMnemonic('c'); connectMenuItem.setText("Connect"); connectMenuItem.setToolTipText("Connect to robot"); connectMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { connectMenuItemActionPerformed(evt); } }); mainControlMenu.add(connectMenuItem); disconnectMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK)); disconnectMenuItem.setMnemonic('d'); disconnectMenuItem.setText("Disconnect"); disconnectMenuItem.setToolTipText("Disconnect from robot"); disconnectMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { disconnectMenuItemActionPerformed(evt); } }); mainControlMenu.add(disconnectMenuItem); enforceConnection.setSelected(true); enforceConnection.setText("Enforce Connection"); enforceConnection.setToolTipText("Make sure that RobotControl is connected to a robot when dialogs try to receive data"); mainControlMenu.add(enforceConnection); layout.setText("Layout"); resetLayoutMenuItem.setText("Reset layout"); resetLayoutMenuItem.setToolTipText("Resets all layout information"); resetLayoutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { resetLayoutMenuItemActionPerformed(evt); } }); layout.add(resetLayoutMenuItem); miSaveDialogConfig.setText("Save dialog layout"); miSaveDialogConfig.setToolTipText("Saves the current active dialog configuration."); miSaveDialogConfig.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { miSaveDialogConfigActionPerformed(evt); } }); layout.add(miSaveDialogConfig); layout.add(jSeparator2); mainControlMenu.add(layout); preferences.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); preferences.setText("Preferences"); preferences.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { preferencesActionPerformed(evt); } }); mainControlMenu.add(preferences); mainControlMenu.add(jSeparator1); exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK)); exitMenuItem.setMnemonic('e'); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); mainControlMenu.add(exitMenuItem); mainMenuBar.add(mainControlMenu); helpMenu.setMnemonic('h'); helpMenu.setText("Help"); aboutMenuItem.setMnemonic('a'); aboutMenuItem.setText("About"); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutMenuItemActionPerformed(evt); } }); helpMenu.add(aboutMenuItem); helpMenu.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); mainMenuBar.add(javax.swing.Box.createHorizontalGlue()); mainMenuBar.add(helpMenu); setJMenuBar(mainMenuBar); setSize(new java.awt.Dimension(974, 626)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void connectMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_connectMenuItemActionPerformed {//GEN-HEADEREND:event_connectMenuItemActionPerformed connectionManager.showConnectionDialog(); }//GEN-LAST:event_connectMenuItemActionPerformed private void disconnectMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_disconnectMenuItemActionPerformed {//GEN-HEADEREND:event_disconnectMenuItemActionPerformed messageServer.disconnect(); }//GEN-LAST:event_disconnectMenuItemActionPerformed private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_exitMenuItemActionPerformed {//GEN-HEADEREND:event_exitMenuItemActionPerformed beforeClose(); System.exit(0); }//GEN-LAST:event_exitMenuItemActionPerformed private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_aboutMenuItemActionPerformed {//GEN-HEADEREND:event_aboutMenuItemActionPerformed AboutDialog dlg = new AboutDialog(this, true); dlg.setLocationRelativeTo(this); dlg.setVisible(true); }//GEN-LAST:event_aboutMenuItemActionPerformed private void resetLayoutMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_resetLayoutMenuItemActionPerformed {//GEN-HEADEREND:event_resetLayoutMenuItemActionPerformed this.dialogRegistry.setDefaultLayout(); }//GEN-LAST:event_resetLayoutMenuItemActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt)//GEN-FIRST:event_formWindowClosing {//GEN-HEADEREND:event_formWindowClosing beforeClose(); }//GEN-LAST:event_formWindowClosing private void preferencesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_preferencesActionPerformed preferencesDialog.setVisible(true); }//GEN-LAST:event_preferencesActionPerformed private void miSaveDialogConfigActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSaveDialogConfigActionPerformed // Ask for a name for this dialog configuration String inputName = JOptionPane.showInputDialog("Set a name for the current dialog layout"); // ignore canceled inputs if(inputName == null) { return; } // replace "invalid" characters String name = inputName.trim().replaceAll("[^A-Za-z0-9_-]", ""); // ignore empty inputs if(name.isEmpty()) { return; } // create layout file File f = createUserDialogConfigFile(name); // if configuration name already exists - ask to overwrite if(f.isFile() && JOptionPane.showConfirmDialog(this, "This dialog layout name already exists. Overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { // don't overwrite! return; } // save configuration try { boolean exists = f.isFile(); dialogRegistry.saveToFile(f); // if this configuration already exists, don't create a new menu entry! if(!exists) { createDialogConfigMenuItem(name); } } catch (IOException ex) { Logger.getLogger(RobotControlImpl.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_miSaveDialogConfigActionPerformed private void btManagerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btManagerActionPerformed TaskManager taskManager = new TaskManager(this, true); String str = "Currently registeres Manager:\n\n"; for(int i = 0; i < messageServer.getListeners().size(); i++) { String name = messageServer.getListeners().get(i).getClass().getSimpleName(); taskManager.addTask(name, "0", null); str += messageServer.getListeners().get(i).getClass().getSimpleName() + "\n"; }//end for str += "\n"; //taskManager.setVisible(true); JOptionPane.showMessageDialog(this, str); }//GEN-LAST:event_btManagerActionPerformed @Override public MessageServer getMessageServer() { return messageServer; } /** * @param args the command line arguments */ public static void main(final String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { // create the configlocation is not existing File configDir = new File(USER_CONFIG_DIR); if(!(configDir.exists() && configDir.isDirectory()) && !configDir.mkdirs()) { getLogger().log(Level.SEVERE, "Could not create the configuration path: \"{0}\".", USER_CONFIG_DIR); } final JSPFProperties props = new JSPFProperties(); props.setProperty(PluginManager.class, "cache.enabled", "false"); // props.setProperty(PluginManager.class, "cache.mode", "strong"); //optional // props.setProperty(PluginManager.class, "cache.file", configlocation+"robot-control.jspf.cache"); PluginManager pluginManager = PluginManagerFactory.createPluginManager(props); try { // make sure the main frame if loaded first pluginManager.addPluginsFrom(new ClassURI(RobotControlImpl.class).toURI()); File selfFile = new File(RobotControlImpl.class.getProtectionDomain().getCodeSource().getLocation().toURI()); // load all plugins from pluginManager.addPluginsFrom(selfFile.toURI()); // NOTE: this is very slow to search in the whole classpath
import org.apache.tools.ant.Task; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.EnumeratedAttribute; import java.net.InetAddress; public class HostName extends Task { private final static boolean DEBUG = false; private String hostname; // What is this used for? private String domainname; // What is this used for? private String domainName(String hostName) { int dot = hostName.indexOf('.'); if (dot == -1) { return null; } return hostName.substring(dot + 1); } public void execute() throws BuildException { String hostName = null; String domainName = null; InetAddress addr = null; try { addr = InetAddress.getLocalHost(); if (DEBUG) { System.err.println("getLocalHost -> " + addr); } InetAddress[] nameAddr = InetAddress.getAllByName(addr.getHostAddress()); for (int i = 0; i < nameAddr.length; i++) { if (DEBUG) { System.err.println("getByName(getHostaddress)[" + i + "] -> " + nameAddr[i]); } hostName = nameAddr[i].getHostName(); if (DEBUG) { System.err.println("getHostName(--) -> " + hostName); } domainName = domainName(hostName); if (domainName != null) { break; } } } catch (Exception e) { throw new BuildException("Could not find my host name" + e); } if (domainName == null && addr != null) { /* It seems our reverse lookup has failed miserably. * Maybe the direct lookup can help a bit... */ String unchecked = addr.toString(); int slash = unchecked.indexOf('/'); if (slash > 0) { hostName = unchecked.substring(0, slash); domainName = domainName(hostName); } } if (hostName == null) { hostName = "(localhost)"; } if (domainName == null) { domainName = "(none)"; } addProperty("hostname", hostName); addProperty("domainname", domainName); domainname = domainName; hostname = hostName; } private void addProperty(String name, String value) { if (getProject().getUserProperty(name) == null) { getProject().setInheritedProperty(name, value); } else { log("Override ignored for " + name, Project.MSG_VERBOSE); } } public void setHostname(String name) { this.hostname = name; } public void setDomainname(String name) { this.domainname = name; } }
package burp; import java.util.List; import com.google.gson.Gson; public class BFakeScannerForMessage implements IScannerCheck { private EventServer wss; private IBurpExtenderCallbacks callbacks; private Gson gson; public BFakeScannerForMessage(IBurpExtenderCallbacks callbacks, EventServer wss) { this.wss = wss; this.callbacks = callbacks; gson = new Gson(); } //@Override public List<IScanIssue> doPassiveScan(IHttpRequestResponse baseRequestResponse) { BHttpRequestResponse bhttpRequestResponse = BHttpRequestResponseFactory.create(baseRequestResponse, callbacks, callbacks.getHelpers()); wss.sendToAll(gson.toJson(bhttpRequestResponse)); return null; } // @Override public List<IScanIssue> doActiveScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { return null; } // @Override public int consolidateDuplicateIssues(IScanIssue existingIssue, IScanIssue newIssue) { return 0; } }
package ccw; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.ILaunch; import org.eclipse.e4.core.contexts.EclipseContextFactory; import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.e4.core.services.events.IEventBroker; import org.eclipse.e4.ui.workbench.UIEvents; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.FontRegistry; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.resource.StringConverter; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IViewReference; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.ui.texteditor.ChainedPreferenceStore; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import ccw.core.StaticStrings; import ccw.editors.clojure.ClojureEditor; import ccw.editors.clojure.IClojureEditor; import ccw.editors.clojure.scanners.IScanContext; import ccw.launching.LaunchUtils; import ccw.nature.AutomaticNatureAdder; import ccw.preferences.PreferenceConstants; import ccw.repl.REPLView; import ccw.repl.SafeConnection; import ccw.util.ClojureInvoker; import ccw.util.DisplayUtil; import ccw.util.ITracer; import ccw.util.NullTracer; import ccw.util.Tracer; import clojure.lang.Keyword; /** * The activator class controls the plug-in life cycle */ public class CCWPlugin extends AbstractUIPlugin { /** The plug-in ID */ public static final String PLUGIN_ID = "ccw.core"; /** Leiningen project nature */ public static final String LEININGEN_NATURE_ID = "ccw.leiningen.nature"; /** * @param swtKey a key from SWT.COLOR_xxx * @return a system managed color (callers must not dispose * the color themselves) */ public static Color getSystemColor(int swtKey) { return Display.getDefault().getSystemColor(swtKey); } //SHOULD LOG INFO / WARN / ERROR WHEN THE APPROPRIATE FLAGS ARE SET SO THAT ONE DOES NOT HAVE //TO GO FROM ONE FILE TO ANOTHER //ALSO CONSIDER VARIANTS FOR STACKTRACE, //RAW STRING (no format), etc. /** The shared instance */ private static CCWPlugin plugin; private ColorRegistry colorCache; private FontRegistry fontRegistry; private AutomaticNatureAdder synchronizedNatureAdapter; private ITracer tracer = NullTracer.INSTANCE; public static ITracer getTracer() { CCWPlugin plugin = getDefault(); if (plugin != null && plugin.tracer != null) return plugin.tracer; else return NullTracer.INSTANCE; } public void startREPLServer() { try { ClojureInvoker.newInvoker(this, "ccw.core.launch")._("ccw-nrepl-start-if-necessary"); } catch (Exception e) { CCWPlugin.logError("Could not start plugin-hosted REPL server", e); throw new RuntimeException("Could not start plugin-hosted REPL server", e); } } public int getREPLServerPort() { startREPLServer(); return (Integer) ClojureInvoker.newInvoker(this, "ccw.core.launch")._("ccw-nrepl-port"); } public void startEventHandlers() { ClojureInvoker.newInvoker(this, "ccw.core.event-bus")._("start"); } public void startEventSubscription() { ClojureInvoker.newInvoker(this, "ccw.repl.visible-in-all-perspectives")._("start"); } public void startNamespaces() { // ClojureInvoker.newInvoker(this, "ccw.editors.clojure.code-content-assist")._("start"); ClojureInvoker.newInvoker(this, "ccw.editors.clojure.code-context-information")._("start"); ClojureInvoker.newInvoker(this, "ccw.editors.clojure.code-completion-proposal")._("start"); } /** * Record of a found CCW dependency. Only used at plugin startup to * log found dependencies. * @see logDependenciesInformation(final BundleContext context) */ private static class CCWDependency { public final String groupId; public final String artifactId; public final String version; public CCWDependency(String g, String a, String v) { groupId = g; artifactId = a; version = v; } } /** * Record of a found CCW dependency in error. Only used at plugin startup to * log found dependencies. * @see logDependenciesInformation(final BundleContext context) */ private static class CCWDependencyErr { public final URL url; public final Exception exception; public CCWDependencyErr(URL u, Exception e) { url = u; exception = e; } } /** * Method implemented in java so we don't trigger clojure accidentally, * because this method is called really early in the plugin initialization * process */ private final void logDependenciesInformation(final BundleContext context) { // Collect bundle embedded external libraries Enumeration<URL> entries = context.getBundle().findEntries("lib", "pom.properties", true); // Initialize colls for dependencies and dependencies in error // dependencies will be sorted first via groupId, then artifactId TreeSet<CCWDependency> deps = new TreeSet<CCWDependency>(new Comparator<CCWDependency>() { @Override public int compare(CCWDependency d1, CCWDependency d2) { if (d1.groupId.equals(d2.groupId)) { return d1.artifactId.compareTo(d2.artifactId); } else { return d1.groupId.compareTo(d2.groupId); } } }); // errors are collected without specific ordering List<CCWDependencyErr> errs = new ArrayList<CCWDependencyErr>(); // Collect dependencies and dependencies in error, gathering as much // info as possible if (entries != null) { while (entries.hasMoreElements()) { URL entry = entries.nextElement(); Reader r = null; try { r = new InputStreamReader(entry.openStream(), Charset.forName("UTF-8")); Properties p = new Properties(); p.load(r); String groupId = p.getProperty("groupId"); String artifactId = p.getProperty("artifactId"); String version = p.getProperty("version"); CCWDependency d = new CCWDependency(groupId, artifactId, version); deps.add(d); } catch (IOException e) { errs.add(new CCWDependencyErr(entry, e)); } finally { if (r != null) try { r.close(); } catch (IOException e) { /* silently ignore */ } } } } // Create the dependencies report String and log it StringBuilder sb = new StringBuilder(); sb.append("Counterclockwise dependencies:"); final String indent = " "; if (entries != null) { for (CCWDependencyErr err: errs) { logWarning("Exception while trying to find maven information for Counterclockwise dependency " + err.url.toExternalForm(), err.exception); sb.append("\n" + indent); sb.append(err.url.toExternalForm() + ": " + err.exception.getMessage()); } for (CCWDependency d: deps) { String name = (d.groupId.equals(d.artifactId)) ? d.groupId : d.groupId + "/" + d.artifactId; sb.append("\n" + indent); sb.append(String.format("[%s \"%s\"]", name, d.version)); } } else { sb.append(indent + "no entries found in bundle"); } // We do not call CCWPlugin.log() because it would duplicate the log // in .metadata/.log because at the time it's called, it would not find // the trace() machinery already installed plugin.getLog().log(new Status(IStatus.INFO, PLUGIN_ID, sb.toString())); } public CCWPlugin() { } private volatile int bundleState = Bundle.UNINSTALLED; /** * Can code be loaded in the current bundle? * @return True or false. */ public static boolean canLoadCodeInBundle() { CCWPlugin plugin = CCWPlugin.getDefault(); return (plugin != null && plugin.bundleState == Bundle.ACTIVE); } @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; log("CCWPlugin.start(): ENTER"); tracer = new Tracer(context); logDependenciesInformation(context); initInjections(context); context.addBundleListener(new BundleListener() { @Override public void bundleChanged(BundleEvent evt) { if (evt.getBundle() == CCWPlugin.this.getBundle()) { bundleState = evt.getType(); if (evt.getType() == BundleEvent.STARTED) { // We immediately give control back to the OSGi framework application // by starting the code in a new thread new Thread(new Runnable() { @Override public void run() { // Some Eclipse plugins, such as LaunchingResourceManager // call PlatformUI.getWorbench() and checking for null, // even though null is not a valid return value // (instead, an exception is thrown), resulting // in the whole Eclipse to collapse. // Let's protect this code once and for all by ensuring // That the Workbench has been initialized before calling // the initialization code while(!PlatformUI.isWorkbenchRunning()) { try { if (CCWPlugin.this.getBundle().getState()!=Bundle.ACTIVE) return; Thread.sleep(200); } catch (InterruptedException e) { logError("Error while querying for the active bundle", e); } } // The Workbench may not be initialized, causing weird issues e.g. in Kepler // WorkbenchThemeManager.getInstance() in Kepler for instance does // not ensure the instance is created in the UI Thread // Once the Workbench is initialized, WorkbenchThemeManager & all // are ensured to be created, so this removes a bunch of plugin startup // race conditions final IWorkbench workbench = PlatformUI.getWorkbench(); final AtomicBoolean isWorkbenchInitialized = new AtomicBoolean(); while (true) { workbench.getDisplay().syncExec(new Runnable() { @Override public void run() { if (workbench.getActiveWorkbenchWindow() != null) { // we've got an active window, so workbench is initialized! isWorkbenchInitialized.set(true); } }}); if (isWorkbenchInitialized.get()) { break; } else { try { Thread.sleep(50); } catch (InterruptedException e) { logError("Error while trying to Thread.sleep.", e); } } } // Here, the workbench is initialized if (System.getProperty(StaticStrings.CCW_PROPERTY_NREPL_AUTOSTART) != null) { try { startNamespaces(); startREPLServer(); startEventHandlers(); startEventSubscription(); } catch (Exception e) { logError("Error while querying for property: " + StaticStrings.CCW_PROPERTY_NREPL_AUTOSTART, e); } } getNatureAdapter().start(); } }).start(); } } } }); // Adding hover extension listener ClojureInvoker invoker = ClojureInvoker.newInvoker(this, "ccw.editors.clojure.hover-support"); invoker._("add-registry-listener"); invoker._("add-preference-listener"); log("CCWPlugin.start(): EXIT"); } private synchronized AutomaticNatureAdder getNatureAdapter() { if (synchronizedNatureAdapter == null) { synchronizedNatureAdapter = new AutomaticNatureAdder(); } return synchronizedNatureAdapter; } private synchronized void createColorCache() { if (colorCache == null) { colorCache = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry(); } } /** * Must be called from the UI thread only */ public ColorRegistry getColorCache() { if (colorCache == null) { createColorCache(); } return colorCache; } private synchronized void createFontRegistry() { if (fontRegistry == null) { DisplayUtil.syncExec(new Runnable() { public void run() { fontRegistry = new FontRegistry(getWorkbench().getDisplay()); // Forces initializations fontRegistry.getItalic(""); // readOnlyFont fontRegistry.getBold(""); // abstractFont } }); } } private FontRegistry getFontRegistry() { if (fontRegistry == null) { createFontRegistry(); } return fontRegistry; } public final Font getJavaSymbolFont() { return getFontRegistry().getItalic(""); } private IPreferenceStore prefs; /** * Create a preference store combined from the Clojure, the EditorsUI and * the PlatformUI preference stores to inherit all the default text editor * settings from the Eclipse preferences. * * <p>Beware, the combined preference store can only be instanciated from the * UI Thread.</p> * * @return the combined preference store. */ public IPreferenceStore getCombinedPreferenceStore() { if (prefs == null) { prefs = new ChainedPreferenceStore(new IPreferenceStore[] { CCWPlugin.getDefault().getPreferenceStore(), EditorsUI.getPreferenceStore(), PlatformUI.getPreferenceStore()}); } return prefs; } public void stop(BundleContext context) throws Exception { // We don't remove colors when deregistered, because, well, we don't have a // corresponding method on the ColorRegistry instance! // We also don't remove fonts when deregistered stopREPLServer(); this.getNatureAdapter().stop(); plugin = null; super.stop(context); } private void stopREPLServer() { try { ClojureInvoker.newInvoker(this, "ccw.core.launch")._("ccw-nrepl-stop"); } catch (Exception e) { logError("Error while trying to close ccw internal nrepl server", e); } } /** * @return the shared instance */ public static CCWPlugin getDefault() { return plugin; } public static void logError(String msg) { getTracer().trace(TraceOptions.LOG_ERROR, "ERROR - " + msg); plugin.getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, msg)); } public static void logError(String msg, Throwable e) { getTracer().trace(TraceOptions.LOG_ERROR, e, "ERROR - " + msg); plugin.getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, msg, e)); } public static void logError(Throwable e) { getTracer().trace(TraceOptions.LOG_ERROR, e, "ERROR - "); plugin.getLog().log( new Status(IStatus.ERROR, PLUGIN_ID, e.getMessage(), e)); } public static IStatus createErrorStatus(String message, Throwable e) { return new Status(IStatus.ERROR, PLUGIN_ID, message, e); } public static IStatus createErrorStatus(String message) { return new Status(IStatus.ERROR, PLUGIN_ID, message); } public static void logWarning(String msg) { getTracer().trace(TraceOptions.LOG_WARNING, "WARNING - " + msg); plugin.getLog().log(new Status(IStatus.WARNING, PLUGIN_ID, msg)); } public static void logWarning(String msg, Throwable e) { getTracer().trace(TraceOptions.LOG_WARNING, e, "WARNING - " + msg); plugin.getLog().log(new Status(IStatus.WARNING, PLUGIN_ID, msg, e)); } public static void logWarning(Throwable e) { getTracer().trace(TraceOptions.LOG_WARNING, e); plugin.getLog().log( new Status(IStatus.WARNING, PLUGIN_ID, e.getMessage(), e)); } public static void log (String msg) { getTracer().trace(TraceOptions.LOG_INFO, "INFO - " + msg); plugin.getLog().log(new Status(IStatus.INFO, PLUGIN_ID, msg)); } @Override protected void initializeImageRegistry(ImageRegistry reg) { reg.put(NS, ImageDescriptor.createFromURL(getBundle().getEntry("/icons/jdt/package_obj.gif"))); reg.put(PUBLIC_FUNCTION, ImageDescriptor.createFromURL(getBundle().getEntry("/icons/jdt/methpub_obj.gif"))); reg.put(PRIVATE_FUNCTION, ImageDescriptor.createFromURL(getBundle().getEntry("/icons/jdt/methpri_obj.gif"))); reg.put(CLASS, ImageDescriptor.createFromURL(getBundle().getEntry("/icons/jdt/class_obj.gif"))); reg.put(SORT, ImageDescriptor.createFromURL(getBundle().getEntry("/icons/jdt/alphab_sort_co.gif"))); } public static final String NS = "icon.namespace"; public static final String PUBLIC_FUNCTION = "icon.function.public"; public static final String PRIVATE_FUNCTION = "icon.function.private"; public static final String CLASS = "class_obj.gif"; public static final String SORT = "alphab_sort_co.gif"; public static boolean isAutoReloadOnStartupSaveEnabled() { return CCWPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.CCW_GENERAL_AUTO_RELOAD_ON_STARTUP_SAVE); } public static boolean isAutoReloadOnStartupSaveEnabled(ILaunch launch) { return (Boolean.parseBoolean(launch.getAttribute(LaunchUtils.ATTR_IS_AUTO_RELOAD_ENABLED))); } public static REPLView[] getREPLViews() { final ArrayList<REPLView> ret = new ArrayList<REPLView>(5); DisplayUtil.syncExec(new Runnable() { public void run() { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { IWorkbenchPage[] pages = window.getPages(); for (int i = 0; i < pages.length; i++) { IWorkbenchPage page = pages[i]; if (page != null) { for (IViewReference r : page.getViewReferences()) { IViewPart v = r.getView(false); if (REPLView.class.isInstance(v)) { ret.add((REPLView) v); } } } } } } }); return ret.toArray(new REPLView[ret.size()]); } public static REPLView getProjectREPL (final IProject project) { REPLView[] repls = getREPLViews(); for (REPLView replView : repls) { ILaunch launch = replView.getLaunch(); if (launch!=null && !launch.isTerminated()) { String launchProject = LaunchUtils.getProjectName(launch); if (launchProject != null && launchProject.equals(project.getName())) { return replView; } } } return null; } public SafeConnection getProjectREPLSafeConnection (IProject project) { REPLView repl = getProjectREPL(project); return repl == null ? null : repl.getSafeToolingConnection(); } private IScanContext scanContext; public synchronized IScanContext getDefaultScanContext() { if (scanContext == null) { scanContext = new StaticScanContext(); } return scanContext; } /** * @return null if a default color must be used (e.g. System color) */ public static RGB getPreferenceRGB(IPreferenceStore store, String preferenceKey) { String enabledKey = PreferenceConstants.getEnabledPreferenceKey(preferenceKey); if (store.contains(enabledKey)) { return store.getBoolean(PreferenceConstants.getEnabledPreferenceKey(preferenceKey)) ? PreferenceConverter.getColor(store, preferenceKey) : PreferenceConverter.getDefaultColor(store, preferenceKey); } else if (store.contains(preferenceKey)) { if (store.isDefault(preferenceKey)) { return PreferenceConverter.getDefaultColor(store, preferenceKey); } else { return PreferenceConverter.getColor(store, preferenceKey); } } else { return null; } } private static void ensureColorInCache(ColorRegistry registry, String id, RGB rgb) { if (!registry.hasValueFor(id)) { registry.put(id, rgb); } } /** * Not thread safe, but should only be called from the UI Thread, so it's * not really a problem. * @param rgbString The rgb string * @return The <code>Color</code> instance cached for this rgb value, creating * it along the way if required. */ public static Color getColor(String rgbString) { ColorRegistry r = getDefault().getColorCache(); RGB rgb = StringConverter.asRGB(rgbString); ensureColorInCache(r, rgbString, rgb); return r.get(rgbString); } /** * Not thread safe, but should only be called from the UI Thread, so it's * not really a problem. * @param rgb The RGB istance * @return The <code>Color</code> instance cached for this rgb value, creating * it along the way if required. */ public static Color getColor(RGB rgb) { ColorRegistry r = getDefault().getColorCache(); String rgbString = StringConverter.asString(rgb); ensureColorInCache(r, rgbString, rgb); return r.get(rgbString); } public static Color getPreferenceColor(IPreferenceStore store, String preferenceKey) { RGB rgb = getPreferenceRGB(store, preferenceKey); return rgb!=null ? getColor(rgb) : null; } /** * Registers all the editor colors in the ColorRegistry, except the ones declared in plugin.xml, * which are already in the registry. * @param store */ public static void registerEditorColors(IPreferenceStore store) { final ColorRegistry colorCache = getDefault().getColorCache(); for (Keyword token: PreferenceConstants.colorizableTokens) { PreferenceConstants.ColorizableToken tokenStyle = PreferenceConstants.getColorizableToken(store, token); String rgbString = StringConverter.asString(tokenStyle.rgb); ensureColorInCache(colorCache, rgbString, tokenStyle.rgb); } } /** * Return the Active editor or null if there is no focus. * * @return An IEditorPart. */ public static IEditorPart getActiveEditor() { IEditorPart clojureEditor = null; IWorkbenchPage activePage = getDefault().internalGetActivePage(); if (activePage != null) { clojureEditor = activePage.getActiveEditor(); } return clojureEditor; } public static IWorkbenchPage getActivePage() { return getDefault().internalGetActivePage(); } // copied from JavaPlugin private IWorkbenchPage internalGetActivePage() { IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow(); if (window == null) return null; return window.getActivePage(); } /** * Gets an instance of ccw.clojureeditor. * @return */ public static IClojureEditor getClojureEditor() { ClojureEditor clojureEditor = null; // Dirty hack to get the Active Editor if out of focus (while stepping for instance). IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows(); if (windows != null) { for (IWorkbenchWindow window : windows) { IWorkbenchPage[] pages = window.getPages(); for (IWorkbenchPage page : pages) { for (IEditorReference editorRef : page.getEditorReferences()) { if (editorRef.getId().equals(ClojureEditor.ID)) { clojureEditor = (ClojureEditor) editorRef.getEditor(false); if (clojureEditor != null) { break; } } } if (clojureEditor != null) { break; } } } } return clojureEditor; } /** * Called in AbstractUIPlugin in order to initialize application-context instances. */ private void initInjections(BundleContext bundleContext) { IEclipseContext c = EclipseContextFactory.getServiceContext(bundleContext); ClojureInvoker.newInvoker(this, "ccw.editors.clojure.hover-support")._("init-injections", c); } private void cleanInjections() { // Empty for now } public static IEclipseContext getEclipseContext() { return EclipseContextFactory.getServiceContext(CCWPlugin.getDefault().getBundle().getBundleContext()); } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util; import java.util.Iterator; import java.util.List; import java.util.Random; import com.samskivert.util.IntListUtil; /** * Provides miscellaneous utility routines to simplify obtaining * useful random number values and to centralize seeding and proper * care and feeding of the pseudo-random number generator. */ public class RandomUtil { /** The random number generator used by the methods in this class. */ public static final Random rand = new Random(); /** * Returns a pseudorandom, uniformly distributed <code>int</code> * value between 0 (inclusive) and the specified value (exclusive). * * @param high the high value limiting the random number sought. */ public static int getInt (int high) { return rand.nextInt(high); } /** * Returns a pseudorandom, uniformly distributed <code>int</code> * value between <code>high</code> and <code>low</code>, exclusive of each. */ public static int getInt (int high, int low) { if (high - low - 1 <= 0) { throw new IllegalArgumentException( "Invalid range [high=" + high + ", low=" + low + "]"); } return low + 1 + rand.nextInt(high - low - 1); } /** * Returns a pseudorandom, uniformly distributed float value between * 0.0 (inclusive) and the specified value (exclusive). * * @param high the high value limiting the random number sought. */ public static float getFloat (float high) { return rand.nextFloat() * high; } /** * Pick a random index from the array, weighted by the value of the * corresponding array element. * * @param weights an array of positive integers. * @return an index into the array, or -1 if the sum of the weights * is less than 1. * * For example, passing in {1, 0, 3, 4} will return * <table><tr><td>0</td><td>1/8th of the time</td></tr> * <tr><td>1</td><td>never</td></tr> * <tr><td>2</td><td>3/8th of the time</td></tr> * <tr><td>3</td><td>half of the time</td></tr></table> */ public static int getWeightedIndex (int[] weights) { int sum = IntListUtil.sum(weights); if (sum < 1) { return -1; } int pick = getInt(sum); for (int ii=0, nn=weights.length; ii < nn; ii++) { pick -= weights[ii]; if (pick < 0) { return ii; } } // Impossible! Log.logStackTrace(new Throwable()); return 0; } /** * Picks a random object from the supplied array of values. Even * weight is given to all elements of the array. * * @return a randomly selected item or null if the array is null or of * length zero. */ public static Object pickRandom (Object[] values) { return (values == null || values.length == 0) ? null : values[getInt(values.length)]; } /** * Picks a random object from the supplied array of values, not * including the specified skip object as a possible selection * (equality with the skipped object is referential rather than via * {@link Object#equals}). The element to be skipped must exist in the * array exactly once. Even weight is given to all elements of the * array except the skipped element. * * @return a randomly selected item or null if the array is null, of * length zero or contains only the skip item. */ public static Object pickRandom (Object[] values, Object skip) { if (values == null || values.length < 2) { return null; } int index = getInt(values.length-1); for (int ii = 0; ii <= index; ii++) { if (values[ii] == skip) { index++; } } return (index >= values.length) ? null : values[index]; } /** * Picks a random object from the supplied List * * @return a randomly selected item. */ public static Object pickRandom (List values) { int size = values.size(); if (size == 0) { throw new IllegalArgumentException( "Must have at least one element [size=" + size + "]"); } return values.get(getInt(size)); } /** * Picks a random object from the supplied List. The specified skip * object will be skipped when selecting a random value. The skipped * object must exist exactly once in the List. * * @return a randomly selected item. */ public static Object pickRandom (List values, Object skip) { int size = values.size(); if (size < 2) { throw new IllegalArgumentException( "Must have at least two elements [size=" + size + "]"); } int pick = getInt(size - 1); for (int ii = 0; ii < size; ii++) { Object val = values.get(ii); if ((val != skip) && (pick return val; } } return null; } /** * Picks a random object from the supplied iterator (which must * iterate over exactly <code>count</code> objects. * * @return a randomly selected item. * * @exception NoSuchElementException thrown if the iterator provides * fewer than <code>count</code> elements. */ public static Object pickRandom (Iterator iter, int count) { if (count < 1) { throw new IllegalArgumentException( "Must have at least one element [count=" + count + "]"); } Object value = iter.next(); for (int ii = 0, ll = getInt(count); ii < ll; ii++) { value = iter.next(); } return value; } /** * Picks a random object from the supplied iterator (which must * iterate over exactly <code>count</code> objects. The specified skip * object will be skipped when selecting a random value. The skipped * object must exist exactly once in the set of objects returned by * the iterator. * * @return a randomly selected item. * * @exception NoSuchElementException thrown if the iterator provides * fewer than <code>count</code> elements. */ public static Object pickRandom (Iterator iter, int count, Object skip) { if (count < 2) { throw new IllegalArgumentException( "Must have at least two elements [count=" + count + "]"); } int index = getInt(count-1); Object value = null; do { value = iter.next(); if (value == skip) { value = iter.next(); } } while (index return value; } }
package nanomsg.exceptions; public class IOException extends java.io.IOException { protected int errno = -1; public IOException(final String message) { super(message); } public IOException(final String message, final int errno) { super(message); this.errno = errno; } public IOException(Throwable cause) { super(cause); } public int getErrno() { return this.errno; } }
// This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.common.xml; import opennlp.common.util.*; import org.jdom.*; import org.jdom.input.*; import org.jdom.output.*; import java.io.*; import java.util.*; public class NLPDocument extends Document { public static final String WORD_LABEL = "w"; public static final String TOKEN_LABEL = "t"; public static final String SENTENCE_LABEL = "s"; public static final String PARAGRAPH_LABEL = "p"; private Element _root; private int _textLength = 0; /** * Empty arg constructor provided for those who do not want the default * behavior of the constructor which takes a string argument. Creates the * root element "nlpDocument" and nothing else. **/ public NLPDocument () { setRootElement(new Element("nlpDocument")); } /** * Constructor which creates an NLPDocument object from a given text. It * automatically breaks the text into paragraphs and "quasiWords" (chunks * of text separated by white spaces). If this behavior is not desired, * use the empty arg constructor and build up the document from the root * element. * * @param text The text which is to be placed into this NLPDocument and * manipulated by tools which process NLPDocuments. **/ public NLPDocument (String text) { this(); addTextContent(text); } protected void addTextContent (String text) { _textLength = text.length(); Element textEl = new Element("text"); String[] paragraphs, quasiWords; paragraphs = PerlHelp.getParagraphs(text); for (int i=0; i<paragraphs.length; i++) { Element paraEl = new Element(PARAGRAPH_LABEL); Element sentEl = new Element(SENTENCE_LABEL); quasiWords = PerlHelp.splitByWhitespace(paragraphs[i]); for (int j=0; j<quasiWords.length; j++) { Element tokenEl = new Element(TOKEN_LABEL); Element wordEl = new Element(WORD_LABEL); wordEl.setText(quasiWords[j]); tokenEl.addContent(wordEl); sentEl.addContent(tokenEl); } paraEl.addContent(sentEl); textEl.addContent(paraEl); } _root.addContent(textEl); } /** * Sets the root element of this document while maintaining the pointer * which the NLPDocument object keeps to the root Element. **/ public Document setRootElement (Element root) { _root = root; return super.setRootElement(root); } /** * Builds a String[] with each item being a paragraph. **/ public String[] getParagraphs () { List parEls = getParagraphElements(); String[] pars = new String[parEls.size()]; int index = 0; for (Iterator i=parEls.iterator(); i.hasNext();) { StringBuffer sb = new StringBuffer(); String[] sents = getSentences((Element)i.next()); for (int j=0; j<sents.length; j++) sb.append(sents[j]).append(' '); pars[index++] = sb.toString().trim(); } return pars; } /** * Grabs all paragraph elements in this document. **/ public List getParagraphElements () { return XmlUtils.getChildrenNested(_root, PARAGRAPH_LABEL); } /** * Return an iterator over all the paragraph Elements in the document. **/ public Iterator paragraphIterator () { return getParagraphElements().iterator(); } /** * Grabs all sentence elements in this document. **/ public String[] getSentences () { return getSentences(_root); } /** * Builds a String[] with each item being a sentence. **/ public String[] getSentences (Element e) { List sentEls = getSentenceElements(e); String[] sents = new String[sentEls.size()]; int index = 0; for (Iterator i=sentEls.iterator(); i.hasNext();) { String[] words = getWords((Element)i.next()); StringBuffer sent = new StringBuffer(); for (int j=0; j<words.length; j++) sent.append(words[j]).append(' '); sents[index++] = sent.toString().trim(); } return sents; } /** * Grabs all sentence elements below the given element. **/ public List getSentenceElements (Element e) { return XmlUtils.getChildrenNested(e, SENTENCE_LABEL); } /** * Grabs all sentence elements in this document. **/ public List getSentenceElements () { return getSentenceElements(_root); } /** * Return an iterator over the all sentence Elements. **/ public Iterator sentenceIterator () { return getSentenceElements().iterator(); } /** * Return an iterator over the sentence Elements below the given element. **/ public Iterator sentenceIterator (Element e) { return getSentenceElements(e).iterator(); } /** * Grabs all token elements below the given element; **/ public List getTokenElements (Element e) { return XmlUtils.getChildrenNested(e, TOKEN_LABEL); } /** * Grabs all token elements in this document. **/ public List getTokenElements () { return getTokenElements(_root); } /** * Grabs all token elements of the specified type in this document. **/ public List getTokenElementsByType (String type) { List allTokens = getTokenElements(_root); List toksByType = new ArrayList(); for (Iterator allTokIt = allTokens.iterator(); allTokIt.hasNext();) { Element tokEl = (Element)allTokIt.next(); String tokType = tokEl.getAttributeValue("type"); if (tokType != null && tokType.equals(type)) { toksByType.add(tokEl); } } return toksByType; } /** * Return an iterator over the all the token Elements. **/ public Iterator tokenIterator () { return getTokenElements().iterator(); } /** * Return an iterator over the token Elements below the given element. **/ public Iterator tokenIterator (Element e) { return getTokenElements(e).iterator(); } public String[] getWords () { return getWords(_root); } public String[] getWords (Element e) { List wordEls = getWordElements(e); String[] words = new String[wordEls.size()]; int index = 0; for (Iterator i=wordIterator(e); i.hasNext();) { words[index++] = ((Element)i.next()).getText(); } return words; } /** * Grabs all word elements below the given element; **/ public List getWordElements (Element e) { return XmlUtils.getChildrenNested(e, WORD_LABEL); } /** * Grabs all word elements in this document. **/ public List getWordElements () { return getWordElements(_root); } /** * Return an iterator over the word Elements below the given element. **/ public Iterator wordIterator (Element e) { return getWordElements(e).iterator(); } /** * Return an iterator over all the word Elements. **/ public Iterator wordIterator () { return getWordElements().iterator(); } public void join (Element startTok, Element endTok) { Element parentSentence = startTok.getParent(); if (endTok.getParent() != parentSentence) { return; } List childrenOfSentence = parentSentence.getChildren(); List $childrenOfSentence = new ArrayList(); for (ListIterator i=childrenOfSentence.listIterator(); i.hasNext();) { Object $_ = i.next(); if ($_ == startTok) { List tokChildren = startTok.getChildren(); List $tokChildren = new ArrayList(); while (($_ = i.next()) != endTok) { List nextChildren = ((Element)$_).getChildren(); ((Element)$_).removeChildren(); $tokChildren.addAll(nextChildren); } List endChildren = endTok.getChildren(); endTok.removeChildren(); $tokChildren.addAll(endChildren); startTok.removeChildren(); startTok.setChildren($tokChildren); $childrenOfSentence.add(startTok); } else { $childrenOfSentence.add($_); } } parentSentence.removeChildren(); parentSentence.setChildren($childrenOfSentence); } /** * Creates a nicely indented String showing the XML content of this * NLPDocument. **/ public String toXml () { StringWriter sw = new StringWriter(); try { new XMLOutputter(" ", true).output(this, sw); } catch (Exception e) { System.out.println("Unable to print document."); System.out.println(e); } return sw.toString(); } /** * Outputs the normalized text content of this NLPDocument. **/ public String toString () { StringBuffer sb = new StringBuffer(_textLength); List parEls = getParagraphElements(); for (Iterator i=parEls.iterator(); i.hasNext();) { String[] sents = getSentences((Element)i.next()); for (int j=0; j<sents.length; j++) sb.append(sents[j]).append(' '); sb.append("\n\n"); } return sb.toString().trim(); } /** * Create a SENT element for an NLP Document. * * @param sent the string of text associated with this sentence. **/ public static Element createSENT(String sent) { int l = sent.length(); Element sentEl = new Element(SENTENCE_LABEL); if (l>0) { char delim = sent.charAt(l-1); if(delim == '.' || delim == '?' || delim == '!') { sentEl.addContent(createTOK(sent.substring(0,l-1))); sentEl.addContent(createTOK(""+delim)); } else { sentEl.addContent(createTOK(sent)); } } return sentEl; } /** * Create a TOK element for an NLPDocument. * * @param tok the string of text associated with this token. **/ public static Element createTOK(String tok) { return new Element(TOKEN_LABEL).addContent( new Element(WORD_LABEL).setText(tok)); } public static void main (String[] args) { NLPDocument doc = new NLPDocument("Here is a sentence. And this is another one.\n\nThis is a sentence in a new paragraph."); System.out.println(doc.toXml()); System.out.println(doc.toString()); } }
package org.joda.time; import java.io.Serializable; import org.joda.time.convert.DurationConverter; import org.joda.time.convert.ConverterManager; import org.joda.time.format.ISODurationFormat; /** * AbstractDuration provides the common behaviour for duration classes. * <p> * This class should generally not be used directly by API users. The * {@link ReadableDuration} interface should be used when different * kinds of durations are to be referenced. * <p> * AbstractDuration subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public abstract class AbstractDuration implements ReadableDuration, Serializable { /** Serialization version */ private static final long serialVersionUID = -2110953284060001145L; /** * Checks whether the field is supported. */ private static void checkArgument(DurationField field, String name) { if (!field.isSupported()) { throw new IllegalArgumentException ("Duration does not support field \"" + name + '"'); } } /** * Checks whether the field is supported. */ private static void checkSupport(DurationField field, String name) { if (!field.isSupported()) { throw new UnsupportedOperationException ("Duration does not support field \"" + name + '"'); } } /** The duration type that allocates the duration to fields */ private final DurationType iType; /** The total milliseconds, if known */ private long iTotalMillis; /** The milliseoond status, 0=unknown, 1=imprecise, 2=precise */ private int iTotalMillisState; private int iYears; private int iMonths; private int iWeeks; private int iDays; private int iHours; private int iMinutes; private int iSeconds; private int iMillis; /** * Creates a zero length duration of the specified type. * * @param type which set of fields this duration supports, null means millis type */ public AbstractDuration(DurationType type) { super(); type = (type == null ? DurationType.getMillisType() : type); iType = type; // Only call a private method setTotalMillis(type, 0L); } public AbstractDuration(Object duration, DurationType type) { super(); DurationConverter converter = ConverterManager.getInstance().getDurationConverter(duration); type = (type == null ? converter.getDurationType(duration) : type); iType = type; if (type.isPrecise() && converter.isPrecise(duration)) { // Only call a private method setTotalMillis(type, converter.getDurationMillis(duration)); } else if (this instanceof ReadWritableDuration) { converter.setInto((ReadWritableDuration) this, duration); } else { // Only call a private method setDuration(type, new MutableDuration(duration, type)); } } public AbstractDuration(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis, DurationType type) { super(); type = (type == null ? DurationType.getAllType() : type); iType = type; // Only call a private method setDuration(type, years, months, weeks, days, hours, minutes, seconds, millis); } /** * Creates a duration from the given interval endpoints. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @param type which set of fields this duration supports, null means AllType */ public AbstractDuration(long startInstant, long endInstant, DurationType type) { super(); type = (type == null ? DurationType.getAllType() : type); iType = type; // Only call a private method setTotalMillis(type, startInstant, endInstant); } /** * Creates a duration from the given interval endpoints. * * @param startInstant interval start, null means now * @param endInstant interval end, null means now * @param type which set of fields this duration supports, null means AllType */ public AbstractDuration( ReadableInstant startInstant, ReadableInstant endInstant, DurationType type) { super(); type = (type == null ? DurationType.getAllType() : type); if (startInstant == null && endInstant == null) { iType = type; } else { long start = (startInstant == null ? DateTimeUtils.currentTimeMillis() : startInstant.getMillis()); long end = (endInstant == null ? DateTimeUtils.currentTimeMillis() : endInstant.getMillis()); iType = type; // Only call a private method setTotalMillis(type, start, end); } } /** * Creates a duration from the given millisecond duration. If any supported * fields are imprecise, an UnsupportedOperationException is thrown. The * exception to this is when the specified duration is zero. * * @param duration the duration, in milliseconds * @param type which set of fields this duration supports, null means MillisType */ public AbstractDuration(long duration, DurationType type) { super(); type = (type == null ? DurationType.getMillisType() : type); iType = type; setTotalMillis(type, duration); // Only call a private method } /** * Returns the object which defines which fields this duration supports. */ public final DurationType getDurationType() { return iType; } public final long getTotalMillis() { int state = iTotalMillisState; if (state == 0) { state = updateTotalMillis(); } if (state != 2) { throw new IllegalStateException("Duration is imprecise"); } return iTotalMillis; } /** * Is this duration a precise length of time, or descriptive. * <p> * A precise duration could include millis, seconds, minutes or hours. * However, days, weeks, months and years can vary in length, resulting in * an imprecise duration. * <p> * An imprecise duration can be made precise by pairing it with a * date in a {@link ReadableInterval}. * * @return true if the duration is precise */ public final boolean isPrecise() { int state = iTotalMillisState; if (state == 0) { state = updateTotalMillis(); } return state == 2; } /** * Walks through the field values, determining total millis and whether * this duration is precise. * * @return new state */ private int updateTotalMillis() { final DurationType type = iType; boolean isPrecise = true; long totalMillis = 0; DurationField field; int value; // used to lock fields against threading issues value = iYears; if (value != 0) { field = type.years(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } value = iMonths; if (value != 0) { field = type.months(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } value = iWeeks; if (value != 0) { field = type.weeks(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } value = iDays; if (value != 0) { field = type.days(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } value = iHours; if (value != 0) { field = type.hours(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } value = iMinutes; if (value != 0) { field = type.minutes(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } value = iSeconds; if (value != 0) { field = type.seconds(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } value = iMillis; if (value != 0) { field = type.millis(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if (isPrecise) { iTotalMillis = totalMillis; return iTotalMillisState = 2; } else { iTotalMillis = totalMillis; return iTotalMillisState = 1; } } /** * Adds this duration to the given instant, returning a new value. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scalar of minus one. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add the * duration to * @param scalar the number of times to add the duration, negative to subtract * @return milliseconds value plus this duration times scalar * @throws ArithmeticException if the result of the calculation is too large */ public final long addTo(long instant, int scalar) { return addTo(instant, scalar, null); } /** * Adds this duration to the given instant, returning a new value. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scalar of minus one. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add the * duration to * @param scalar the number of times to add the duration, negative to subtract * @param chrono override the duration's chronology, unless null is passed in * @return milliseconds value plus this duration times scalar * @throws ArithmeticException if the result of the calculation is too large */ public final long addTo(long instant, int scalar, Chronology chrono) { if (isPrecise()) { return instant += getTotalMillis() * scalar; } DurationType type = iType; if (chrono != null) { type = type.withChronology(chrono); } long value; // used to lock fields against threading issues value = scaleValue(iYears, scalar); if (value != 0) { instant = type.years().add(instant, value); } value = scaleValue(iMonths, scalar); if (value != 0) { instant = type.months().add(instant, value); } value = scaleValue(iWeeks, scalar); if (value != 0) { instant = type.weeks().add(instant, value); } value = scaleValue(iDays, scalar); if (value != 0) { instant = type.days().add(instant, value); } value = scaleValue(iHours, scalar); if (value != 0) { instant = type.hours().add(instant, value); } value = scaleValue(iMinutes, scalar); if (value != 0) { instant = type.minutes().add(instant, value); } value = scaleValue(iSeconds, scalar); if (value != 0) { instant = type.seconds().add(instant, value); } value = scaleValue(iMillis, scalar); if (value != 0) { instant = type.millis().add(instant, value); } return instant; } /** * Convert the scalar to a multiple efficiently. * * @param value the value * @param scalar the scalar * @return the converted value */ private static long scaleValue(int value, int scalar) { long val = value; // use long to avoid truncation switch (scalar) { case -1: return -val; case 0: return 0; case 1: return val; default: return val * scalar; } } /** * Adds this duration to the given instant, returning a new Instant. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scalar of minus one. * * @param instant the instant to add the duration to, null means now * @param scalar the number of times to add the duration, negative to subtract * @return instant with the original value plus this duration times scalar * @throws ArithmeticException if the result of the calculation is too large */ public final Instant addTo(ReadableInstant instant, int scalar) { if (instant == null) { return new Instant(addTo(DateTimeUtils.currentTimeMillis(), scalar)); } return new Instant(addTo(instant.getMillis(), scalar)); } public final void addInto(ReadWritableInstant instant, int scalar) { if (instant == null) { throw new IllegalArgumentException("The instant must not be null"); } instant.setMillis(addTo(instant.getMillis(), scalar)); } /** * Gets the years field part of the duration. * * @return the number of years in the duration, zero if unsupported */ public final int getYears() { return iYears; } /** * Gets the months field part of the duration. * * @return the number of months in the duration, zero if unsupported */ public final int getMonths() { return iMonths; } /** * Gets the weeks field part of the duration. * * @return the number of weeks in the duration, zero if unsupported */ public final int getWeeks() { return iWeeks; } /** * Gets the days field part of the duration. * * @return the number of days in the duration, zero if unsupported */ public final int getDays() { return iDays; } /** * Gets the hours field part of the duration. * * @return the number of hours in the duration, zero if unsupported */ public final int getHours() { return iHours; } /** * Gets the minutes field part of the duration. * * @return the number of minutes in the duration, zero if unsupported */ public final int getMinutes() { return iMinutes; } /** * Gets the seconds field part of the duration. * * @return the number of seconds in the duration, zero if unsupported */ public final int getSeconds() { return iSeconds; } /** * Gets the millis field part of the duration. * * @return the number of millis in the duration, zero if unsupported */ public final int getMillis() { return iMillis; } /** * Get this object as an immutable Duration. This can be useful if you * don't trust the implementation of the interface to be well-behaved, or * to get a guaranteed immutable object. * * @return a Duration using the same field set and values */ public final Duration toDuration() { if (this instanceof Duration) { return (Duration) this; } return new Duration(this); } /** * Get this object as a MutableDuration. * * @return a MutableDuration using the same field set and values */ public final MutableDuration toMutableDuration() { return new MutableDuration(this); } public int compareTo(Object obj) { // Comparable contract means we cannot handle null or other types gracefully ReadableDuration thisDuration = (ReadableDuration) this; ReadableDuration otherDuration = (ReadableDuration) obj; long thisMillis = thisDuration.getTotalMillis(); long otherMillis = otherDuration.getTotalMillis(); // cannot do (thisMillis - otherMillis) as it can overflow if (thisMillis < otherMillis) { return -1; } if (thisMillis > otherMillis) { return 1; } return 0; } public boolean isEqual(ReadableDuration duration) { if (duration == null) { duration = Duration.ZERO; } return compareTo(duration) == 0; } public boolean isLongerThan(ReadableDuration duration) { if (duration == null) { duration = Duration.ZERO; } return compareTo(duration) > 0; } public boolean isShorterThan(ReadableDuration duration) { if (duration == null) { duration = Duration.ZERO; } return compareTo(duration) < 0; } /** * Compares this object with the specified object for equality based * on the value of each field. All ReadableDuration instances are accepted. * <p> * To compare two durations for absolute duration (ie. millisecond duration * ignoring the fields), use {@link #isEqual(ReadableDuration)} or * {@link #compareTo(Object)}. * * @param readableDuration a readable duration to check against * @return true if all the field values are equal, false if * not or the duration is null or of an incorrect type */ public boolean equals(Object readableDuration) { if (this == readableDuration) { return true; } if (readableDuration instanceof ReadableDuration == false) { return false; } ReadableDuration other = (ReadableDuration) readableDuration; DurationType type = getDurationType(); if (type.equals(other.getDurationType()) == false) { return false; } return getYears() == other.getYears() && getMonths() == other.getMonths() && getWeeks() == other.getWeeks() && getDays() == other.getDays() && getHours() == other.getHours() && getMinutes() == other.getMinutes() && getSeconds() == other.getSeconds() && getMillis() == other.getMillis(); } /** * Gets a hash code for the duration that is compatable with the * equals method. * * @return a hash code */ public int hashCode() { int hash = getDurationType().hashCode(); hash = 53 * hash + getYears(); hash = 53 * hash + getMonths(); hash = 53 * hash + getWeeks(); hash = 53 * hash + getDays(); hash = 53 * hash + getHours(); hash = 53 * hash + getMinutes(); hash = 53 * hash + getSeconds(); hash = 53 * hash + getMillis(); return hash; } /** * Gets the value as a String in the ISO8601 duration format. * <p> * For example, "P6H3M7S" represents 6 hours, 3 minutes, 7 seconds. * * @return the value as an ISO8601 string */ public String toString() { return ISODurationFormat.getInstance().standard().print(this); } protected void setDuration(ReadableDuration duration) { if (duration == null) { setTotalMillis(iType, 0L); } else { setDuration(iType, duration); } } /** * This method is private to prevent subclasses from overriding. */ private void setDuration(DurationType type, ReadableDuration duration) { setDuration(type, duration.getYears(), duration.getMonths(), duration.getWeeks(), duration.getDays(), duration.getHours(), duration.getMinutes(), duration.getSeconds(), duration.getMillis()); if (type.equals(duration.getDurationType()) && duration.isPrecise()) { iTotalMillis = duration.getTotalMillis(); iTotalMillisState = 2; } } protected void setDuration(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { setDuration(iType, years, months, weeks, days, hours, minutes, seconds, millis); } /** * This method is private to prevent subclasses from overriding. */ private void setDuration(DurationType type, int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { if (years != 0) { checkArgument(type.years(), "years"); } if (months != 0) { checkArgument(type.months(), "months"); } if (weeks != 0) { checkArgument(type.weeks(), "weeks"); } if (days != 0) { checkArgument(type.days(), "days"); } if (hours != 0) { checkArgument(type.hours(), "hours"); } if (minutes != 0) { checkArgument(type.minutes(), "minutes"); } if (seconds != 0) { checkArgument(type.seconds(), "seconds"); } if (millis != 0) { checkArgument(type.millis(), "millis"); } // assign fields in one block to reduce threading issues iYears = years; iMonths = months; iWeeks = weeks; iDays = days; iHours = hours; iMinutes = minutes; iSeconds = seconds; iMillis = millis; iTotalMillisState = 0; } /** * Sets all the fields in one go from a millisecond interval. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds */ protected void setTotalMillis(long startInstant, long endInstant) { setTotalMillis(iType, startInstant, endInstant); } /** * This method is private to prevent subclasses from overriding. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds */ private void setTotalMillis(DurationType type, long startInstant, long endInstant) { long baseTotalMillis = (endInstant - startInstant); int years = 0, months = 0, weeks = 0, days = 0; int hours = 0, minutes = 0, seconds = 0, millis = 0; DurationField field; field = type.years(); if (field.isSupported()) { years = field.getDifference(endInstant, startInstant); startInstant = field.add(startInstant, years); } field = type.months(); if (field.isSupported()) { months = field.getDifference(endInstant, startInstant); startInstant = field.add(startInstant, months); } field = type.weeks(); if (field.isSupported()) { weeks = field.getDifference(endInstant, startInstant); startInstant = field.add(startInstant, weeks); } field = type.days(); if (field.isSupported()) { days = field.getDifference(endInstant, startInstant); startInstant = field.add(startInstant, days); } field = type.hours(); if (field.isSupported()) { hours = field.getDifference(endInstant, startInstant); startInstant = field.add(startInstant, hours); } field = type.minutes(); if (field.isSupported()) { minutes = field.getDifference(endInstant, startInstant); startInstant = field.add(startInstant, minutes); } field = type.seconds(); if (field.isSupported()) { seconds = field.getDifference(endInstant, startInstant); startInstant = field.add(startInstant, seconds); } field = type.millis(); if (field.isSupported()) { millis = field.getDifference(endInstant, startInstant); startInstant = field.add(startInstant, millis); } // assign fields in one block to reduce threading issues iYears = years; iMonths = months; iWeeks = weeks; iDays = days; iHours = hours; iMinutes = minutes; iSeconds = seconds; iMillis = millis; // (end - start) is excess to be discarded iTotalMillis = baseTotalMillis - (endInstant - startInstant); iTotalMillisState = 2; } /** * Sets all the fields in one go from a millisecond duration. If any * supported fields are imprecise, an UnsupportedOperationException is * thrown. The exception to this is when the specified duration is zero. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param duration the duration, in milliseconds */ protected void setTotalMillis(long duration) { setTotalMillis(iType, duration); } /** * This method is private to prevent subclasses from overriding. * * @param duration the duration, in milliseconds */ private void setTotalMillis(DurationType type, long duration) { if (duration == 0) { iTotalMillis = duration; iTotalMillisState = 2; iYears = 0; iMonths = 0; iWeeks = 0; iDays = 0; iHours = 0; iMinutes = 0; iSeconds = 0; iMillis = 0; return; } long startInstant = 0; int years = 0, months = 0, weeks = 0, days = 0; int hours = 0, minutes = 0, seconds = 0, millis = 0; DurationField field; field = type.years(); if (field.isSupported() && field.isPrecise()) { years = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, years); } field = type.months(); if (field.isSupported() && field.isPrecise()) { months = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, months); } field = type.weeks(); if (field.isSupported() && field.isPrecise()) { weeks = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, weeks); } field = type.days(); if (field.isSupported() && field.isPrecise()) { days = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, days); } field = type.hours(); if (field.isSupported() && field.isPrecise()) { hours = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, hours); } field = type.minutes(); if (field.isSupported() && field.isPrecise()) { minutes = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, minutes); } field = type.seconds(); if (field.isSupported() && field.isPrecise()) { seconds = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, seconds); } field = type.millis(); if (field.isSupported() && field.isPrecise()) { millis = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, millis); } // assign fields in one block to reduce threading issues iYears = years; iMonths = months; iWeeks = weeks; iDays = days; iHours = hours; iMinutes = minutes; iSeconds = seconds; iMillis = millis; // (end - start) is excess to be discarded iTotalMillis = duration - (duration - startInstant); iTotalMillisState = 2; } protected void add(long duration) { setTotalMillis(getTotalMillis() + duration); } protected void add(ReadableDuration duration) { if (duration != null) { add(duration.getTotalMillis()); } } protected void normalize() { setTotalMillis(getTotalMillis()); } /** * Sets the number of years of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param years the number of years * @throws UnsupportedOperationException if field is not supported. */ protected void setYears(int years) { if (years != iYears) { if (years != 0) { checkSupport(iType.years(), "years"); } iYears = years; iTotalMillisState = 0; } } /** * Adds the specified years to the number of years in the duration. * * @param years the number of years * @throws UnsupportedOperationException if field is not supported. */ protected void addYears(int years) { setYears(getYears() + years); } /** * Sets the number of months of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param months the number of months * @throws UnsupportedOperationException if field is not supported. */ protected void setMonths(int months) { if (months != iMonths) { if (months != 0) { checkSupport(iType.months(), "months"); } iMonths = months; iTotalMillisState = 0; } } /** * Adds the specified months to the number of months in the duration. * * @param months the number of months * @throws UnsupportedOperationException if field is not supported. */ protected void addMonths(int months) { setMonths(getMonths() + months); } /** * Sets the number of weeks of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param weeks the number of weeks * @throws UnsupportedOperationException if field is not supported. */ protected void setWeeks(int weeks) { if (weeks != iWeeks) { if (weeks != 0) { checkSupport(iType.weeks(), "weeks"); } iWeeks = weeks; iTotalMillisState = 0; } } /** * Adds the specified weeks to the number of weeks in the duration. * * @param weeks the number of weeks * @throws UnsupportedOperationException if field is not supported. */ protected void addWeeks(int weeks) { setWeeks(getWeeks() + weeks); } /** * Sets the number of days of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param days the number of days * @throws UnsupportedOperationException if field is not supported. */ protected void setDays(int days) { if (days != iDays) { if (days != 0) { checkSupport(iType.days(), "days"); } iDays = days; iTotalMillisState = 0; } } /** * Adds the specified days to the number of days in the duration. * * @param days the number of days * @throws UnsupportedOperationException if field is not supported. */ protected void addDays(int days) { setDays(getDays() + days); } /** * Sets the number of hours of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param hours the number of hours * @throws UnsupportedOperationException if field is not supported. */ protected void setHours(int hours) { if (hours != iHours) { if (hours != 0) { checkSupport(iType.hours(), "hours"); } iHours = hours; iTotalMillisState = 0; } } /** * Adds the specified hours to the number of hours in the duration. * * @param hours the number of hours * @throws UnsupportedOperationException if field is not supported. */ protected void addHours(int hours) { setHours(getHours() + hours); } /** * Sets the number of minutes of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param minutes the number of minutes * @throws UnsupportedOperationException if field is not supported. */ protected void setMinutes(int minutes) { if (minutes != iMinutes) { if (minutes != 0) { checkSupport(iType.minutes(), "minutes"); } iMinutes = minutes; iTotalMillisState = 0; } } /** * Adds the specified minutes to the number of minutes in the duration. * * @param minutes the number of minutes * @throws UnsupportedOperationException if field is not supported. */ protected void addMinutes(int minutes) { setMinutes(getMinutes() + minutes); } /** * Sets the number of seconds of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param seconds the number of seconds * @throws UnsupportedOperationException if field is not supported. */ protected void setSeconds(int seconds) { if (seconds != iSeconds) { if (seconds != 0) { checkSupport(iType.seconds(), "seconds"); } iSeconds = seconds; iTotalMillisState = 0; } } /** * Adds the specified seconds to the number of seconds in the duration. * * @param seconds the number of seconds * @throws UnsupportedOperationException if field is not supported. */ protected void addSeconds(int seconds) { setSeconds(getSeconds() + seconds); } /** * Sets the number of millis of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param millis the number of millis * @throws UnsupportedOperationException if field is not supported. */ protected void setMillis(int millis) { if (millis != iMillis) { if (millis != 0) { checkSupport(iType.millis(), "millis"); } iMillis = millis; iTotalMillisState = 0; } } /** * Adds the specified millis to the number of millis in the duration. * * @param millis the number of millis * @throws UnsupportedOperationException if field is not supported. */ protected void addMillis(int millis) { setMillis(getMillis() + millis); } }
package ruby.keyboardwarrior.data.tag; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import ruby.keyboardwarrior.common.Utils; import ruby.keyboardwarrior.data.exception.DuplicateDataException; import java.util.*; //@@author A0139716X /** * A list of tags that enforces no nulls and uniqueness between its elements. * * Supports minimal set of list operations for the app's features. * * @see Tag#equals(Object) * @see CollectionUtil#elementsAreUnique(Collection) */ public class UniqueTagList implements Iterable<Tag> { private final ObservableList<Tag> internalList = FXCollections.observableArrayList(); /** * Signals that an operation would have violated the 'no duplicates' property of the list. */ public static class DuplicateTagException extends DuplicateDataException { protected DuplicateTagException() { super("Operation would result in duplicate tags"); } } /** * Signals that an operation targeting a specified Tag in the list would fail because * there is no such matching Tag in the list. */ public static class TagNotFoundException extends Exception { protected TagNotFoundException() { super("Tag is not found inside the list"); } } /** * Constructs empty TagList. */ public UniqueTagList() {} /** * Varargs/array constructor for the Tags, it enforces no nulls or duplicates. */ public UniqueTagList(Tag... tags) throws DuplicateTagException { assert !Utils.isAnyNull((Object[]) tags); final List<Tag> initialTags = Arrays.asList(tags); if (!Utils.elementsAreUnique(initialTags)) { throw new DuplicateTagException(); } this.internalList.addAll(initialTags); } /** * Java collections constructor, enforces no null or duplicate elements. */ public UniqueTagList(Collection<Tag> tags) throws DuplicateTagException { Utils.assertNoNullElements(tags); if (!Utils.elementsAreUnique(tags)) { throw new DuplicateTagException(); } this.internalList.addAll(tags); } /** * Java set constructor, enforces no nulls. */ public UniqueTagList(Set<Tag> tags) { Utils.assertNoNullElements(tags); this.internalList.addAll(tags); } /** * Copy constructor, insulates from changes in source. */ public UniqueTagList(UniqueTagList source) { // Insulate internal list from changes in argument this.internalList.addAll(source.internalList); } /** * All Tags in this list as a Set. This set is mutable and change-insulated against the internal list. */ public Set<Tag> toSet() { return new HashSet<>(this.internalList); } /** * Replaces the Tags in this list with those in the argument tag list. */ public void setTags(UniqueTagList replacement) { this.internalList.clear(); this.internalList.addAll(replacement.internalList); } /** * Adds every Tag from the argument list that does not yet exist in this list. */ public void mergeFrom(UniqueTagList tags) { final Set<Tag> alreadyInside = this.toSet(); for (Tag tag : tags) { if (!alreadyInside.contains(tag)) { this.internalList.add(tag); } } } /** * Returns true if the list contains an equivalent Tag as the given argument. */ public boolean contains(Tag toCheck) { assert toCheck != null; return this.internalList.contains(toCheck); } /** * Adds a Tag to the list. * * @throws DuplicateTagException if the Tag to add is a duplicate of an existing Tag in the list. */ public void add(Tag toAdd) throws DuplicateTagException { assert toAdd != null; if (contains(toAdd)) { throw new DuplicateTagException(); } this.internalList.add(toAdd); } /** * Removes the equivalent Tag from the list. * * @throws TagNotFoundException if no such Tag could be found in the list. */ public void remove(Tag toRemove) throws TagNotFoundException { final boolean TagFoundAndDeleted = this.internalList.remove(toRemove); if (!TagFoundAndDeleted) { throw new TagNotFoundException(); } } /** * Returns an iterator for the list of Tags */ @Override public Iterator<Tag> iterator() { return this.internalList.iterator(); } /** * Get method for an internal list of Tags */ public ObservableList<Tag> getInternalList() { return this.internalList; } /** * Overrides the to String method for the Tag list */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); for(Tag t : this.internalList){ String stringTag = t.toString(); builder.append(stringTag); } return builder.toString(); } /** * Overrides the equals method for the Tag list */ @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof UniqueTagList // instance of handles nulls && this.internalList.equals( ((UniqueTagList) other).internalList)); } /** * Overrides the hash code method for the Tag list */ @Override public int hashCode() { return this.internalList.hashCode(); } }
package sim.components.basic; import java.util.ArrayList; public class ProbabilityMultiplexer extends Multiplexer { private ArrayList<Tuple> sinks; private Double sum; class Tuple { Double mass; Sink sink; } public ProbabilityMultiplexer() { sinks = new ArrayList<>(); } @Override public void connectTo(Sink sink) { connectTo(sink, "1"); } @Override public void connectTo(Sink sink, String prob) { Tuple t = new Tuple(); t.mass = Double.parseDouble(prob); t.sink = sink; sum += t.mass; sinks.add(t); } @Override public void send(Job job) { onArrival(job); Double random = Math.random() * sum; for (Tuple t : sinks) { if (random < t.mass) { onDeparture(job); t.sink.send(job); break; } random -= t.mass; } } }
package com.balancedpayments; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.HashMap; import com.balancedpayments.errors.*; import org.junit.Test; public class CallbackTest extends BaseTest { @Test public void testCallbackCreate() throws HTTPError, NotCreated, NoResultsFound, MultipleResultsFound { Callback.Collection callbacks = mp.callbacks; int total = callbacks.total(); assertEquals(0, total); HashMap<String, Object> callbackPayload = new HashMap<String, Object>(); callbackPayload.put("url", "http: callbackPayload.put("method", "post"); Callback callback = new Callback(callbackPayload); callback.save(); callback.reload(); mp.reload(); assertEquals(mp.callbacks.total(), 1); assertEquals("http: assertEquals("post", callback.method); callback.delete(); mp.reload(); assertEquals(mp.callbacks.total(), 0); } @Test public void testCallbacksResourceFields() throws HTTPError { HashMap<String, Object> payload = new HashMap<String, Object>(); payload.put("url", "http: payload.put("method", "post"); Callback callback = new Callback(payload); callback.save(); assertTrue(callback.href.contains("/callbacks/CB")); assertTrue(callback.id.contains("CB")); assertEquals(callback.method, "post"); assertEquals(callback.revision, "1.1"); assertEquals(callback.url, "http: } }
package com.cognitect.transit; import com.cognitect.transit.impl.JsonParser; import com.cognitect.transit.impl.JsonReader; import com.cognitect.transit.impl.JsonWriter; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.codec.binary.Base64; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URISyntaxException; import java.util.*; public class TransitTest extends TestCase { public TransitTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(TransitTest.class); } // Reading public Reader reader(String s) throws IOException { InputStream in = new ByteArrayInputStream(s.getBytes()); return new JsonReader(in); } public void testReadString() throws IOException { assertEquals("foo", reader("\"foo\"").read()); assertEquals("~foo", reader("\"~~foo\"").read()); assertEquals("`foo", reader("\"~`foo\"").read()); assertEquals("~#foo", reader("\"~#foo\"").read()); assertEquals("^foo", reader("\"~^foo\"").read()); } public void testReadBoolean() throws IOException { assertTrue((Boolean) reader("\"~?t\"").read()); assertFalse((Boolean) reader("\"~?f\"").read()); } public void testReadNull() throws IOException { assertNull(reader("\"~_\"").read()); } public void testReadKeyword() throws IOException { Reader r = reader("\"~:foo\""); Object v = r.read(); assertEquals("foo", v.toString()); assertEquals("foo", ((Keyword)v).value); } public void testReadInteger() throws IOException { Reader r = reader("\"~i42\""); assertEquals(42L, r.read()); r = reader("\"~i4256768765123454321897654321234567\""); assertEquals(0, (new BigInteger("4256768765123454321897654321234567")).compareTo( (BigInteger)r.read())); } public void testReadDouble() throws IOException { assertEquals(new Double("42.5"), reader("\"~d42.5\"").read()); } public void testReadBigDecimal() throws IOException { assertEquals(0, (new BigDecimal("42.5")).compareTo( (BigDecimal)reader("\"~f42.5\"").read())); } public void testReadTime() throws IOException { Date d = new Date(); long t = d.getTime(); String timeString = JsonParser.dateTimeFormat.format(d); assertEquals(t, ((Date) reader("\"~t" + timeString + "\"").read()).getTime()); assertEquals(t, ((Date) reader("{\"~#t\": " + t + "}").read()).getTime()); } public void testReadUUID() throws IOException { UUID uuid = UUID.randomUUID(); long hi64 = uuid.getMostSignificantBits(); long lo64 = uuid.getLeastSignificantBits(); assertEquals(0, uuid.compareTo((UUID)reader("\"~u" + uuid.toString() + "\"").read())); assertEquals(0, uuid.compareTo((UUID)reader("{\"~#u\": [" + hi64 + ", " + lo64 + "]}").read())); } public void testReadURI() throws URISyntaxException, IOException { URI uri = new URI("http: assertEquals(0, uri.compareTo((URI)reader("\"~rhttp: } public void testReadSymbol() throws IOException { Reader r = reader("\"~$foo\""); Object v = r.read(); assertEquals("foo", v.toString()); assertEquals("foo", ((Symbol)v).value); } public void testReadCharacter() throws IOException { assertEquals('f', reader("\"~cf\"").read()); } public void testReadBinary() throws IOException { byte[] bytes = "foobarbaz".getBytes(); byte[] encodedBytes = Base64.encodeBase64(bytes); byte[] decoded = (byte[])reader("\"~b" + new String(encodedBytes) + "\"").read(); assertEquals(bytes.length, decoded.length); boolean same = true; for(int i=0;i<bytes.length;i++) { if(bytes[i]!=decoded[i]) same = false; } assertTrue(same); } public void testReadUnknown() throws IOException { assertEquals("~jfoo", reader("\"~jfoo\"").read()); } public void testReadArray() throws IOException { List l = (List)reader("[1, 2, 3]").read(); assertTrue(l instanceof ArrayList); assertEquals(3, l.size()); assertEquals(1L, l.get(0)); assertEquals(2L, l.get(1)); assertEquals(3L, l.get(2)); } public void testReadArrayWithNested() throws IOException { Date d = new Date(); String t = JsonParser.dateTimeFormat.format(d); List l = (List)reader("[\"~:foo\", \"~t" + t + "\", \"~?t\"]").read(); assertEquals(3, l.size()); assertEquals("foo", ((Keyword)l.get(0)).value); assertEquals(d.getTime(), ((Date)l.get(1)).getTime()); assertTrue((Boolean) l.get(2)); } public void testReadMap() throws IOException { Map m = (Map)reader("{\"a\": 2, \"b\": 4}").read(); assertEquals(2, m.size()); assertEquals(2L, m.get("a")); assertEquals(4L, m.get("b")); } public void testReadMapWithNested() throws IOException { String uuid = UUID.randomUUID().toString(); Map m = (Map)reader("{\"a\": \"~:foo\", \"b\": \"~u" + uuid + "\"}").read(); assertEquals(2, m.size()); assertEquals("foo", ((Keyword)m.get("a")).value); assertEquals(uuid, m.get("b").toString()); } public void testReadSet() throws IOException { Set s = (Set)reader("{\"~#set\": [1, 2, 3]}").read(); assertEquals(3, s.size()); assertTrue(s.contains(1L)); assertTrue(s.contains(2L)); assertTrue(s.contains(3L)); } public void testReadList() throws IOException { List l = (List)reader("{\"~#list\": [1, 2, 3]}").read(); assertTrue(l instanceof LinkedList); assertEquals(3, l.size()); assertEquals(1L, l.get(0)); assertEquals(2L, l.get(1)); assertEquals(3L, l.get(2)); } public void testReadUnknownTaggedMap() throws IOException { Map m = (Map)reader("{\"~#foo\": [1, 2, 3]}").read(); assertTrue(m instanceof HashMap); assertEquals(1, m.size()); List l = (List)m.get("~#foo"); System.out.println(l); assertEquals(3, l.size()); assertEquals(1L, l.get(0)); assertEquals(2L, l.get(1)); assertEquals(3L, l.get(2)); } public void testReadMany() throws IOException { Reader r = reader("true null false \"foo\" 42.2 42"); assertTrue((Boolean)r.read()); assertNull(r.read()); assertFalse((Boolean) r.read()); assertEquals("foo", r.read()); assertEquals(42.2, r.read()); assertEquals(42L, r.read()); } // Writing public String write(Object o) throws Exception { OutputStream out = new ByteArrayOutputStream(); Writer w = new JsonWriter(out); w.write(o); return out.toString(); } public void testWriteBoolean() throws Exception { assertEquals("true", write(true)); } public boolean isEqual(Object o1, Object o2) { if(o1 instanceof Boolean) return o1 == o2; else return false; } public void testRoundTrip() throws Exception { Object inObject = true; OutputStream out = new ByteArrayOutputStream(); Writer w = new JsonWriter(out); w.write(inObject); String s = out.toString(); InputStream in = new ByteArrayInputStream(s.getBytes()); JsonReader reader = new JsonReader(in); Object outObject = reader.read(); assertTrue(isEqual(inObject, outObject)); } }
package de.bmoth.App; import de.bmoth.app.OptionController; import de.bmoth.app.PersonalPreferences; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import org.junit.Test; import org.loadui.testfx.GuiTest; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import static org.loadui.testfx.Assertions.verifyThat; import static org.loadui.testfx.controls.Commons.hasText; public class OptionControllerTest extends GuiTest { private final Logger logger = Logger.getLogger(getClass().getName()); private OptionController optionController; @Override protected Parent getRootNode() { Parent parent; try { FXMLLoader loader = new FXMLLoader(getClass().getResource("options.fxml")); parent = loader.load(); optionController = loader.getController(); } catch (IOException e) { logger.log(Level.SEVERE, "Couldn't create parent", e); return null; } return parent; } @Test public void optionCreateTest() { optionController.setUpPrefs(); verifyThat("#minInt", hasText(String.valueOf(PersonalPreferences.getIntPreference(PersonalPreferences.IntPreference.MIN_INT)))); verifyThat("#maxInt", hasText(String.valueOf(PersonalPreferences.getIntPreference(PersonalPreferences.IntPreference.MAX_INT)))); verifyThat("#maxInitState", hasText(String.valueOf(PersonalPreferences.getIntPreference(PersonalPreferences.IntPreference.MAX_INITIAL_STATE)))); verifyThat("#maxTrans", hasText(String.valueOf(PersonalPreferences.getIntPreference(PersonalPreferences.IntPreference.MAX_TRANSITIONS)))); verifyThat("#z3Timeout", hasText(String.valueOf(PersonalPreferences.getIntPreference(PersonalPreferences.IntPreference.Z3_TIMEOUT)))); } }
package hudson.plugins.git; import java.io.File; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class IndexEntryTest { private final String mode = "160000"; private final String type = "commit"; private final String object = "index-entry-object"; private final String file = ".git" + File.separator + "index-entry-file"; private IndexEntry entry; public IndexEntryTest() { } @Before public void setUp() { entry = new IndexEntry(mode, type, object, file); } @Test public void testGetMode() { assertEquals(mode, entry.getMode()); } @Test public void testSetMode() { String myMode = "100777"; entry.setMode(myMode); assertEquals(myMode, entry.getMode()); } @Test public void testGetType() { assertEquals(type, entry.getType()); } @Test public void testSetType() { String myType = "tag"; entry.setType(myType); assertEquals(myType, entry.getType()); } @Test public void testGetObject() { assertEquals(object, entry.getObject()); } @Test public void testSetObject() { String myObject = "my-object"; entry.setObject(myObject); assertEquals(myObject, entry.getObject()); } @Test public void testGetFile() { assertEquals(file, entry.getFile()); } @Test public void testSetFile() { String myFile = "my-file"; entry.setFile(myFile); assertEquals(myFile, entry.getFile()); } @Test public void testToString() { String expected = "IndexEntry[mode=" + mode + ",type=" + type + ",file=" + file + ",object=" + object + "]"; assertEquals(expected, entry.toString()); } }
package laboratory.test.time; import java.util.Date; import java.util.GregorianCalendar; import org.joda.time.DateTime; import org.joda.time.Duration; import org.joda.time.Interval; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JodaTimeTest { private static final Logger log = LoggerFactory.getLogger(JodaTimeTest.class); // @Test // public void testDateValidate() { // DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); @Test public void testNow() { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); String dt = DateTime.now().toString(formatter); log.debug("testNow: " + dt); } @Test public void testFromString() { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime dt = formatter.parseDateTime("2016-02-05"); Assert.assertEquals("2016-02-05T00:00:00.000+09:00", dt.toString()); try { formatter.parseDateTime("20160205"); } catch (Exception e) { log.error(e.getMessage()); } DateTime dt2 = new DateTime("2015-01-01"); Assert.assertEquals("2015-01-01T00:00:00.000+09:00", String.valueOf(dt2)); } @Test public void testGetter() { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS"); DateTime dt = formatter.parseDateTime("2016-02-15 13:40:30.123"); // (ERA) Assert.assertEquals(1, dt.getEra()); Assert.assertEquals(20, dt.getCenturyOfEra()); Assert.assertEquals(2016, dt.getYear()); Assert.assertEquals(16, dt.getYearOfCentury()); Assert.assertEquals(2016, dt.getYearOfEra()); Assert.assertEquals(2016, dt.getWeekyear()); Assert.assertEquals(2, dt.getMonthOfYear()); Assert.assertEquals(7, dt.getWeekOfWeekyear()); Assert.assertEquals("Asia/Seoul", dt.getZone().toString()); Assert.assertEquals(46, dt.getDayOfYear()); Assert.assertEquals(15, dt.getDayOfMonth()); Assert.assertEquals(1, dt.getDayOfWeek()); Assert.assertEquals(13, dt.getHourOfDay()); Assert.assertEquals(820, dt.getMinuteOfDay()); Assert.assertEquals(40, dt.getMinuteOfHour()); Assert.assertEquals(49230, dt.getSecondOfDay()); Assert.assertEquals(30, dt.getSecondOfMinute()); Assert.assertEquals(123, dt.getMillisOfSecond()); Assert.assertEquals(1455511230123L, dt.getMillis()); } @Test public void testFromJavaUtilDate() { Date date = GregorianCalendar.getInstance().getTime(); DateTime dt = new DateTime(date); log.debug("testFromJavaUtilDate: " + dt.toString()); } /** * * * @author fixalot */ @Test public void testDateSplit() { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime start = formatter.parseDateTime("2017-01-01"); DateTime end = formatter.parseDateTime("2017-02-03"); log.debug(start.toString()); log.debug(end.toString()); // Period p = new Period(start, end); // (p.getYears() * 365) // p.getDays() Interval interval = new Interval(start.toDate().getTime(), end.toDate().getTime()); Period period = interval.toPeriod(); System.out.printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds%n", period.getYears(), period.getMonths(), period.getDays(), period.getHours(), period.getMinutes(), period.getSeconds()); } @Test public void testToFormatString() { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss:SSS"); DateTime dt = new DateTime(); DateTime newDt = dt.withYear(2020).withMonthOfYear(2).withDayOfMonth(29).withHourOfDay(23) .withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(10); Assert.assertEquals("2020-02-29T23:59:59.010+09:00", newDt.toString()); Assert.assertEquals("2020-02-29 23:59:59:010", newDt.toString(formatter)); } @Test public void testEqual() { // Assert.assertEquals(new DateTime(), DateTime.now()); // Assert.assertEquals(new DateTime(2020, 2, 29, 23, 59, 59, 10), new DateTime().withYear(2020).withMonthOfYear(2).withDayOfMonth(29).withHourOfDay(23) .withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(10)); } @Test public void testFromFormatString() { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss:SSS"); Assert.assertEquals(new DateTime(2020, 2, 29, 23, 59, 59, 10), formatter.parseDateTime("2020-02-29 23:59:59:010")); } @Test public void testPlusDay() { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss:SSS"); DateTime dt = new DateTime(2020, 2, 29, 23, 59, 59, 10); DateTime newInstance = dt.plusDays(1); Assert.assertEquals("2020-03-01 23:59:59:010", newInstance.toString(formatter)); newInstance = dt.plus(Period.days(1)); Assert.assertEquals("2020-03-01 23:59:59:010", newInstance.toString(formatter)); newInstance = dt.plus(new Duration(24L*60L*60L*1000L)); Assert.assertEquals("2020-03-01 23:59:59:010", newInstance.toString(formatter)); } @Test public void testCalculateMonth() { DateTime dt = new DateTime(2017, 3, 31, 00, 00, 00); DateTime a = dt.minusMonths(1); Assert.assertEquals(new DateTime(2017, 2, 28, 00, 00, 00).toString(), a.toString()); DateTime b = dt.plusMonths(1); Assert.assertEquals(new DateTime(2017, 4, 30, 00, 00, 00).toString(), b.toString()); } }
package org.goldenorb.test; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.hadoop.io.LongWritable; import org.apache.zookeeper.ZooKeeper; import org.goldenorb.OrbRunner; import org.goldenorb.conf.OrbConfiguration; import org.goldenorb.zookeeper.OrbZKFailure; import org.goldenorb.zookeeper.ZookeeperUtils; import org.goldenorb.zookeeper.test.TJTracker; import org.junit.Test; public class TestJobManager extends OrbRunner{ private final static int NUM_OF_MEMBERS = 10; private final static int HEARTBEAT_INTERVAL = 500; //in ms List<Thread> threads = new ArrayList<Thread>(); List<TJTracker> trackers = new ArrayList<TJTracker>(); private ZooKeeper zk; @Test public void jobManagerTest() throws IOException, InterruptedException, OrbZKFailure { zk = ZookeeperUtils.connect("localhost"); ZookeeperUtils.tryToCreateNode(zk, "/GoldenOrb"); ZookeeperUtils.tryToCreateNode(zk, "/GoldenOrb/OrbCluster"); CountDownLatch joinLeaderGroup = new CountDownLatch(NUM_OF_MEMBERS); //everyone join? CountDownLatch exit = new CountDownLatch(NUM_OF_MEMBERS); //everyone ready to exit? CountDownLatch jobCreated = new CountDownLatch(1); CountDownLatch newLeader = new CountDownLatch(1); OrbConfiguration orbConf = new OrbConfiguration(); orbConf.setOrbClusterName("OrbCluster"); orbConf.setJobHeartbeatTimeout(1000); orbConf.setMaximumJobTries(3); System.out.println(orbConf.getJobHeartbeatTimeout()); // Create all of the test Trackers for (int i = 0; i < NUM_OF_MEMBERS; i++) { TJTracker tracker = new TJTracker(zk, joinLeaderGroup, exit, orbConf, i, "/GoldenOrb/OrbCluster"); trackers.add(tracker); threads.add(new Thread(tracker)); threads.get(i).start(); } joinLeaderGroup.await(); orbConf.setOrbZooKeeperQuorum("localhost"); String path1 = runJob(orbConf); String path2 = runJob(orbConf); new Thread(new HeartbeatUpdater(getJobInProgressPath(path1))).start(); new Thread(new HeartbeatUpdater(getJobInProgressPath(path2))).start(); jobCreated.await(2, TimeUnit.SECONDS); int leader = 0; for (int i = 0; i < NUM_OF_MEMBERS; i++){ if(trackers.get(i).isLeader()){ leader = i; } } trackers.get(leader).leave(); newLeader.await(5, TimeUnit.SECONDS); //exit and shutdown for (int i = 0; i < NUM_OF_MEMBERS; i++) { trackers.get(i).leave(); } exit.await(); ZookeeperUtils.recursiveDelete(zk, "/GoldenOrb"); ZookeeperUtils.deleteNodeIfEmpty(zk, "/GoldenOrb"); } private class HeartbeatUpdater implements Runnable{ private String pathToUpdate; private boolean active = true; private Long heartbeat = 1L; public HeartbeatUpdater(String pathToUpdate){ this.pathToUpdate = pathToUpdate; } @Override public void run() { while(active){ synchronized(this){ try { wait(HEARTBEAT_INTERVAL); try { ZookeeperUtils.existsUpdateNodeData(zk, pathToUpdate + "/messages/heartbeat", new LongWritable(heartbeat++)); System.err.println("Creating heartbeat for: " + pathToUpdate + "/messages/heartbeat" + " heartbeat is: " + heartbeat); } catch (OrbZKFailure e) { e.printStackTrace(); } } catch (InterruptedException e) { e.printStackTrace(); } } } } public void kill(){ active = false; } } private static String getJobInProgressPath(String path){ String[] pieces = path.split("/"); String importantPiece = pieces[pieces.length -1]; return "/GoldenOrb/OrbCluster/JobsInProgress/" + importantPiece; } }
package org.rythmengine.issue; import models.Foo; import models.GH185Model; import org.junit.Test; import org.rythmengine.TestBase; import org.rythmengine.conf.RythmConfigurationKey; import org.rythmengine.extension.ICodeType; import org.rythmengine.utils.Escape; import org.rythmengine.utils.JSONWrapper; import org.rythmengine.utils.S; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * Test Github Issues */ public class GHIssueTest extends TestBase { @Test public void test116() { t = "PlayRythm Demo - @get(\"title\")"; s = r(t); eq("PlayRythm Demo - "); } @Test public void test117() { System.getProperties().put("default.template_lang.impl", ICodeType.DefImpl.CSV); t = "@for(\"FirstName,LastName,Email\"){@__sep}"; s = r(t); eq("FirstName,LastName,Email"); } @Test public void test120() { t = "@def String x(boolean x) {if (x) {return \"x\";} else {return \"y\";}}@x(true)"; s = r(t); eq("x"); } @Test public void test122() { System.getProperties().put(RythmConfigurationKey.DEFAULT_CODE_TYPE_IMPL.getKey(), ICodeType.DefImpl.HTML); t = "@args String src;<script src='@src'></script><script src='@src'></script>"; s = r(t, "/js/abc"); eq("<script src='/js/abc'></script><script src='/js/abc'></script>"); t = "@args models.Foo foo;<script src='@foo.bar()._x()'></script>"; s = r(t, new Foo()); eq("<script src=''></script>"); } @Test public void test123() { t = "@args models.Foo foo;@foo.bar()._x()"; s = r(t, new Foo()); eq(""); } @Test public void test132() { t = "@args String s;@s.length()"; s = r(t, null); eq("0"); s = r(t); eq("0"); } @Test public void test137() { t = "@{String s = \"abc\"}\n@s @assign(foo){bar}@foo"; s = r(t); eq("\nabc bar"); } @Test public void test139() { t = "@args Object @1;@if (@1) \n{true} \nelse\n{false}"; s = r(t, true); eq("true"); s = r(t, "false"); eq("false"); t = "@for(int i = 0; i < 1; ++i).join()\n{\n@i\n}"; s = r(t); eq("\n0\n"); t = "@args List l;@for(l).join()\n{@_}"; s = r(t, Arrays.asList("1,2".split(","))); eq("\n1,2"); } @Test public void test140() { t = "@args Date d;@d.format(\"yyyy-MM-dd\"):@args Number n;@n.format()"; s = r(t, null, null); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String refValue = sdf.format(new Date(0)) + ":0"; eq(refValue); } @Test public void test141() { t = "@args integration.T t;@t"; s = r(t); eq(""); } @Test public void test142() { t = "@locale(\"zh_CN\"){@i18n('template', \"planet\", 7, new Date())}"; s = r(t); assertContains(s, ""); assertContains(s, DateFormat.getDateInstance(DateFormat.LONG, new Locale("zh", "CN")).format(new Date())); } @Test public void test143() { s = S.join("::", new Integer[]{1,2,3}); eq("1::2::3"); s = S.join(":", new Double[]{1.0, 2.0, 3.0}); eq("1.0:2.0:3.0"); } @Test public void test144() { t = "@args Integer[] itr;@itr[0]"; s = r(t, JSONWrapper.wrap("{\"itr\": [\"1\"]}")); eq("1"); t = "@args List<Integer> itr;@itr.get(0)"; s = r(t, JSONWrapper.wrap("{\"itr\": [\"1\"]}")); eq("1"); } @Test public void test145() { t = "@args Date today = new Date(),Boolean b;@today.format(\"yyyy\"):@b"; s = r(t); eq(S.format(new Date(), "yyyy") + ":false"); t = "@args String x = \"x\";@x"; s = r(t); eq("x"); } @Test public void test146() { t = "@for(\"a\"){\n{true}\n}"; s = r(t); eq("{true}\n"); t = "@if(true){\n{true}\n}"; s = r(t); eq("{true}"); t = "@for(int i = 0; i < 1; ++i){\n{true}\n}"; s = r(t); eq("{true}\n"); } @Test public void test147() { t = "gh147/index.html"; s = r(t); contains("pre-callback-in-tag2"); } @Test public void test148() { t = "gh148/main.html"; s = r(t,"a", "b"); eq("2/b"); Map<String, Object> args = new HashMap<String, Object>(); args.put("id", "x"); args.put("sid", "b"); s = r(t, args); eq("2/b"); } @Test public void test155() { String x = "\uD83D\uDE30"; assertEquals(x, S.escapeCSV(x).toString()); assertEquals(x, Escape.CSV.apply(x).toString()); System.getProperties().setProperty(RythmConfigurationKey.DEFAULT_CODE_TYPE_IMPL.getKey(), "org.rythmengine.extension.ICodeType.DefImpl.CSV"); t = "@s"; s = r(t, x); eq(x); } private void yes(Object p) { assertEquals("yes", r(t, p, null)); } private void no(Object p) { assertEquals("no", r(t, p, null)); } @Test public void test157() { t = "@args List o;@if(o){yes}else{no}"; no(null); t = "@args Integer o;@if(o){yes}else{no}"; no(null); t = "@args Long o;@if(o){yes}else{no}"; no(null); t = "@args Character o;@if(o){yes}else{no}"; no(null); t = "@args Float o;@if(o){yes}else{no}"; no(null); t = "@args Double o;@if(o){yes}else{no}"; no(null); t = "@args Boolean o;@if(o){yes}else{no}"; no(null); } @Test public void test176() { t = "@for (int i = 0; i < 10; ++i) {\n" + " @continue(i % 5)\n" + " @i\n" + "}"; s = r(t); eq("0\n5\n"); } @Test public void test185() { GH185Model model = new GH185Model("bar"); t = "@args models.GH185Model model\n@if (model.foo@) {@model.foo@}"; s = r(t, model); eq("bar"); } @Test public void test188() { t = "gh188/foo.txt"; s = r(t); eq("good"); } @Test public void test193() { t = "@if(true) {a} else { \nb\n}"; s = r(t); eq("a"); } @Test public void test194() { // This is known issue. // The workaround could be use ESCAPED WORD // t = "@verbatim{\\}"; // s = r(t); } @Test public void test201() { // Known issue // t = "gh201/gh201.txt"; // StringWriter sw = new StringWriter(); // Rythm.engine().render(sw, t); // s = sw.toString(); // contains("header"); // contains("inner"); // contains("footer"); } @Test public void test202() { t = "@def echo(String s){@s}@echo(\"okay?\")"; eq("okay?"); } @Test public void test211() { t = "gh211/foo.txt"; s = r(t); System.out.println(s); } public static void main(String[] args) { run(GHIssueTest.class); } }
package seedu.jimi.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.jimi.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.jimi.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static seedu.jimi.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.jimi.TestApp; import seedu.jimi.commons.core.Config; import seedu.jimi.commons.core.EventsCenter; import seedu.jimi.commons.events.model.TaskBookChangedEvent; import seedu.jimi.commons.events.ui.JumpToListRequestEvent; import seedu.jimi.commons.events.ui.ShowHelpRequestEvent; import seedu.jimi.commons.util.CommandUtil; import seedu.jimi.commons.util.ConfigUtil; import seedu.jimi.logic.commands.AddCommand; import seedu.jimi.logic.commands.ClearCommand; import seedu.jimi.logic.commands.Command; import seedu.jimi.logic.commands.CommandResult; import seedu.jimi.logic.commands.CompleteCommand; import seedu.jimi.logic.commands.DeleteCommand; import seedu.jimi.logic.commands.ExitCommand; import seedu.jimi.logic.commands.FindCommand; import seedu.jimi.logic.commands.HelpCommand; import seedu.jimi.logic.commands.RedoCommand; import seedu.jimi.logic.commands.SaveAsCommand; import seedu.jimi.model.Model; import seedu.jimi.model.ModelManager; import seedu.jimi.model.ReadOnlyTaskBook; import seedu.jimi.model.TaskBook; import seedu.jimi.model.datetime.DateTime; import seedu.jimi.model.event.Event; import seedu.jimi.model.tag.Priority; import seedu.jimi.model.tag.Tag; import seedu.jimi.model.tag.UniqueTagList; import seedu.jimi.model.task.DeadlineTask; import seedu.jimi.model.task.FloatingTask; import seedu.jimi.model.task.Name; import seedu.jimi.model.task.ReadOnlyTask; import seedu.jimi.storage.StorageManager; import seedu.jimi.testutil.TestUtil; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyTaskBook latestSavedTaskBook; private boolean helpShown; private ReadOnlyTask targetedTask; private List<Command> cmdStubList = CommandUtil.getInstance().getCommandStubList(); @Subscribe private void handleLocalModelChangedEvent(TaskBookChangedEvent tbce) { latestSavedTaskBook = new TaskBook(tbce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedTask = je.targetTask; } @Before public void setup() { model = new ModelManager(); String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedTaskBook = new TaskBook(model.getTaskBook()); // last saved assumed to be up to date before. helpShown = false; } @After public void teardown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() throws Exception { String invalidCommand = " "; assertCommandBehavior(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } // @@author A0140133B @Test public void execute_redo_redolimit() throws Exception { setup(); assertCommandBehavior("redo", RedoCommand.COMMAND_WORD.substring(0, 1).toUpperCase() + RedoCommand.COMMAND_WORD.substring(1) + ": " + History.MESSAGE_REACHED_REDO_LIMIT); } // @@author /** * Executes the command and confirms that the result message is correct. * Both the 'address book' and the 'last shown list' are expected to be empty. * @see #assertCommandBehavior(String, String, ReadOnlyTaskBook, List) */ private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception { assertCommandBehavior(inputCommand, expectedMessage, new TaskBook(), Collections.emptyList(), Collections.emptyList()); } /** * Executes the command and confirms that the result message is correct and * also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal address book data are same as those in the {@code expectedAddressBook} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedAddressBook} was saved to the storage file. <br> */ private void assertCommandBehavior(String inputCommand, String expectedMessage, ReadOnlyTaskBook expectedTaskBook, List<? extends ReadOnlyTask> expectedShownTaskList, List<? extends ReadOnlyTask> expectedShownEventList) throws Exception { //Execute the command CommandResult result = logic.execute(inputCommand); //Confirm the ui display elements should contain the right data assertEquals(expectedMessage, result.feedbackToUser); assertEquals(expectedShownTaskList, model.getFilteredAgendaTaskList()); assertEquals(expectedShownEventList, model.getFilteredAgendaEventList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedTaskBook, model.getTaskBook()); assertEquals(expectedTaskBook, latestSavedTaskBook); } private void assertCommandBehavior(String inputCommand, String expectedMessage, ReadOnlyTaskBook expectedTaskBook, List<? extends ReadOnlyTask> expectedShownTaskList, List<? extends ReadOnlyTask> expectedShownEventList, List<? extends ReadOnlyTask> actualShownTaskList, List<? extends ReadOnlyTask> actualShownEventList) throws Exception { //Execute the command CommandResult result = logic.execute(inputCommand); //Confirm the ui display elements should contain the right data assertEquals(expectedMessage, result.feedbackToUser); assertEquals(expectedShownTaskList, actualShownTaskList); assertEquals(expectedShownEventList, actualShownEventList); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedTaskBook, model.getTaskBook()); assertEquals(expectedTaskBook, latestSavedTaskBook); } // @@author A0140133B @Test public void execute_unknownCommandWord() throws Exception { String unknownCommand = "uicfhmowqewca"; assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand)); /* exit and clear should have the user type the full command word for it to be valid */ unknownCommand = "ex"; assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand)); unknownCommand = "exi"; assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand)); unknownCommand = "cl"; assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand)); unknownCommand = "cle"; assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand)); unknownCommand = "clea"; assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand)); } @Test public void execute_help() throws Exception { // testing pop up page assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); helpShown = false; assertCommandBehavior("h", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); helpShown = false; assertCommandBehavior("he", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); helpShown = false; assertCommandBehavior("hel", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); helpShown = false; for (Command c : cmdStubList) { // to account for some commands having no command words e.g. IncorrectCommand if (c.getCommandWord().isEmpty()) { continue; } assertCommandBehavior("help " + c.getCommandWord(), c.getMessageUsage()); assertFalse(helpShown); assertCommandBehavior("h " + c.getCommandWord(), c.getMessageUsage()); assertFalse(helpShown); assertCommandBehavior("he " + c.getCommandWord(), c.getMessageUsage()); assertFalse(helpShown); assertCommandBehavior("hel " + c.getCommandWord(), c.getMessageUsage()); assertFalse(helpShown); } } @Test public void execute_help_unknown_cmd() throws Exception { String invalidCmd = "asdasdasdasd"; String expectedMessage = String.format(MESSAGE_UNKNOWN_COMMAND, invalidCmd); helpShown = false; assertCommandBehavior("help " + invalidCmd, expectedMessage); assertFalse(helpShown); } @Test public void execute_exit() throws Exception { assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateFloatingTask(1)); model.addTask(helper.generateFloatingTask(2)); model.addTask(helper.generateFloatingTask(3)); assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new TaskBook(), Collections.emptyList(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandBehavior( "add \"do dishes\" t/impt t/asd", expectedMessage); assertCommandBehavior( "add \"wash //plates\"", expectedMessage); assertCommandBehavior( "a \"do dishes\" t/impt t/asd", expectedMessage); assertCommandBehavior( "a \"wash //plates\"", expectedMessage); assertCommandBehavior( "ad \"do dishes\" t/impt t/asd", expectedMessage); assertCommandBehavior( "ad \"wash //plates\"", expectedMessage); } @Test public void execute_add_invalidTaskData() throws Exception { assertCommandBehavior( "add \"Valid task\" t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); assertCommandBehavior( "a \"Valid task\" t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); assertCommandBehavior( "ad \"Valid task\" t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); assertCommandBehavior( "add \"Valid task\" t/valid p/invalid", Priority.MESSAGE_PRIORITY_CONSTRAINTS); } // @@author @Test public void execute_addFloatingtask_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); TaskBook expectedAB = new TaskBook(); // execute command and verify result FloatingTask toBeAdded = helper.adam(); expectedAB.addTask(toBeAdded); assertCommandBehavior( helper.generateAddCommand_Ad(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList(), Collections.emptyList()); toBeAdded = helper.homework(); expectedAB.addTask(toBeAdded); assertCommandBehavior( helper.generateAddCommand_A(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList(), Collections.emptyList()); toBeAdded = helper.laundry(); expectedAB.addTask(toBeAdded); assertCommandBehavior( helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList(), Collections.emptyList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); FloatingTask toBeAdded = helper.adam(); TaskBook expectedTB = new TaskBook(); expectedTB.addTask(toBeAdded); // setup starting state model.addTask(toBeAdded); // person already in internal address book // execute command and verify result assertCommandBehavior( helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK, expectedTB, expectedTB.getTaskList(), Collections.emptyList()); assertCommandBehavior( helper.generateAddCommand_A(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK, expectedTB, expectedTB.getTaskList(), Collections.emptyList()); assertCommandBehavior( helper.generateAddCommand_Ad(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK, expectedTB, expectedTB.getTaskList(), Collections.emptyList()); } // @@author A0143471L @Test public void execute_addDeadlineTask_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); DeadlineTask toBeAdded = helper.holiday(); TaskBook expectedTB = new TaskBook(); expectedTB.addTask(toBeAdded); // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedTB, expectedTB.getTaskList(), Collections.emptyList()); toBeAdded = helper.toiletPaper(); expectedTB.addTask(toBeAdded); assertCommandBehavior( helper.generateAddCommand_ad(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedTB, expectedTB.getTaskList(), Collections.emptyList()); toBeAdded = helper.submission(); expectedTB.addTask(toBeAdded); assertCommandBehavior( helper.generateAddCommand_a(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedTB, expectedTB.getTaskList(), Collections.emptyList()); } @Test public void execute_addDeadlineTask_invalid() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandBehavior("add \"Valid deadline task\" tmr", expectedMessage); assertCommandBehavior("add \"Valid deadline task\" to tmr", expectedMessage); assertCommandBehavior("add \"Valid deadline task\" by tmr", expectedMessage); } @Test public void execute_addEvent_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Event toBeAdded = helper.exam(); TaskBook expectedTB = new TaskBook(); expectedTB.addTask(toBeAdded); // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedTB, Collections.emptyList(), expectedTB.getTaskList()); toBeAdded = helper.tuition(); expectedTB.addTask(toBeAdded); assertCommandBehavior( helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedTB, Collections.emptyList(), expectedTB.getTaskList()); toBeAdded = helper.meeting(); expectedTB.addTask(toBeAdded); assertCommandBehavior( helper.generateAddCommand_a(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedTB, Collections.emptyList(), expectedTB.getTaskList()); } // @@author /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandBehavior(commandWord , expectedMessage); //index missing assertCommandBehavior(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandBehavior(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandBehavior(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandBehavior(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<FloatingTask> floatingTaskList = helper.generateFloatingTaskList(2); // set AB state to 2 persons model.resetData(new TaskBook()); for (FloatingTask p : floatingTaskList) { model.addTask(p); } assertCommandBehavior(commandWord + " t3", expectedMessage, model.getTaskBook(), floatingTaskList, Collections.emptyList()); } //@@author A0138915X @Test public void execute_show_showsAllTasksAndEvents() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskBook expectedAB = helper.generateTaskBook(2); List<? extends ReadOnlyTask> expectedTaskList = expectedAB.getTaskList(); List<? extends ReadOnlyTask> expectedEventList = Collections.emptyList(); // prepare address book state helper.addToModel(model, 2); assertCommandBehavior("s all", Command.getMessageForTaskListShownSummary(model.getShownSize()), expectedAB, expectedTaskList, expectedEventList); assertCommandBehavior("sh all", Command.getMessageForTaskListShownSummary(model.getShownSize()), expectedAB, expectedTaskList, expectedEventList); assertCommandBehavior("sho all", Command.getMessageForTaskListShownSummary(model.getShownSize()), expectedAB, expectedTaskList, expectedEventList); assertCommandBehavior("show all", Command.getMessageForTaskListShownSummary(model.getShownSize()), expectedAB, expectedTaskList, expectedEventList); } public void execute_show_showsFloatingTasks() throws Exception { } //@@author /* @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("s", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("se", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("sel", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("sele", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("selec", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); assertIndexNotFoundBehaviorForCommand("s"); assertIndexNotFoundBehaviorForCommand("se"); assertIndexNotFoundBehaviorForCommand("sel"); assertIndexNotFoundBehaviorForCommand("sele"); assertIndexNotFoundBehaviorForCommand("selec"); } @Test public void execute_select_jumpsToCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<FloatingTask> threeFloatingTasks = helper.generateFloatingTaskList(3); TaskBook expectedAB = helper.generateFloatingTaskBook(threeFloatingTasks); helper.addToModel(model, threeFloatingTasks); assertCommandBehavior("select t2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredAgendaTaskList().get(1), threeFloatingTasks.get(1)); assertCommandBehavior("s t1", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 1), expectedAB, expectedAB.getTaskList()); assertEquals(0, targetedJumpIndex); assertEquals(model.getFilteredAgendaTaskList().get(0), threeFloatingTasks.get(0)); assertCommandBehavior("se t2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredAgendaTaskList().get(1), threeFloatingTasks.get(1)); assertCommandBehavior("sel t1", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 1), expectedAB, expectedAB.getTaskList()); assertEquals(0, targetedJumpIndex); assertEquals(model.getFilteredAgendaTaskList().get(0), threeFloatingTasks.get(0)); assertCommandBehavior("sele t2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredAgendaTaskList().get(1), threeFloatingTasks.get(1)); assertCommandBehavior("selec t1", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 1), expectedAB, expectedAB.getTaskList()); assertEquals(0, targetedJumpIndex); assertEquals(model.getFilteredAgendaTaskList().get(0), threeFloatingTasks.get(0)); } */ // @@author A0140133B @Test public void execute_completeInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, CompleteCommand.MESSAGE_USAGE); for (int i = 1; i <= CompleteCommand.COMMAND_WORD.length(); i++) { assertIncorrectIndexFormatBehaviorForCommand(CompleteCommand.COMMAND_WORD.substring(0, i), expectedMessage); } } @Test public void execute_completeIndexNotFound_errorMessageShown() throws Exception { for (int i = 1; i <= CompleteCommand.COMMAND_WORD.length(); i++) { assertIndexNotFoundBehaviorForCommand(CompleteCommand.COMMAND_WORD.substring(0, i)); } } @Test public void execute_completeCorrectly() throws Exception { TestDataHelper helper = new TestDataHelper(); FloatingTask index0 = helper.generateFloatingTaskWithName("first"); FloatingTask index1 = helper.generateFloatingTaskWithName("second"); FloatingTask index2 = helper.generateFloatingTaskWithName("third"); List<FloatingTask> threeFloatingTasks = helper.generateFloatingTaskList(index0, index1, index2); List<FloatingTask> expectedList = helper.generateFloatingTaskList(index1); TaskBook expectedTB = helper.generateFloatingTaskBook(threeFloatingTasks); helper.addToModel(model, threeFloatingTasks); // execute command and verify result assertCommandBehavior("complete t2", String.format(CompleteCommand.MESSAGE_COMPLETE_TASK_SUCCESS, threeFloatingTasks.get(1)), expectedTB, expectedList, Collections.emptyList(), model.getFilteredCompletedTaskList(), Collections.emptyList()); assertTrue(threeFloatingTasks.get(1).isCompleted()); // already completed assertCommandBehavior("complete t1", CompleteCommand.MESSAGE_INVALID_COMPLETION, expectedTB, expectedList, Collections.emptyList(), model.getFilteredCompletedTaskList(), Collections.emptyList()); assertTrue(threeFloatingTasks.get(1).isCompleted()); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("d", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("de", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("del", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("dele", expectedMessage); assertIncorrectIndexFormatBehaviorForCommand("delet", expectedMessage); expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; assertCommandBehavior("delete t3 to t1", MESSAGE_INVALID_TASK_DISPLAYED_INDEX); assertCommandBehavior("delete e1 to t1", MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); assertIndexNotFoundBehaviorForCommand("d"); assertIndexNotFoundBehaviorForCommand("de"); assertIndexNotFoundBehaviorForCommand("del"); assertIndexNotFoundBehaviorForCommand("dele"); assertIndexNotFoundBehaviorForCommand("delet"); } @Test public void execute_delete_removesCorrectPerson() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); FloatingTask index0 = helper.generateFloatingTaskWithName("first"); FloatingTask index1 = helper.generateFloatingTaskWithName("second"); FloatingTask index2 = helper.generateFloatingTaskWithName("third"); List<FloatingTask> threeFloatingTasks = helper.generateFloatingTaskList(index0, index1, index2); List<FloatingTask> expectedList = helper.generateFloatingTaskList(index0, index2); TaskBook expectedTB = helper.generateFloatingTaskBook(expectedList); helper.addToModel(model, threeFloatingTasks); // execute command and verify result assertCommandBehavior("delete t2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, "1. " + threeFloatingTasks.get(1)), expectedTB, expectedTB.getTaskList(), Collections.emptyList()); } @Test public void execute_delete_removesCorrectRange() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); FloatingTask index0 = helper.generateFloatingTaskWithName("first"); FloatingTask index1 = helper.generateFloatingTaskWithName("second"); FloatingTask index2 = helper.generateFloatingTaskWithName("third"); List<FloatingTask> threeFloatingTasks = helper.generateFloatingTaskList(index0, index1, index2); String expectedMsg = String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, "1. " + threeFloatingTasks.get(0) + "\n" + "2. " + threeFloatingTasks.get(1)); List<FloatingTask> expectedList = helper.generateFloatingTaskList(index2); TaskBook expectedTB = helper.generateFloatingTaskBook(expectedList); helper.addToModel(model, threeFloatingTasks); // execute command and verify result assertCommandBehavior("delete t1 to t2", expectedMsg, expectedTB, expectedList, Collections.emptyList()); } //@@ author @Test public void execute_find_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandBehavior("find ", expectedMessage); assertCommandBehavior("f ", expectedMessage); assertCommandBehavior("fi ", expectedMessage); assertCommandBehavior("fin ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); FloatingTask pTarget1 = helper.generateFloatingTaskWithName("bla bla KEY bla"); FloatingTask pTarget2 = helper.generateFloatingTaskWithName("bla KEY bla bceofeia"); FloatingTask p1 = helper.generateFloatingTaskWithName("KE Y"); FloatingTask p2 = helper.generateFloatingTaskWithName("KEYKEYKEY sduauo"); List<FloatingTask> testFloatingTasks = helper.generateFloatingTaskList(pTarget1, pTarget2, p1, p2); TaskBook expectedAB = helper.generateFloatingTaskBook(testFloatingTasks); List<FloatingTask> expectedList = helper.generateFloatingTaskList(pTarget1, pTarget2, p1, p2); helper.addToModel(model, testFloatingTasks); assertCommandBehavior("find \"KEY\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); assertCommandBehavior("fi \"KEY\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); assertCommandBehavior("fin \"KEY\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); assertCommandBehavior("f \"KEY\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); FloatingTask p1 = helper.generateFloatingTaskWithName("bla bla KEY bla"); FloatingTask p2 = helper.generateFloatingTaskWithName("bla KEY bla bceofeia"); FloatingTask p3 = helper.generateFloatingTaskWithName("key key"); FloatingTask p4 = helper.generateFloatingTaskWithName("KEy sduauo"); List<FloatingTask> fourFloatingTasks = helper.generateFloatingTaskList(p1, p2, p3, p4); TaskBook expectedAB = helper.generateFloatingTaskBook(fourFloatingTasks); List<FloatingTask> expectedList = fourFloatingTasks; helper.addToModel(model, fourFloatingTasks); assertCommandBehavior("find \"KEY\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); assertCommandBehavior("fi \"KEY\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); assertCommandBehavior("fin \"KEY\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); assertCommandBehavior("f \"KEY\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); FloatingTask pTarget1 = helper.generateFloatingTaskWithName("bla bla KEY bla"); FloatingTask pTarget2 = helper.generateFloatingTaskWithName("bla rAnDoM bla bceofeia"); FloatingTask pTarget3 = helper.generateFloatingTaskWithName("key key"); FloatingTask p1 = helper.generateFloatingTaskWithName("sduauo"); List<FloatingTask> fourFloatingTasks = helper.generateFloatingTaskList(pTarget1, p1, pTarget2, pTarget3); TaskBook expectedAB = helper.generateFloatingTaskBook(fourFloatingTasks); List<FloatingTask> expectedList = helper.generateFloatingTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourFloatingTasks); assertCommandBehavior("find \"key rAnDoM\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); assertCommandBehavior("f \"key rAnDoM\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); assertCommandBehavior("fi \"key rAnDoM\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); assertCommandBehavior("fin \"key rAnDoM\"", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList, Collections.emptyList()); } // @@author A0143471L @Test public void execute_saveAs_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveAsCommand.MESSAGE_USAGE); assertCommandBehavior("saveas ", expectedMessage); assertCommandBehavior("saveas data/taskbook", expectedMessage); assertCommandBehavior("saveas data/taskbook.txt", expectedMessage); } @Test public void execute_saveAs_successful() throws Exception { SaveAsCommand.setConfigFilePath(TestApp.DEFAULT_CONFIG_FILE_FOR_TESTING); //Access config file used for testing only TestDataHelper helper = new TestDataHelper(); String originalTaskBookFilePathName = TestUtil.getFilePathInSandboxFolder("sampleData.xml"); String newTaskBookFilePathName = TestUtil.getFilePathInSandboxFolder("newSampleData.xml"); Config originalConfig = helper.generateConfigFile(originalTaskBookFilePathName); Config expectedConfig = helper.generateConfigFile(newTaskBookFilePathName); Config currentConfig = ConfigUtil.readConfig(TestApp.DEFAULT_CONFIG_FILE_FOR_TESTING).orElse(new Config()); assertCommandBehavior(helper.generateSaveAsCommand(newTaskBookFilePathName), String.format(SaveAsCommand.MESSAGE_SUCCESS, expectedConfig.getTaskBookFilePath())); currentConfig = ConfigUtil.readConfig(TestApp.DEFAULT_CONFIG_FILE_FOR_TESTING).orElse(new Config()); assertEquals(expectedConfig, currentConfig); assertCommandBehavior(helper.generateSaveAsCommand(originalTaskBookFilePathName), String.format(SaveAsCommand.MESSAGE_SUCCESS, originalConfig.getTaskBookFilePath())); currentConfig = ConfigUtil.readConfig(TestApp.DEFAULT_CONFIG_FILE_FOR_TESTING).orElse(new Config()); assertEquals(originalConfig, currentConfig); } @Test public void execute_saveAs_duplicateNotAllowed() throws Exception { SaveAsCommand.setConfigFilePath(TestApp.DEFAULT_CONFIG_FILE_FOR_TESTING); //Access config file used for testing only TestDataHelper helper = new TestDataHelper(); String originalTaskBookFilePathName = TestUtil.getFilePathInSandboxFolder("sampleData.xml"); String expectedMessage = String.format(SaveAsCommand.MESSAGE_DUPLICATE_SAVE_DIRECTORY); assertCommandBehavior(helper.generateSaveAsCommand(originalTaskBookFilePathName), expectedMessage); } // @@author /** * A utility class to generate test data. */ class TestDataHelper { FloatingTask adam() throws Exception { Name name = new Name("Adam Brown"); Tag tag1 = new Tag("tag1"); UniqueTagList tags = new UniqueTagList(tag1); Priority priority = new Priority("HIGH"); return new FloatingTask(name, tags, priority); } FloatingTask laundry() throws Exception { Name name = new Name("laundry"); Tag tag1 = new Tag("dothem"); UniqueTagList tags = new UniqueTagList(tag1); Priority priority = new Priority("MED"); return new FloatingTask(name, tags, priority); } FloatingTask homework() throws Exception { Name name = new Name("homework"); Tag tag1 = new Tag("impt"); UniqueTagList tags = new UniqueTagList(tag1); Priority priority = new Priority("LOW"); return new FloatingTask(name, tags, priority); } // @@author A0143471L DeadlineTask submission() throws Exception { Name name = new Name("Submission"); DateTime deadline = new DateTime("2016-11-02 21:00"); Tag tag = new Tag("impt"); UniqueTagList tags = new UniqueTagList(tag); Priority priority = new Priority ("HIGH"); return new DeadlineTask(name, deadline, tags, priority); } DeadlineTask holiday() throws Exception { Name name = new Name("Plan holiday itinerary"); DateTime deadline = new DateTime("2016-10-31 19:00"); Tag tag = new Tag("Japan"); UniqueTagList tags = new UniqueTagList(tag); Priority priority = new Priority ("LOW"); return new DeadlineTask(name, deadline, tags, priority); } DeadlineTask toiletPaper() throws Exception { Name name = new Name("Buy toilet paper"); DateTime deadline = new DateTime("2016-11-01 18:00"); Tag tag = new Tag("Necessities"); UniqueTagList tags = new UniqueTagList(tag); Priority priority = new Priority ("MED"); return new DeadlineTask(name, deadline, tags, priority); } Event tuition() throws Exception { Name name = new Name ("Math tuition"); DateTime start = new DateTime("2016-12-05 19:00"); DateTime end = new DateTime("2016-12-05 21:00"); UniqueTagList tags = new UniqueTagList(); // No tags Priority priority = new Priority ("MED"); return new Event(name, start, end, tags, priority); } Event exam() throws Exception { Name name = new Name ("Practical exam"); DateTime start = new DateTime("2016-12-01 18:00"); DateTime end = new DateTime("2016-12-01 21:00"); Tag tag = new Tag("Programming"); UniqueTagList tags = new UniqueTagList(tag); Priority priority = new Priority ("HIGH"); return new Event(name, start, end, tags, priority); } Event meeting() throws Exception { Name name = new Name ("Committee meeting"); DateTime start = new DateTime("2016-12-08 09:00"); DateTime end = new DateTime("2016-12-08 11:00"); Tag tag = new Tag("School"); UniqueTagList tags = new UniqueTagList(tag); Priority priority = new Priority ("HIGH"); return new Event(name, start, end, tags, priority); } // @@author /** * Generates a valid person using the given seed. * Running this function with the same parameter values guarantees the returned person will have the same state. * Each unique seed will generate a unique FloatingTask object. * * @param seed used to generate the person data field values */ FloatingTask generateFloatingTask(int seed) throws Exception { return new FloatingTask( new Name("FloatingTask " + seed), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))), new Priority("MED") ); } // @@author A0140133B /** Generates the correct add command based on the person given */ String generateAddCommand(FloatingTask p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append("\""); cmd.append(p.getName().toString()); cmd.append("\""); UniqueTagList tags = p.getTags(); for (Tag t : tags) { cmd.append(" t/").append(t.tagName); cmd.append(" p/"); cmd.append(p.getPriority().tagName); } return cmd.toString(); } String generateAddCommand_A(FloatingTask p) { StringBuffer cmd = new StringBuffer(); cmd.append("a "); cmd.append("\""); cmd.append(p.getName().toString()); cmd.append("\""); UniqueTagList tags = p.getTags(); for (Tag t : tags) { cmd.append(" t/").append(t.tagName); } cmd.append(" p/").append(p.getPriority().tagName); return cmd.toString(); } String generateAddCommand_Ad(FloatingTask p) { StringBuffer cmd = new StringBuffer(); cmd.append("ad "); cmd.append("\""); cmd.append(p.getName().toString()); cmd.append("\""); UniqueTagList tags = p.getTags(); for (Tag t : tags) { cmd.append(" t/").append(t.tagName); cmd.append(" p/").append(p.getPriority().tagName); } return cmd.toString(); } // @@author // @@author A0143471L String generateAddCommand(DeadlineTask dt) { StringBuffer cmd = new StringBuffer(); cmd.append("add ") .append("\"") .append(dt.getName()) .append("\" due ") .append(dt.getDeadline().getDate() + " ") .append(dt.getDeadline().getTime()); UniqueTagList tags = dt.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } cmd.append(" p/").append(dt.getPriority().tagName); return cmd.toString(); } String generateAddCommand_ad(DeadlineTask dt) { StringBuffer cmd = new StringBuffer(); cmd.append("ad ") .append("\"") .append(dt.getName()) .append("\" due ") .append(dt.getDeadline().getDate() + " ") .append(dt.getDeadline().getTime()); UniqueTagList tags = dt.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } cmd.append(" p/").append(dt.getPriority().tagName); return cmd.toString(); } String generateAddCommand_a(DeadlineTask dt) { StringBuffer cmd = new StringBuffer(); cmd.append("a ") .append("\"") .append(dt.getName()) .append("\" due ") .append(dt.getDeadline().getDate() + " ") .append(dt.getDeadline().getTime()); UniqueTagList tags = dt.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } cmd.append(" p/").append(dt.getPriority().tagName); return cmd.toString(); } String generateAddCommand(Event e) { StringBuffer cmd = new StringBuffer(); cmd.append("add ") .append("\"") .append(e.getName()) .append("\" on ") .append(e.getStart()) .append(" to ") .append(e.getEnd()); UniqueTagList tags = e.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } cmd.append(" p/").append(e.getPriority().tagName); return cmd.toString(); } String generateAddCommand_ad(Event e) { StringBuffer cmd = new StringBuffer(); cmd.append("ad ") .append("\"") .append(e.getName()) .append("\" from ") .append(e.getStart()) .append(" to ") .append(e.getEnd()); UniqueTagList tags = e.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } cmd.append(" p/").append(e.getPriority().tagName); return cmd.toString(); } String generateAddCommand_a(Event e) { StringBuffer cmd = new StringBuffer(); cmd.append("a ") .append("\"") .append(e.getName()) .append("\" from ") .append(e.getStart()) .append(" to ") .append(e.getEnd()); UniqueTagList tags = e.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } cmd.append(" p/").append(e.getPriority().tagName); return cmd.toString(); } // @@author /** * Generates an TaskBook with auto-generated persons. */ TaskBook generateTaskBook(int numGenerated) throws Exception{ TaskBook taskBook = new TaskBook(); addToTaskBook(taskBook, numGenerated); return taskBook; } /** * Generates an TaskBook based on the list of Persons given. */ TaskBook generateFloatingTaskBook(List<FloatingTask> floatingTasks) throws Exception{ TaskBook taskBook = new TaskBook(); addToFloatingTaskBook(taskBook, floatingTasks); return taskBook; } /** * Adds auto-generated FloatingTask objects to the given TaskBook * @param taskBook The TaskBook to which the Persons will be added */ void addToTaskBook(TaskBook taskBook, int numGenerated) throws Exception{ addToFloatingTaskBook(taskBook, generateFloatingTaskList(numGenerated)); } /** * Adds the given list of Persons to the given TaskBook */ void addToFloatingTaskBook(TaskBook taskBook, List<FloatingTask> floatingTasksToAdd) throws Exception{ for(FloatingTask p: floatingTasksToAdd){ taskBook.addTask(p); } } /** * Adds auto-generated FloatingTask objects to the given model * @param model The model to which the Persons will be added */ void addToModel(Model model, int numGenerated) throws Exception{ addToModel(model, generateFloatingTaskList(numGenerated)); } /** * Adds the given list of Persons to the given model */ void addToModel(Model model, List<FloatingTask> floatingTasksToAdd) throws Exception{ for (FloatingTask p : floatingTasksToAdd) { model.addTask(p); } } /** * Generates a list of FloatingTasks based on the flags. */ List<FloatingTask> generateFloatingTaskList(int numGenerated) throws Exception{ List<FloatingTask> floatingTasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { floatingTasks.add(generateFloatingTask(i)); } return floatingTasks; } List<FloatingTask> generateFloatingTaskList(FloatingTask... persons) { return Arrays.asList(persons); } /** * Generates a FloatingTask object with given name. Other fields will have some dummy values. */ FloatingTask generateFloatingTaskWithName(String name) throws Exception { return new FloatingTask( new Name(name), new UniqueTagList(new Tag("tag")), new Priority("MED") ); } /** * Generates the correct saveAs command based on the filepath given **/ String generateSaveAsCommand(String taskBookFilePathName) { StringBuffer cmd = new StringBuffer(); cmd.append("saveas "); cmd.append(taskBookFilePathName); return cmd.toString(); } /** * Generates a config file with the given task book file path name. Other fields will have some dummy values. */ Config generateConfigFile(String taskBookFilePathName) throws Exception { Config config = new Config(); config.setTaskBookFilePath(taskBookFilePathName); return config; } } }
package org.apache.commons.collections; import junit.framework.*; import java.io.IOException; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.Collection; import java.util.Set; import java.util.Iterator; import java.util.HashSet; import java.util.NoSuchElementException; /** * Tests base {@link java.util.Map} methods and contracts. * <p> * If your class implements the full Map interface, including optional * operations, simply extend this class, and implement the {@link * #makeEmptyMap()} method. * <p> * If your {@link Map} fails one of these tests by design, you may still use * this base set of cases. Simply override the test case (method) your {@link * Map} fails and/or the methods that define the assumptions used by the test * cases. For example, if your map does not allow duplicate values, override * {@link useDuplicateValues()} and have it return <code>false</code> * * @author Michael Smith * @author Rodney Waldhoff * @version $Id: TestMap.java,v 1.9 2002/02/22 06:16:35 morgand Exp $ */ public abstract class TestMap extends TestObject { public TestMap(String testName) { super(testName); } /** * Override if your map does not allow a <code>null</code> key. The * default implementation returns <code>true</code> **/ public boolean useNullKey() { return true; } /** * Override if your map does not allow <code>null</code> values. The * default implementation returns <code>true</code>. **/ public boolean useNullValue() { return true; } /** * Override if your map does not allow duplicate values. The default * implementation returns <code>true</code>. **/ public boolean useDuplicateValues() { return true; } /** * Override if your map allows its mappings to be changed to new values. * The default implementation returns <code>true</code>. **/ public boolean isChangeable() { return true; } /** * Override if your map does not allow add/remove modifications. The * default implementation returns <code>true</code>. **/ public boolean isAddRemoveModifiable() { return true; } /** * Returns the set of keys in the mappings used to test the map. This * method must return an array with the same length as {@link * #getSampleValues()} and all array elements must be different. The * default implementation constructs a set of String keys, and includes a * single null key if {@link #useNullKey()} returns <code>true</code>. **/ public Object[] getSampleKeys() { Object[] result = new Object[] { "blah", "foo", "bar", "baz", "tmp", "gosh", "golly", "gee", "hello", "goodbye", "we'll", "see", "you", "all", "again", "key", "key2", (useNullKey()) ? null : "nonnullkey" }; return result; } /** * Returns the set of values in the mappings used to test the map. This * method must return an array with the same length as {@link * #getSampleKeys()}. The default implementation contructs a set of * String values and includes a single null value if {@link * #useNullValue()} returns <code>true</code>, and includes two values * that are the same if {@link #useDuplicateValues()} returns * <code>true</code>. **/ public Object[] getSampleValues() { Object[] result = new Object[] { "blahv", "foov", "barv", "bazv", "tmpv", "goshv", "gollyv", "geev", "hellov", "goodbyev", "we'llv", "seev", "youv", "allv", "againv", (useNullValue()) ? null : "nonnullvalue", "value", (useDuplicateValues()) ? "value" : "value2", }; return result; } /** * Returns a the set of values that can be used to replace the values * returned from {@link #getSampleValues()}. This method must return an * array with the same length as {@link #getSampleValues()}. The values * returned from this method should not be the same as those returned from * {@link #getSampleValues()}. The default implementation constructs a * set of String values and includes a single null value if {@link * #useNullValue()} returns <code>true</code>, and includes two values * that are the same if {@link #useDuplicateValues()} returns * <code>true</code>. **/ public Object[] getNewSampleValues() { Object[] result = new Object[] { (useNullValue()) ? null : "newnonnullvalue", "newvalue", (useDuplicateValues()) ? "newvalue" : "newvalue2", "newblahv", "newfoov", "newbarv", "newbazv", "newtmpv", "newgoshv", "newgollyv", "newgeev", "newhellov", "newgoodbyev", "newwe'llv", "newseev", "newyouv", "newallv", "newagainv", }; return result; } /** * Helper method to add all the mappings described by {@link * #getSampleKeys()} and {@link #getSampleValues()}. **/ public void addSampleMappings(Map m) { Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); for(int i = 0; i < keys.length; i++) { try { m.put(keys[i], values[i]); } catch (NullPointerException exception) { assertTrue("NullPointerException only allowed to be thrown " + "if either the key or value is null.", keys[i] == null || values[i] == null); assertTrue("NullPointerException on null key, but " + "useNullKey is not overridden to return false.", keys[i] == null || !useNullKey()); assertTrue("NullPointerException on null value, but " + "useNullValue is not overridden to return false.", values[i] == null || !useNullValue()); assertTrue("Unknown reason for NullPointer.", false); } } assertEquals("size must reflect number of mappings added.", keys.length, m.size()); } /** * Return a new, empty {@link Map} to be used for testing. */ public abstract Map makeEmptyMap(); /** * Return a new, populated map. The mappings in the map should match the * keys and values returned from {@linke #getSampleKeys()} and {@link * #getSampleValues()}. The default implementation uses makeEmptyMap() * and calls {@link #addSampleMappings()} to add all the mappings to the * map. **/ public Map makeFullMap() { Map m = makeEmptyMap(); addSampleMappings(m); return m; } public Object makeObject() { return makeEmptyMap(); } /** * Test to ensure the test setup is working properly. This method checks * to ensure that the getSampleKeys and getSampleValues methods are * returning results that look appropriate. That is, they both return a * non-null array of equal length. The keys array must not have any * duplicate values, and may only contain a (single) null key if * useNullKey() returns true. The values array must only have a null * value if useNullValue() is true and may only have duplicate values if * useDuplicateValues() returns true. **/ public void testSampleMappings() { Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); Object[] newValues = getNewSampleValues(); assertTrue("failure in test: Must have keys returned from " + "getSampleKeys.", keys != null); assertTrue("failure in test: Must have values returned from " + "getSampleValues.", values != null); // verify keys and values have equivalent lengths (in case getSampleX are // overridden) assertEquals("failure in test: not the same number of sample " + "keys and values.", keys.length, values.length); assertEquals("failure in test: not the same number of values and new values.", values.length, newValues.length); // verify there aren't duplicate keys, and check values for(int i = 0; i < keys.length - 1; i++) { for(int j = i + 1; j < keys.length; j++) { assertTrue("failure in test: duplicate null keys.", (keys[i] != null || keys[j] != null)); assertTrue("failure in test: duplicate non-null key.", (keys[i] == null || keys[j] == null || (!keys[i].equals(keys[j]) && !keys[j].equals(keys[i])))); } assertTrue("failure in test: found null key, but useNullKey " + "is false.", keys[i] != null || useNullKey()); assertTrue("failure in test: found null value, but useNullValue " + "is false.", values[i] != null || useNullValue()); assertTrue("failure in test: found null new value, but useNullValue " + "is false.", newValues[i] != null || useNullValue()); assertTrue("failure in test: values should not be the same as new value", values[i] != newValues[i] && (values[i] == null || !values[i].equals(newValues[i]))); } } // tests begin here. Each test adds a little bit of tested functionality. // Many methods assume previous methods passed. That is, they do not // exhaustively recheck things that have already been checked in a previous // test methods. /** * Test to ensure that makeEmptyMap and makeFull returns a new non-null * map with each invocation. **/ public void testMakeMap() { Map em = makeEmptyMap(); assertTrue("failure in test: makeEmptyMap must return a non-null map.", em != null); Map em2 = makeEmptyMap(); assertTrue("failure in test: makeEmptyMap must return a non-null map.", em != null); assertTrue("failure in test: makeEmptyMap must return a new map " + "with each invocation.", em != em2); Map fm = makeFullMap(); assertTrue("failure in test: makeFullMap must return a non-null map.", fm != null); Map fm2 = makeFullMap(); assertTrue("failure in test: makeFullMap must return a non-null map.", fm != null); assertTrue("failure in test: makeFullMap must return a new map " + "with each invocation.", fm != fm2); } /** * Tests Map.isEmpty() **/ public void testIsEmpty() { Map em = makeEmptyMap(); assertEquals("Map.isEmpty() should return true with an empty map", true, em.isEmpty()); Map fm = makeFullMap(); assertEquals("Map.isEmpty() should return false with a non-empty map", false, fm.isEmpty()); } /** * Tests Map.size() **/ public void testSize() { Map em = makeEmptyMap(); assertEquals("Map.size() should be 0 with an empty map", 0, em.size()); Map fm = makeFullMap(); assertEquals("Map.size() should equal the number of entries in the map", getSampleKeys().length, fm.size()); } /** * Tests {@link Map#clear()}. If the map {@link #isAddRemoveModifiable() * can add and remove elements}, then {@link Map#size()} and {@link * Map#isEmpty()} are used to ensure that map has no elements after a call * to clear. If the map does not support adding and removing elements, * this method checks to ensure clear throws an * UnsupportedOperationException. This method checks that the both maps * returned by makeEmptyMap and makeFullMap have correct behavior. **/ public void testClear() { Map em = makeEmptyMap(); try { em.clear(); assertTrue("Map must throw UnsupportedOperationException if the " + "map does not support removing elements", isAddRemoveModifiable()); assertEquals("size() must return zero after clear.", 0, em.size()); assertEquals("isEmpty() must return true after clear.", true, em.isEmpty()); } catch (UnsupportedOperationException exception) { assertTrue("Map must not throw UnsupportedOperationException if the " + "map supports removing elements", !isAddRemoveModifiable()); } Map fm = makeFullMap(); try { fm.clear(); assertTrue("Map must throw UnsupportedOperationException if the " + "map does not support removing elements", isAddRemoveModifiable()); assertEquals("size() must return zero after clear.", 0, fm.size()); assertEquals("isEmpty() must return true after clear.", true, fm.isEmpty()); } catch (UnsupportedOperationException exception) { assertTrue("Map must not throw UnsupportedOperationException if the " + "map supports removing elements", !isAddRemoveModifiable()); } } /** * Tests: * <ul> * <li> Map.entrySet().isEmpty() * <li> Map.entrySet().size() * </ul> **/ public void testEntrySetIsEmpty() { Map em = makeEmptyMap(); Set es = em.entrySet(); assertEquals("entrySet() must return an empty set when map is empty.", em.isEmpty(), es.isEmpty()); assertEquals("entrySet() must return a set with the same size as " + "the map.", em.size(), es.size()); Map fm = makeEmptyMap(); Set fs = fm.entrySet(); assertEquals("entrySet() must return a non-empty set when map is not empty.", fm.isEmpty(), fs.isEmpty()); assertEquals("entrySet() must return a set with the same size as " + "the map.", fm.size(), fs.size()); } /** * Tests Map.containsKey(Object) by verifying it returns false for all * sample keys on a map created using makeEmptyMap() and returns true for * all sample keys returned on a map created using makeFullMap() **/ public void testContainsKey() { Object[] keys = getSampleKeys(); Map em = makeEmptyMap(); for(int i = 0; i < keys.length; i++) { assertTrue("Map must not contain key when map is empty", !em.containsKey(keys[i])); } Map fm = makeFullMap(); for(int i = 0; i < keys.length; i++) { assertTrue("Map must contain key for a mapping in the map.", fm.containsKey(keys[i])); } } /** * Tests Map.containsValue(Object) by verifying it returns false for all * sample alues on a map created using makeEmptyMap() and returns true for * all sample values returned on a map created using makeFullMap. **/ public void testContainsValue() { Object[] values = getSampleValues(); Map em = makeEmptyMap(); for(int i = 0; i < values.length; i++) { assertTrue("Empty map must not contain value", !em.containsValue(values[i])); } Map fm = makeFullMap(); for(int i = 0; i < values.length; i++) { assertTrue("Map must contain value for a mapping in the map.", fm.containsValue(values[i])); } } /** * Test to ensure that Map.entrySet() returns a non-null set. **/ public void testEntrySet() { Map em = makeEmptyMap(); Set es = em.entrySet(); assertTrue("entrySet() must return a non-null set.", es != null); Map fm = makeEmptyMap(); Set fs = fm.entrySet(); assertTrue("entrySet() must return a non-null set.", fs != null); } /** * Tests: * <ul> * <li> Map.entrySet().contains(Object) * <li> Map.entrySet().containsAll(Collection) * </ul> * * Note: This test relies on a working commons.collections.DefaultMapEntry class. **/ public void testEntrySetContainsProperMappings() { Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); Map.Entry[] entries = new Map.Entry[keys.length]; HashSet mappings = new HashSet(); for(int i = 0; i < keys.length; i++) { entries[i] = new DefaultMapEntry(keys[i], values[i]); mappings.add(entries[i]); } // test an empty map Map em = makeEmptyMap(); Set es = em.entrySet(); for(int i = 0; i < keys.length; i++) { assertEquals("entrySet().contains(Object) must return false when map " + "is empty", false, es.contains(entries[i])); } assertEquals("entrySet().containsAll(Collection) must return false when the " + "map is empty", false, es.containsAll(mappings)); Map fm = makeFullMap(); Set fs = fm.entrySet(); for(int i = 0; i < keys.length; i++) { assertEquals("entrySet().contains(Object) must return true when map " + "contains the mapping", true, fs.contains(entries[i])); } assertEquals("entrySet().containsAll(Collection) must return true when the " + "map contains the mapping", true, fs.containsAll(mappings)); try { es.containsAll((Collection)null); fail("entrySet().containsAll(null) should " + "throw a NullPointerException"); } catch (NullPointerException exception) { // expected } try { fs.containsAll((Collection)null); fail("entrySet().containsAll(null) should " + "throw a NullPointerException"); } catch (NullPointerException exception) { // expected } } // TODO: test entrySet().clear() // TODO: test entrySet().add() throws OperationNotSupported // TODO: test entrySet().addAll() throws OperationNotSupported // TODO: test entrySet().contains(Object) // TODO: test entrySet().containsAll(Collection) // TODO: test entrySet().equals(Object) // TODO: test entrySet().hashCode() // TODO: test entrySet().toArray() // TODO: test entrySet().toArray(Object[] a) // TODO: test entrySet().remove(Object) // TODO: test entrySet().removeAll(Collection) // TODO: test entrySet().retainAll(Collection) /** * Tests: * <ul> * <li> Map.entrySet().iterator() * <li> Map.entrySet().iterator().hasNext() * <li> Map.entrySet().iterator().next() * </ul> **/ public void testEntrySetIterator() { Map em = makeEmptyMap(); Set es = em.entrySet(); Iterator eiter = es.iterator(); assertEquals("entrySet().iterator().hasNext() must return false " + "when then the map is empty.", false, eiter.hasNext()); // note: we make a new map to test for this because some impls in the // past have required a call to hasMoreElements before a call to next // for it to work properly. By using a new map, we make sure this test // will catch those broken impls. em = makeEmptyMap(); es = em.entrySet(); eiter = es.iterator(); try { eiter.next(); fail("entrySet().iterator().next() must throw a NoSuchElementException " + "when the map is empty"); } catch (NoSuchElementException exception) { // expected } Map fm = makeFullMap(); Set fs = fm.entrySet(); Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); boolean[] found = new boolean[keys.length]; Iterator iter = fs.iterator(); assertTrue("entrySet().iterator() must return a non-null " + "iterator.", iter != null); while(iter.hasNext()) { Object obj = iter.next(); assertTrue("Null is not allowed to be returned from the " + "entrySet().iterator()'s next().", obj != null); assertTrue("Objects returned from entrySet().iterator() must be " + "instances of Map.Entry.", obj instanceof Map.Entry); Map.Entry entry = (Map.Entry)obj; Object key = entry.getKey(); Object value = entry.getValue(); assertTrue("the key for an entry returned from the entry " + "set's iterator can only be null if useNullKey " + "is true.", key != null || (key == null && useNullKey())); assertTrue("the value for an entry returned from the entry " + "set's iterator can only be null if useNullValue " + "is true.", value != null || (value == null && useNullValue())); for(int i = 0; i < keys.length; i++) { if((key == null && keys[i] == null) || (key != null && key.equals(keys[i]))) { assertTrue("entrySet().iterator() must not return " + "multiple entries with the same key.", !found[i]); found[i] = true; assertTrue ("value of entry returned from iterator " + "must be the value for the added mapping.", (value == null && values[i] == null) || (value != null && value.equals(values[i]))); } } } for(int i = 0; i < found.length; i++) { assertTrue("must find all added elements through entrySet's " + "iterator().", found[i]); } } /** * Tests Map.entrySet().iterator().remove() **/ public void testEntrySetIteratorRemove() { Map m = makeFullMap(); Set s = m.entrySet(); Iterator iter = s.iterator(); try { iter.remove(); fail("Entry set iterator must not allow a call to remove " + "before any calls to next"); } catch (IllegalStateException exception) { // expected exception provided add/remove modifiable assertTrue("iterator should throw UnsupportedOperationException " + "if remove is not allowed from the entrySet().iterator()", isAddRemoveModifiable()); } catch (UnsupportedOperationException exception) { assertTrue("iterator should not throw UnsupportedOperationException " + "if the map supports adding and removing elements", !isAddRemoveModifiable()); } while(iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); assertTrue("Entry key from entry set iterator must exist in map", m.containsKey(entry.getKey())); try { iter.remove(); // note: we do not check that the mapping was actually removed // from the map because some classes do not have their // entrySet().iterator() backed by the map. That test occurs // below in testEntrySetIteratorRemoveCausesMapModification } catch (UnsupportedOperationException exception) { assertTrue("iterator should not throw UnsupportedOperationException " + "if the map supports adding and removing elements", !isAddRemoveModifiable()); } try { iter.remove(); fail("Entry set iterator must not allow two calls to " + "remove without a call to next."); } catch (IllegalStateException exception) { // expected exception provided add/remove modifiable assertTrue("iterator should throw UnsupportedOperationException " + "if remove is not allowed from the entrySet().iterator()", isAddRemoveModifiable()); } catch (UnsupportedOperationException exception) { assertTrue("iterator should not throw UnsupportedOperationException " + "if the map supports adding and removing elements", !isAddRemoveModifiable()); } } } /** * Tests whether the map's entrySet() is backed by the map by making sure * a put in the map is reflected in the entrySet. This test does nothing * if add/remove modifications are not supported. **/ public void testEntrySetChangesWithMapPut() { if(!isAddRemoveModifiable()) return; Map m = makeEmptyMap(); // test insert reflected in entry set Set s = m.entrySet(); addSampleMappings(m); assertEquals("entrySet() must only be empty if map is empty.", m.isEmpty(), s.isEmpty()); assertEquals("entrySet() must adjust size when map changes.", m.size(), s.size()); // TODO: test set and map reflect the same contents } /** * Tests whether the map's entrySet() is backed by the map by making sure * a remove from the map is reflected in the entrySet. This test does nothing * if add/remove modifications are not supported. **/ public void testEntrySetChangesWithMapRemove() { if(!isAddRemoveModifiable()) return; Map m = makeFullMap(); Set s = m.entrySet(); Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); for(int i = 0; i < keys.length; i++) { m.remove(keys[i]); assertEquals("entrySet() must only be empty if map is empty.", m.isEmpty(), s.isEmpty()); assertEquals("entrySet() must adjust size when map changes.", m.size(), s.size()); //TODO: test set and map reflect the same contents } } // TODO: test entrySet() changes after Map.remove // TODO: test entrySet() changes after Map.clear // TODO: test entrySet() changes after Map.putAll /** * Tests whether the map's entrySet() is backed by the map by making sure * a remove from the entrySet's iterator is reflected in the map. This * test does nothing if add/remove modifications are not supported. **/ public void testEntrySetIteratorRemoveCausesMapModification() { if(!isAddRemoveModifiable()) return; Map m = makeFullMap(); Set s = m.entrySet(); Iterator iter = s.iterator(); while(iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); try { iter.remove(); assertTrue("Entry key from entry set iterator must " + "no longer exist in map", !m.containsKey(entry.getKey())); } catch (UnsupportedOperationException exception) { // isAddRemoveModifiable is true -- we've checked that above fail("iterator should not throw UnsupportedOperationException " + "if the map supports adding and removing elements"); } } } // TODO: test map changes after entrySet().remove // TODO: test map changes after entrySet().removeAll // TODO: test map changes after entrySet().retainAll public void testMapEquals() { // XXX finish me } public void testMapGet() { // XXX finish me } public void testMapHashCode() { // XXX finish me } public void testMapKeySet() { // XXX finish me } public void testMapSupportsNullValues() { if ((this instanceof TestMap.SupportsPut) == false) { return; } Map map = makeEmptyMap(); map.put(new Integer(1),"foo"); assertTrue("no null values in Map",map.containsValue(null) == false); map.put(new Integer(2),null); assertTrue("null value in Map",map.containsValue(null)); assertTrue("key to a null value",map.containsKey(new Integer(2))); } public void testMultiplePuts() { if ((this instanceof TestMap.SupportsPut) == false) { return; } Map map = makeEmptyMap(); map.put(new Integer(4),"foo"); map.put(new Integer(4),"bar"); map.put(new Integer(4),"foo"); map.put(new Integer(4),"bar"); assertTrue("same key different value",map.get(new Integer(4)).equals("bar")); } public void testCapacity() { if ((this instanceof TestMap.SupportsPut) == false) { return; } Map map = makeEmptyMap(); map.put(new Integer(1),"foo"); map.put(new Integer(2),"foo"); map.put(new Integer(3),"foo"); map.put(new Integer(1),"foo"); assertTrue("size of Map should be 3, but was " + map.size(), map.size() == 3); } public void testEntrySetRemove() { if ((this instanceof TestMap.EntrySetSupportsRemove) == false || (this instanceof TestMap.SupportsPut) == false) { return; } Map map = makeEmptyMap(); map.put("1","1"); map.put("2","2"); map.put("3","3"); Object o = map.entrySet().iterator().next(); // remove one of the key/value pairs Set set = map.entrySet(); set.remove(o); assertTrue(set.size() == 2); // try to remove it again, to make sure // the Set is not confused by missing entries set.remove(o); assertTrue("size of Map should be 2, but was " + map.size(), map.size() == 2); } public void testEntrySetContains() { if ((this instanceof TestMap.SupportsPut) == false) { return; } Map map = makeEmptyMap(); map.put("1","1"); map.put("2","2"); map.put("3","3"); Set set = map.entrySet(); Object o = set.iterator().next(); assertTrue("entry set should contain valid element",set.contains(o)); // create a fresh entry mapped to existing values DefaultMapEntry goodEntry = new DefaultMapEntry("2","2"); assertTrue("entry set should recognize externally constructed MapEntry objects", set.contains(goodEntry)); // make a bogus entry DefaultMapEntry badEntry = new DefaultMapEntry("4","4"); assertTrue("entry set should not contain a bogus element", set.contains(badEntry) == false); } public void testEmptyMapSerialization() throws IOException, ClassNotFoundException { Map map = makeEmptyMap(); if (!(map instanceof Serializable)) return; byte[] objekt = writeExternalFormToBytes((Serializable) map); Map map2 = (Map) readExternalFormFromBytes(objekt); assertTrue("Both maps are empty",map.isEmpty() == true); assertTrue("Both maps are empty",map2.isEmpty() == true); } public void testFullMapSerialization() throws IOException, ClassNotFoundException { Map map = makeFullMap(); if (!(map instanceof Serializable)) return; byte[] objekt = writeExternalFormToBytes((Serializable) map); Map map2 = (Map) readExternalFormFromBytes(objekt); assertEquals("Both maps are same size",map.size(), getSampleKeys().length); assertEquals("Both maps are same size",map2.size(),getSampleKeys().length); } /** * Marker interface, indicating that a TestMap subclass * can test put(Object,Object) operations. */ public interface SupportsPut { } public interface EntrySetSupportsRemove { } }
package org.jdesktop.swingx; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.KeyboardFocusManager; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.DefaultListSelectionModel; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import org.jdesktop.swingx.JXTableHeader.SortGestureRecognizer; import org.jdesktop.swingx.decorator.AlternateRowHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.ConditionalHighlighter; import org.jdesktop.swingx.decorator.Filter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterPipeline; import org.jdesktop.swingx.decorator.PatternFilter; import org.jdesktop.swingx.decorator.PatternHighlighter; import org.jdesktop.swingx.decorator.RolloverHighlighter; import org.jdesktop.swingx.decorator.ShuttleSorter; import org.jdesktop.swingx.decorator.AlternateRowHighlighter.UIAlternateRowHighlighter; import org.jdesktop.swingx.table.ColumnHeaderRenderer; import org.jdesktop.swingx.table.DefaultTableColumnModelExt; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.util.AncientSwingTeam; /** * Split from old JXTableUnitTest - contains "interactive" * methods only. * * @author Jeanette Winzenburg */ public class JXTableVisualCheck extends JXTableUnitTest { private static final Logger LOG = Logger.getLogger(JXTableVisualCheck.class .getName()); public static void main(String args[]) { JXTableVisualCheck test = new JXTableVisualCheck(); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactive.*ColumnControl.*"); // test.runInteractiveTests("interactive.*TableHeader.*"); // test.runInteractiveTests("interactive.*Multiple.*"); // test.runInteractiveTests("interactive.*RToL.*"); // test.runInteractiveTests("interactive.*Boolean.*"); test.runInteractiveTests("interactive.*Sort.*"); // test.runInteractiveTests("interactive.*Column.*"); test.runInteractiveTests("interactive.*Header.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @Override protected void setUp() throws Exception { super.setUp(); // super has LF specific tests... setSystemLF(true); } /** * Issue #271-swingx: make sort triggering mouseEvents * customizable. * * added SortGestureRecognizer. * */ public void interactiveSortGestureRecognizer() { final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, "Sort Gesture customization"); Action action = new AbstractAction("toggle default/custom recognizer") { boolean hasCustom; public void actionPerformed(ActionEvent e) { SortGestureRecognizer recognizer = null; if (!hasCustom) { hasCustom = !hasCustom; recognizer = new SortGestureRecognizer() { /** * allow double clicks to trigger a sort. */ @Override public boolean isSortOrderGesture(MouseEvent e) { return e.getClickCount() <= 2; } /** * Disable reset gesture. */ @Override public boolean isResetSortOrderGesture(MouseEvent e) { return false; } /** * ignore modifiers. */ @Override public boolean isToggleSortOrderGesture(MouseEvent e) { return isSortOrderGesture(e); } }; } ((JXTableHeader) table.getTableHeader()).setSortGestureRecognizer(recognizer); } }; addAction(frame, action); frame.setVisible(true); } /** * Issue #281-swingx: header should be auto-repainted on changes to * header title, value. * * */ public void interactiveUpdateHeader() { final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, "update header"); Action action = new AbstractAction("update headervalue") { int count; public void actionPerformed(ActionEvent e) { table.getColumn(0).setHeaderValue("A" + count++); } }; addAction(frame, action); action = new AbstractAction("update column title") { int count; public void actionPerformed(ActionEvent e) { table.getColumnExt(0).setTitle("A" + count++); } }; addAction(frame, action); frame.setVisible(true); } /** * Issue #256-swingx: viewport config. * */ public void interactiveTestFillsViewportHeight() { final JXTable table = new JXTable(10, 2); table.setFillsViewportHeight(true); JXFrame frame = wrapWithScrollingInFrame(table, "toggle viewport height"); frame.setSize(500, table.getPreferredSize().height * 2); Action action = new AbstractAction("toggle fill") { public void actionPerformed(ActionEvent e) { table.setFillsViewportHeight(!table.getFillsViewportHeight()); } }; addAction(frame, action); frame.setVisible(true); } /** * Issue ??: Anchor lost after receiving a structure changed. * Lead/anchor no longer automatically initialized - no visual clue * if table is focused. * */ public void interactiveTestToggleTableModelU6() { final DefaultTableModel tableModel = createAscendingModel(0, 20); final JTable table = new JTable(tableModel); // JW: need to explicitly set _both_ anchor and lead to >= 0 // need to set anchor first table.getSelectionModel().setAnchorSelectionIndex(0); table.getSelectionModel().setLeadSelectionIndex(0); table.getColumnModel().getSelectionModel().setAnchorSelectionIndex(0); table.getColumnModel().getSelectionModel().setLeadSelectionIndex(0); Action toggleAction = new AbstractAction("Toggle TableModel") { public void actionPerformed(ActionEvent e) { TableModel model = table.getModel(); table.setModel(model.equals(tableModel) ? sortableTableModel : tableModel); } }; JXFrame frame = wrapWithScrollingInFrame(table, "anchor lost after structure changed"); addAction(frame, toggleAction); frame.setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run() { // sanity - focus is on table LOG.info("isFocused? " + table.hasFocus()); LOG.info("who has focus? " + KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner()); } }); } /** * Issue #186-swingxProblem with lead/selection and buttons as editors: * - move focus (using arrow keys) to first editable boolean * - press space to toggle boolean * - move focus to next row (same column) * - press space to toggle boolean * - move back to first row (same column) * - press space: boolean is toggled and (that's the problem) * lead selection is moved to next row. * No problem in JTable. * */ public void interactiveTestCompareTableBoolean() { JXTable xtable = new JXTable(createModelWithBooleans()); JTable table = new JTable(createModelWithBooleans()); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "Compare boolean renderer JXTable <--> JTable"); frame.setVisible(true); } private TableModel createModelWithBooleans() { String[] columnNames = { "text only", "Bool editable", "Bool not-editable" }; DefaultTableModel model = new DefaultTableModel(columnNames, 0) { public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public boolean isCellEditable(int row, int column) { return !getColumnName(column).contains("not"); } }; for (int i = 0; i < 4; i++) { model.addRow(new Object[] {"text only " + i, Boolean.TRUE, Boolean.TRUE }); } return model; } /** * Issue #89-swingx: ColumnControl not updated with ComponentOrientation. * */ public void interactiveRToLTableWithColumnControl() { final JXTable table = new JXTable(createAscendingModel(0, 20)); final JScrollPane pane = new JScrollPane(table); // table.setColumnControlVisible(true); // pane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); JXFrame frame = wrapInFrame(pane, "RToLScrollPane"); Action toggleComponentOrientation = new AbstractAction("toggle orientation") { public void actionPerformed(ActionEvent e) { ComponentOrientation current = pane.getComponentOrientation(); if (current == ComponentOrientation.LEFT_TO_RIGHT) { pane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); } else { pane.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); } } }; addAction(frame, toggleComponentOrientation); Action toggleColumnControl = new AbstractAction("toggle column control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; addAction(frame, toggleColumnControl); frame.setVisible(true); } public void interactiveTestRowHeightAndSelection() { final JXTable table = new JXTable(sortableTableModel); table.setRowHeightEnabled(true); table.setRowHeight(0, table.getRowHeight() * 2); final int column = 0; table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; ListSelectionModel model = (ListSelectionModel) e.getSource(); int selected = model.getMinSelectionIndex(); if (selected < 0) return; System.out.println("from selection: " + table.getValueAt(selected, column)); } }); JXFrame frame = wrapWithScrollingInFrame(table, "Accessing values (indy rowheights)"); Action updateCellAction = new AbstractAction("update cell value") { public void actionPerformed(ActionEvent e) { int anchorRow = table.getSelectionModel().getLeadSelectionIndex(); int anchorCol = table.getColumnModel().getSelectionModel().getLeadSelectionIndex(); if ((anchorRow < 0) || (anchorCol < 0)) return; table.setValueAt("x" + table.getValueAt(anchorRow, anchorCol), anchorRow, anchorCol); } }; addAction(frame, updateCellAction); frame.setVisible(true); } public void interactiveTestRowHeight() { final JXTable table = new JXTable(sortableTableModel); table.setRowHeightEnabled(true); table.setRowHeight(0, table.getRowHeight() * 2); JXFrame frame = wrapWithScrollingInFrame(table, "Individual rowheight"); Action temp = new AbstractAction("empty selection") { public void actionPerformed(ActionEvent e) { table.changeSelection(-1, -1, false, false); } }; addAction(frame, temp); frame.setVisible(true); } /** * Issue #232-swingx: SelectionMapper not updated on changing selectionModel. * visually verify that the mapper keeps the selection after re-setting * table's selectionModel. * * * */ public void interactiveSelectionMapperOnSelectionModelChange() { final JXTable table = new JXTable(sortableTableModel); table.setSelectionModel(new DefaultListSelectionModel()); JXFrame frame = wrapWithScrollingInFrame(table, "SelectionMapper: keep selection on change view model"); // Action temp = new AbstractAction("toggle selectionModel") { // public void actionPerformed(ActionEvent e) { // table.setSelectionModel(new DefaultListSelectionModel()); // addAction(frame, temp); frame.setVisible(true); } /** * example mixed sorting (Jens Elkner). * */ public void interactiveTestSorterPatch() { Object[][] fourWheels = new Object[][]{ new Object[] {"Car", new Car(180f)}, new Object[] {"Porsche", new Porsche(170)}, new Object[] {"Porsche", new Porsche(170)}, new Object[] {"Porsche", new Porsche(170, false)}, new Object[] {"Tractor", new Tractor(20)}, new Object[] {"Tractor", new Tractor(10)}, }; DefaultTableModel model = new DefaultTableModel(fourWheels, new String[] {"Text", "Car"}) ; JXTable table = new JXTable(model); JFrame frame = wrapWithScrollingInFrame(table, "Sorter patch"); frame.setVisible(true); } public class Car implements Comparable<Car> { float speed = 100; public Car(float speed) { this.speed = speed; } public int compareTo(Car o) { return speed < o.speed ? -1 : speed > o.speed ? 1 : 0; } public String toString() { return "Car - " + speed; } } public class Porsche extends Car { boolean hasBridgeStone = true; public Porsche(float speed) { super(speed); } public Porsche(float speed, boolean bridgeStone) { this(speed); hasBridgeStone = bridgeStone; } public int compareTo(Car o) { if (o instanceof Porsche) { return ((Porsche) o).hasBridgeStone ? 0 : 1; } return super.compareTo(o); } public String toString() { return "Porsche - " + speed + (hasBridgeStone ? "+" : ""); } } public class Tractor implements Comparable<Tractor> { float speed = 20; public Tractor(float speed) { this.speed = speed; } public int compareTo(Tractor o) { return speed < o.speed ? -1 : speed > o.speed ? 1 : 0; } public String toString() { return "Tractor - " + speed; } } /** * Issue #179: Sorter does not use collator if cell content is * a String. * */ public void interactiveTestLocaleSorter() { Object[][] rowData = new Object[][] { new Object[] { Boolean.TRUE, "aa" }, new Object[] { Boolean.FALSE, "AB" }, new Object[] { Boolean.FALSE, "AC" }, new Object[] { Boolean.TRUE, "BA" }, new Object[] { Boolean.FALSE, "BB" }, new Object[] { Boolean.TRUE, "BC" } }; String[] columnNames = new String[] { "Critical", "Task" }; DefaultTableModel model = new DefaultTableModel(rowData, columnNames); // public Class getColumnClass(int column) { // return column == 1 ? String.class : super.getColumnClass(column); final JXTable table = new JXTable(model); table.toggleSortOrder(1); JFrame frame = wrapWithScrollingInFrame(table, "locale sorting"); frame.setVisible(true); } /** * Issue #??: Problems with filters and ColumnControl * * - sporadic ArrayIndexOOB after sequence: * filter(column), sort(column), hide(column), setFilter(null) * * - filtering invisible columns? Unclear state transitions. * */ public void interactiveTestColumnControlAndFilters() { final JXTable table = new JXTable(sortableTableModel); // hmm bug regression with combos as editors - same in JTable // JComboBox box = new JComboBox(new Object[] {"one", "two", "three" }); // box.setEditable(true); // table.getColumnExt(0).setCellEditor(new DefaultCellEditor(box)); Action toggleFilter = new AbstractAction("Toggle Filter col. 0") { boolean hasFilters; public void actionPerformed(ActionEvent e) { if (hasFilters) { table.setFilters(null); } else { Filter filter = new PatternFilter("e", 0, 0); table.setFilters(new FilterPipeline(new Filter[] {filter})); } hasFilters = !hasFilters; } }; toggleFilter.putValue(Action.SHORT_DESCRIPTION, "filtering first column - problem if invisible "); table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters"); addAction(frame, toggleFilter); frame.setVisible(true); } /** * @KEEP this is about testing Mustang sorting. */ public void interactiveTestColumnControlAndFiltersRowSorter() { // final JXTable table = new JXTable(sortableTableModel); // // hmm bug regression with combos as editors - same in JTable //// JComboBox box = new JComboBox(new Object[] {"one", "two", "three" }); //// box.setEditable(true); //// table.getColumnExt(0).setCellEditor(new DefaultCellEditor(box)); // Action toggleFilter = new AbstractAction("Toggle RowFilter -contains e- ") { // boolean hasFilters; // public void actionPerformed(ActionEvent e) { // if (hasFilters) { // table.setFilters(null); // } else { // RowSorterFilter filter = new RowSorterFilter(); // filter.setRowFilter(RowFilter.regexFilter(".*e.*", 0)); // table.setFilters(new FilterPipeline(new Filter[] {filter})); // hasFilters = !hasFilters; // toggleFilter.putValue(Action.SHORT_DESCRIPTION, "filtering first column - problem if invisible "); // table.setColumnControlVisible(true); // JFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters"); // addAction(frame, toggleFilter); // frame.setVisible(true); } /** * Issue ??: Column control on changing column model. * */ public void interactiveTestToggleTableModel() { final DefaultTableModel tableModel = createAscendingModel(0, 20); final JXTable table = new JXTable(tableModel); table.setColumnControlVisible(true); Action toggleAction = new AbstractAction("Toggle TableModel") { public void actionPerformed(ActionEvent e) { TableModel model = table.getModel(); table.setModel(model.equals(tableModel) ? sortableTableModel : tableModel); } }; JXFrame frame = wrapWithScrollingInFrame(table, "ColumnControl: set columnModel -> core default"); addAction(frame, toggleAction); frame.setVisible(true); } /** * Issue ??: Column control on changing column model. * */ public void interactiveTestColumnControlColumnModel() { final JXTable table = new JXTable(10, 5); table.setColumnControlVisible(true); Action toggleAction = new AbstractAction("Set ColumnModel") { public void actionPerformed(ActionEvent e) { table.setColumnModel(new DefaultTableColumnModel()); table.setModel(sortableTableModel); setEnabled(false); } }; JXFrame frame = wrapWithScrollingInFrame(table, "ColumnControl: set columnModel -> core default"); addAction(frame, toggleAction); frame.setVisible(true); } /** * Issue ??: Column control on changing column model. * */ public void interactiveTestColumnControlColumnModelExt() { final JXTable table = new JXTable(); table.setColumnModel( new DefaultTableColumnModel()); table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); Action toggleAction = new AbstractAction("Set ColumnModelExt") { public void actionPerformed(ActionEvent e) { table.setColumnModel(new DefaultTableColumnModelExt()); table.setModel(sortableTableModel); table.getColumnExt(0).setVisible(false); setEnabled(false); } }; JXFrame frame = wrapWithScrollingInFrame(table, "ColumnControl: set ColumnModel -> modelExt"); addAction(frame, toggleAction); frame.setVisible(true); } /** * Issue #155-swingx: vertical scrollbar policy lost. * */ public void interactiveTestColumnControlConserveVerticalScrollBarPolicy() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); // table.setColumnControlVisible(true); JScrollPane scrollPane1 = new JScrollPane(table); scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); JXFrame frame = wrapInFrame(scrollPane1, "JXTable Vertical ScrollBar Policy"); addAction(frame, toggleAction); frame.setVisible(true); } /** * Issue #11: Column control not showing with few rows. * */ public void interactiveTestColumnControlFewRows() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl with few rows"); addAction(frame, toggleAction); frame.setVisible(true); } /** * check behaviour outside scrollPane * */ public void interactiveTestColumnControlWithoutScrollPane() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; toggleAction.putValue(Action.SHORT_DESCRIPTION, "does nothing visible - no scrollpane"); table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); JXFrame frame = wrapInFrame(table, "JXTable: Toggle ColumnControl outside ScrollPane"); addAction(frame, toggleAction); frame.setVisible(true); } /** * check behaviour of moving into/out of scrollpane. * */ public void interactiveTestToggleScrollPaneWithColumnControlOn() { final JXTable table = new JXTable(); table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); final JXFrame frame = wrapInFrame(table, "JXTable: Toggle ScrollPane with Columncontrol on"); Action toggleAction = new AbstractAction("Toggle ScrollPane") { public void actionPerformed(ActionEvent e) { Container parent = table.getParent(); boolean inScrollPane = parent instanceof JViewport; if (inScrollPane) { JScrollPane scrollPane = (JScrollPane) table.getParent().getParent(); frame.getContentPane().remove(scrollPane); frame.getContentPane().add(table); } else { parent.remove(table); parent.add(new JScrollPane(table)); } frame.pack(); } }; addAction(frame, toggleAction); frame.setVisible(true); } /** * TableColumnExt: user friendly resizable * */ public void interactiveTestColumnResizable() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); final TableColumnExt priorityColumn = table.getColumnExt("First Name"); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable: Column with Min=Max not resizable"); Action action = new AbstractAction("Toggle MinMax of FirstName") { public void actionPerformed(ActionEvent e) { // user-friendly resizable flag if (priorityColumn.getMinWidth() == priorityColumn.getMaxWidth()) { priorityColumn.setMinWidth(50); priorityColumn.setMaxWidth(150); } else { priorityColumn.setMinWidth(100); priorityColumn.setMaxWidth(100); } } }; addAction(frame, action); frame.setVisible(true); } /** * quick check if multiple comparators per column work. * Basically yes, with a slight tweak: need to comment guarding * code in filterpipeline throwing exceptions. * * So commented the body for now, need to enquire why the guard * was added in the first place. * * @KEEP */ public void interactiveMultipleComparatorsPerColumn() { // JXTable table = new JXTable(createSplittableValues()); // Sorter sorter1 = new ShuttleSorter(0, false); // sorter1.setComparator(new ClassComparator(0)); // Sorter sorter2 = new ShuttleSorter(0, true ); // sorter2.setComparator(new ClassComparator(1)); // FilterPipeline pipeline = new FilterPipeline(new Filter[] { sorter1, sorter2 }); // table.setFilters(pipeline); // JXFrame frame = wrapWithScrollingInFrame(table, "MultipleSorter per Column"); // frame.setVisible(true); } private TableModel createSplittableValues() { String[] values = {"avalue:zvalue", "avalue:yvalue", "avalue:xvalue", "bvalue:zvalue", "bvalue:yvalue", "bvalue:xvalue", "cvalue:zvalue", "cvalue:yvalue", "cvalue:xvalue", }; DefaultTableModel model = new DefaultTableModel(values.length, 1); for (int i = 0; i < values.length; i++) { model.setValueAt(values[i], i, 0); } return model; } public class ClassComparator implements Comparator { List packageOrder; int sortIndex; public ClassComparator(int index) { this.sortIndex = index; } public int compare(Object o1, Object o2) { String[] value1 = String.valueOf(o1).split(":"); String[] value2 = String.valueOf(o2).split(":"); String part1 = value1.length > sortIndex ? value1[sortIndex] : ""; String part2 = value2.length > sortIndex ? value2[sortIndex] : ""; return part1.compareTo(part2); } } /** * Issue #31 (swingx): clicking header must not sort if table !enabled. * */ public void interactiveTestDisabledTableSorting() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); Action toggleAction = new AbstractAction("Toggle Enabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); } }; JXFrame frame = wrapWithScrollingInFrame(table, "Disabled tabled: no sorting"); addAction(frame, toggleAction); frame.setVisible(true); } /** * Issue #191: sorting and custom renderer * not reproducible ... * */ public void interactiveTestCustomRendererSorting() { JXTable table = new JXTable(sortableTableModel); TableColumn column = table.getColumn("No."); TableCellRenderer renderer = new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { value = "# " + value ; Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col ); return comp; } }; column.setCellRenderer(renderer); JFrame frame = wrapWithScrollingInFrame(table, "RendererSortingTest"); frame.setVisible(true); } public void interactiveTestToggleSortable() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); Action toggleSortableAction = new AbstractAction("Toggle Sortable") { public void actionPerformed(ActionEvent e) { table.setSortable(!table.isSortable()); } }; JXFrame frame = wrapWithScrollingInFrame(table, "ToggleSortingEnabled Test"); addAction(frame, toggleSortableAction); frame.setVisible(true); } public void interactiveTestTableSizing1() { JXTable table = new JXTable(); table.setAutoCreateColumnsFromModel(false); table.setModel(tableModel); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); TableColumnExt columns[] = new TableColumnExt[tableModel.getColumnCount()]; for (int i = 0; i < columns.length; i++) { columns[i] = new TableColumnExt(i); table.addColumn(columns[i]); } columns[0].setPrototypeValue(new Integer(0)); columns[1].setPrototypeValue("Simple String Value"); columns[2].setPrototypeValue(new Integer(1000)); columns[3].setPrototypeValue(Boolean.TRUE); columns[4].setPrototypeValue(new Date(100)); columns[5].setPrototypeValue(new Float(1.5)); columns[6].setPrototypeValue(new LinkModel("Sun Micro", "_blank", tableModel.linkURL)); columns[7].setPrototypeValue(new Integer(3023)); columns[8].setPrototypeValue("John Doh"); columns[9].setPrototypeValue("23434 Testcase St"); columns[10].setPrototypeValue(new Integer(33333)); columns[11].setPrototypeValue(Boolean.FALSE); table.setVisibleRowCount(12); JFrame frame = wrapWithScrollingInFrame(table, "TableSizing1 Test"); frame.setVisible(true); } public void interactiveTestEmptyTableSizing() { JXTable table = new JXTable(0, 5); table.setColumnControlVisible(true); JFrame frame = wrapWithScrollingInFrame(table, "Empty Table (0 rows)"); frame.setVisible(true); } public void interactiveTestTableSizing2() { JXTable table = new JXTable(); table.setAutoCreateColumnsFromModel(false); table.setModel(tableModel); TableColumnExt columns[] = new TableColumnExt[6]; int viewIndex = 0; for (int i = columns.length - 1; i >= 0; i columns[viewIndex] = new TableColumnExt(i); table.addColumn(columns[viewIndex++]); } columns[5].setHeaderValue("String Value"); columns[5].setPrototypeValue("9999"); columns[4].setHeaderValue("String Value"); columns[4].setPrototypeValue("Simple String Value"); columns[3].setHeaderValue("Int Value"); columns[3].setPrototypeValue(new Integer(1000)); columns[2].setHeaderValue("Bool"); columns[2].setPrototypeValue(Boolean.FALSE); //columns[2].setSortable(false); columns[1].setHeaderValue("Date"); columns[1].setPrototypeValue(new Date(0)); //columns[1].setSortable(false); columns[0].setHeaderValue("Float"); columns[0].setPrototypeValue(new Float(5.5)); table.setRowHeight(24); table.setRowMargin(2); JFrame frame = wrapWithScrollingInFrame(table, "TableSizing2 Test"); frame.setVisible(true); } public void interactiveTestRolloverHighlight() { JXTable table = new JXTable(sortableTableModel); table.setRolloverEnabled(true); table.addHighlighter(new RolloverHighlighter(Color.YELLOW, null)); // table.addHighlighter(new RolloverHighlighter(null, Color.RED)); JFrame frame = wrapWithScrollingInFrame(table, "rollover highlight"); frame.setVisible(true); } public void interactiveTestTableAlternateHighlighterGroup() { JXTable table = new JXTable(tableModel); table.setRowHeight(22); AlternateRowHighlighter highlighter = new UIAlternateRowHighlighter(); highlighter.setLinesPerGroup(5); table.addHighlighter(highlighter); JFrame frame = wrapWithScrollingInFrame(table, "AlternateRow with Grouping of 5 lines"); frame.setVisible(true); } public void interactiveTestAlternateRowWithForegroundHighlighter() { JXTable table = new JXTable(tableModel); ConditionalHighlighter highlighter = new ConditionalHighlighter(null, Color.BLUE, 1, 1) { @Override protected boolean needsHighlight(ComponentAdapter adapter) { return highlightColumn == adapter.viewToModel(adapter.column); } @Override protected boolean test(ComponentAdapter adapter) { // not called - the column is highlighted unconditionally return false; } }; table.addHighlighter(highlighter); table.addHighlighter(new UIAlternateRowHighlighter()); JFrame frame = wrapWithScrollingInFrame(table, "AlternateRow with and column"); frame.setVisible(true); } public void interactiveTestTableAlternateHighlighter1() { JXTable table = new JXTable(tableModel); table.setRolloverEnabled(true); table.setRowHeight(22); table.setRowMargin(1); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(0, true) // column 0, ascending })); table.setHighlighters(new HighlighterPipeline(new Highlighter[] { AlternateRowHighlighter.linePrinter, new RolloverHighlighter(Color.YELLOW, null), })); JFrame frame = wrapWithScrollingInFrame(table, "LinePrinter plus yellow rollover"); frame.setVisible(true); } public void interactiveTestTableAlternateRowHighlighter2() { JXTable table = new JXTable(tableModel); table.setRowHeight(22); table.setRowMargin(1); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(1, false), // column 1, descending })); table.addHighlighter(AlternateRowHighlighter.classicLinePrinter); JFrame frame = wrapWithScrollingInFrame(table, "classic lineprinter Test"); frame.setVisible(true); } public void interactiveTestTableSorter1() { JXTable table = new JXTable(sortableTableModel); table.setBackground(new Color(0xFF, 0xFF, 0xCC)); // notepad table.setGridColor(Color.cyan.darker()); table.setRowHeight(22); table.setRowMargin(1); table.setShowHorizontalLines(true); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(0, true), // column 0, ascending new ShuttleSorter(1, true), // column 1, ascending })); JFrame frame = wrapWithScrollingInFrame(table, "TableSorter1 col 0= asc, col 1 = asc"); frame.setVisible(true); } public void interactiveTestTableSorter2() { JXTable table = new JXTable(sortableTableModel); table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger table.setGridColor(Color.cyan.darker()); table.setRowHeight(22); table.setRowMargin(1); table.setShowHorizontalLines(true); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(0, true), // column 0, ascending new ShuttleSorter(1, false), // column 1, descending })); JFrame frame = wrapWithScrollingInFrame(table, "TableSorter2 col 0 = asc, col 1 = desc"); frame.setVisible(true); } public void interactiveTestFocusedCellBackground() { TableModel model = new AncientSwingTeam() { public boolean isCellEditable(int row, int column) { return column != 0; } }; JXTable xtable = new JXTable(model); xtable.setBackground(Highlighter.notePadBackground.getBackground()); // ledger JTable table = new JTable(model); table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger JFrame frame = wrapWithScrollingInFrame(xtable, table, "Unselected focused background: JXTable/JTable"); frame.setVisible(true); } public void interactiveTestTableSorter3() { JXTable table = new JXTable(sortableTableModel); table.addHighlighter(new Highlighter(Color.orange, null)); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(1, true), // column 1, ascending new ShuttleSorter(0, false), // column 0, descending })); JFrame frame = wrapWithScrollingInFrame(table, "TableSorter3 col 1 = asc, col 0 = desc"); frame.setVisible(true); } public void interactiveTestTableSorter4() { JXTable table = new JXTable(sortableTableModel); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(0, false), // column 0, descending new ShuttleSorter(1, true), // column 1, ascending })); JFrame frame = wrapWithScrollingInFrame(table, "TableSorter4 col 0 = des, col 1 = asc"); frame.setVisible(true); } public void interactiveTestTablePatternFilter1() { JXTable table = new JXTable(tableModel); table.setIntercellSpacing(new Dimension(1, 1)); table.setShowGrid(true); table.setFilters(new FilterPipeline(new Filter[] { new PatternFilter("^A", 0, 1) })); JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter1 Test"); frame.setVisible(true); } public void interactiveTestTablePatternFilter2() { JXTable table = new JXTable(tableModel); table.setIntercellSpacing(new Dimension(2, 2)); table.setShowGrid(true); table.setFilters(new FilterPipeline(new Filter[] { new PatternFilter("^S", 0, 1), new ShuttleSorter(0, false), // column 0, descending })); JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter2 Test"); frame.setVisible(true); } public void interactiveTestTablePatternFilter3() { JXTable table = new JXTable(tableModel); table.setShowGrid(true); table.setFilters(new FilterPipeline(new Filter[] { new PatternFilter("^S", 0, 1), new ShuttleSorter(1, false), // column 1, descending new ShuttleSorter(0, false), // column 0, descending })); JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter3 Test"); frame.setVisible(true); } public void interactiveTestTablePatternFilter4() { JXTable table = new JXTable(tableModel); table.setIntercellSpacing(new Dimension(3, 3)); table.setShowGrid(true); table.setFilters(new FilterPipeline(new Filter[] { new PatternFilter("^A", 0, 1), new ShuttleSorter(0, false), // column 0, descending })); JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter4 Test"); frame.setVisible(true); } public void interactiveTestTableSortedPatternFilterPatternHighlighter() { JXTable table = new JXTable(tableModel); table.setFilters(new FilterPipeline(new Filter[] { new PatternFilter("^S", 0, 1), new ShuttleSorter(0, false), // column 0, descending new ShuttleSorter(1, true), // column 1, ascending new ShuttleSorter(3, false), // column 3, descending })); table.addHighlighter(new PatternHighlighter(null, Color.red, "^S", 0, 1)); JFrame frame = wrapWithScrollingInFrame(table, "PatternFilter/Highlighter ^S col1"); frame.setVisible(true); } public void interactiveTestTableViewProperties() { JXTable table = new JXTable(tableModel); table.setIntercellSpacing(new Dimension(15, 15)); table.setRowHeight(48); JFrame frame = wrapWithScrollingInFrame(table, "TableViewProperties Test"); frame.setVisible(true); } public void interactiveTestTablePatternHighlighter() { JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); table.setIntercellSpacing(new Dimension(15, 15)); table.setRowHeight(48); table.setRowHeight(0, 96); table.setShowGrid(true); table.addHighlighter(new PatternHighlighter(null, Color.red, "^A", 0, 1)); JFrame frame = wrapWithScrollingInFrame(table, "PatternHighlighter ^A col 1"); frame.setVisible(true); } public void interactiveTestTableColumnProperties() { JXTable table = new JXTable(); table.setModel(tableModel); table.getTableHeader().setBackground(Color.green); table.getTableHeader().setForeground(Color.magenta); table.getTableHeader().setFont(new Font("Serif", Font.PLAIN, 10)); ColumnHeaderRenderer headerRenderer = ColumnHeaderRenderer.createColumnHeaderRenderer(); headerRenderer.setHorizontalAlignment(JLabel.LEFT); headerRenderer.setBackground(Color.blue); headerRenderer.setForeground(Color.yellow); headerRenderer.setIcon(new Icon() { public int getIconWidth() { return 12; } public int getIconHeight() { return 12; } public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(Color.red); g.fillOval(0, 0, 10, 10); } }); headerRenderer.setIconTextGap(20); headerRenderer.setFont(new Font("Serif", Font.BOLD, 18)); for (int i = 0; i < table.getColumnCount(); i++) { TableColumnExt column = table.getColumnExt(i); if (i % 3 > 0) { column.setHeaderRenderer(headerRenderer); } if (i % 2 > 0) { TableCellRenderer cellRenderer = table.getNewDefaultRenderer(table.getColumnClass(i)); if (cellRenderer instanceof JLabel || cellRenderer instanceof AbstractButton) { JComponent labelCellRenderer = (JComponent)cellRenderer; labelCellRenderer.setBackground(Color.gray); labelCellRenderer.setForeground(Color.red); if (cellRenderer instanceof JLabel) { ((JLabel) labelCellRenderer).setHorizontalAlignment(JLabel.CENTER); } else { ((AbstractButton) labelCellRenderer).setHorizontalAlignment(JLabel.CENTER); } column.setCellRenderer(cellRenderer); } } } JFrame frame = wrapWithScrollingInFrame(table, "TableColumnProperties Test"); frame.setVisible(true); } /** * dummy */ public void testDummy() { } }
package com.jme3.font; import java.io.IOException; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.export.Savable; import com.jme3.material.Material; /** * Represents a font within jME that is generated with the AngelCode Bitmap Font Generator * @author dhdd */ public class BitmapFont implements Savable { /** * Specifies horizontal alignment for text. * * @see BitmapText#setAlignment(com.jme3.font.BitmapFont.Align) */ public enum Align { /** * Align text on the left of the text block */ Left, /** * Align text in the center of the text block */ Center, /** * Align text on the right of the text block */ Right } /** * Specifies vertical alignment for text. * * @see BitmapText#setVerticalAlignment(com.jme3.font.BitmapFont.VAlign) */ public enum VAlign { /** * Align text on the top of the text block */ Top, /** * Align text in the center of the text block */ Center, /** * Align text at the bottom of the text block */ Bottom } private BitmapCharacterSet charSet; private Material[] pages; public BitmapFont() { } public BitmapText createLabel(String content){ BitmapText label = new BitmapText(this); label.setSize(getCharSet().getRenderedSize()); label.setText(content); return label; } public float getPreferredSize(){ return getCharSet().getRenderedSize(); } public void setCharSet(BitmapCharacterSet charSet) { this.charSet = charSet; } public void setPages(Material[] pages) { this.pages = pages; charSet.setPageSize(pages.length); } public Material getPage(int index) { return pages[index]; } public int getPageSize() { return pages.length; } public BitmapCharacterSet getCharSet() { return charSet; } /** * Gets the line height of a StringBlock. * @param sb * @return */ public float getLineHeight(StringBlock sb) { return charSet.getLineHeight() * (sb.getSize() / charSet.getRenderedSize()); } public float getCharacterAdvance(char curChar, char nextChar, float size){ BitmapCharacter c = charSet.getCharacter(curChar); if (c == null) return 0f; float advance = size * c.getXAdvance(); advance += c.getKerning(nextChar) * size; return advance; } private int findKerningAmount(int newLineLastChar, int nextChar) { BitmapCharacter c = charSet.getCharacter(newLineLastChar); if (c == null) return 0; return c.getKerning(nextChar); } @Override public void write(JmeExporter ex) throws IOException { OutputCapsule oc = ex.getCapsule(this); oc.write(charSet, "charSet", null); oc.write(pages, "pages", null); } @Override public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); charSet = (BitmapCharacterSet) ic.readSavable("charSet", null); Savable[] pagesSavable = ic.readSavableArray("pages", null); pages = new Material[pagesSavable.length]; System.arraycopy(pagesSavable, 0, pages, 0, pages.length); } public float getLineWidth(CharSequence text){ // This method will probably always be a bit of a maintenance // nightmare since it basis its calculation on a different // routine than the Letters class. The ideal situation would // be to abstract out letter position and size into its own // class that both BitmapFont and Letters could use for // positioning. // If getLineWidth() here ever again returns a different value // than Letters does with the same text then it might be better // just to create a Letters object for the sole purpose of // getting a text size. It's less efficient but at least it // would be accurate. // And here I am mucking around in here again... // A font character has a few values that are pertinent to the // line width: // xOffset // xAdvance // kerningAmount(nextChar) // The way BitmapText ultimately works is that the first character // starts with xOffset included (ie: it is rendered at -xOffset). // Its xAdvance is wider to accomodate that initial offset. // The cursor position is advanced by xAdvance each time. // So, a width should be calculated in a similar way. Start with // -xOffset + xAdvance for the first character and then each subsequent // character is just xAdvance more 'width'. // The kerning amount from one character to the next affects the // cursor position of that next character and thus the ultimate width // and so must be factored in also. float lineWidth = 0f; float maxLineWidth = 0f; char lastChar = 0; boolean firstCharOfLine = true; // float sizeScale = (float) block.getSize() / charSet.getRenderedSize(); float sizeScale = 1f; for (int i = 0; i < text.length(); i++){ char theChar = text.charAt(i); if (theChar == '\n'){ maxLineWidth = Math.max(maxLineWidth, lineWidth); lineWidth = 0f; firstCharOfLine = true; continue; } BitmapCharacter c = charSet.getCharacter((int) theChar); if (c != null){ if (theChar == '\\' && i<text.length()-1 && text.charAt(i+1)==' if (i+5<text.length() && text.charAt(i+5)==' i+=5; continue; }else if (i+8<text.length() && text.charAt(i+8)==' i+=8; continue; } } if (!firstCharOfLine){ lineWidth += findKerningAmount(lastChar, theChar) * sizeScale; } else { // The first character needs to add in its xOffset but it // is the only one... and negative offsets = postive width // because we're trying to account for the part that hangs // over the left. So we subtract. lineWidth -= c.getXOffset() * sizeScale; firstCharOfLine = false; } float xAdvance = c.getXAdvance() * sizeScale; // If this is the last character, then we really should have // only add its width. The advance may include extra spacing // that we don't care about. if (i == text.length() - 1) { lineWidth += c.getWidth() * sizeScale; // Since theh width includes the xOffset then we need // to take it out again by adding it, ie: offset the width // we just added by the appropriate amount. lineWidth += c.getXOffset() * sizeScale; } else { lineWidth += xAdvance; } } } return Math.max(maxLineWidth, lineWidth); } /** * Merge two fonts. * If two font have the same style, merge will fail. * @param styleSet Style must be assigned to this. * @author Yonghoon */ public void merge(BitmapFont newFont) { charSet.merge(newFont.charSet); final int size1 = this.pages.length; final int size2 = newFont.pages.length; Material[] tmp = new Material[size1+size2]; System.arraycopy(this.pages, 0, tmp, 0, size1); System.arraycopy(newFont.pages, 0, tmp, size1, size2); this.pages = tmp; // this.pages = Arrays.copyOf(this.pages, size1+size2); // System.arraycopy(newFont.pages, 0, this.pages, size1, size2); } public void setStyle(int style) { charSet.setStyle(style); } }
import javax.swing.*; import java.util.ArrayList; public class UI { //all visible GUI display elements JFrame frame; //all invisible GUI display elements JPanel base; JPanel diceBase; JPanel[] individualDiceBase; //all background elements Calc calc; int playerCount; public UI(Calc calc,ArrayList<String> names){ this.calc=calc; playerCount=names.size(); } private void createUI(){ //create JFrame to contain every element frame=new JFrame("Yahtzee"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //add the base panel to the frame base=new JPanel(); base.setLayout(new BoxLayout(base, BoxLayout.X_AXIS)); frame.add(base); //add the panel for all dices diceBase=new JPanel(); diceBase.setLayout(new BoxLayout(diceBase, BoxLayout.X_AXIS)); base.add(diceBase); //create and add the panel for every singular dice individualDiceBase = new JPanel[5]; for (int i=0;i<5;i++){ individualDiceBase[i]=new JPanel(); individualDiceBase[i].setLayout(new BoxLayout(individualDiceBase[i],BoxLayout.Y_AXIS)); base.add(individualDiceBase[i]); } } }
package com.google.blockly.ui; import android.content.Context; import android.util.AttributeSet; import android.view.ViewGroup; /** * ViewGroup base class that does not propagate pressed, activated, or selected state to child * Views. */ public abstract class NonPropagatingViewGroup extends ViewGroup { public NonPropagatingViewGroup(Context context) { super(context); } public NonPropagatingViewGroup(Context context, AttributeSet attrs) { super(context, attrs); } public NonPropagatingViewGroup(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public NonPropagatingViewGroup(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override public void dispatchSetActivated(boolean activated) { // Do nothing. Do not assign the activated state to children. } @Override public void dispatchSetPressed(boolean pressed) { // Do nothing. Do not assign the pressed state to children. } @Override public void dispatchSetSelected(boolean selected) { // Do nothing. Do not assign the selected state to children. } }
package net.bytebuddy.agent.builder; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.EqualsAndHashCode; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.dynamic.loading.ClassInjector; import java.lang.instrument.ClassFileTransformer; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * This class serves as a dispatcher for creating lambda expression objects when Byte Buddy is configured to instrument the * {@code java.lang.invoke.LambdaMetafactory}. For this purpose, this class is injected into the class path to serve as a VM-global * singleton and for becoming reachable from the JVM's meta factory. This class keeps a reference to all registered transformers which need * to be explicitly deregistered in order to avoid a memory leak. */ @EqualsAndHashCode public class LambdaFactory { /** * The name of the field to access. */ private static final String FIELD_NAME = "CLASS_FILE_TRANSFORMERS"; /** * A mapping of all registered class file transformers and their lambda factories, linked in their application order. * This field <b>must not</b> be accessed directly but only by reading this class from the system class loader. */ @SuppressFBWarnings(value = "MS_MUTABLE_COLLECTION_PKGPROTECT", justification = "The field must be accessible by different class loader instances") public static final Map<ClassFileTransformer, LambdaFactory> CLASS_FILE_TRANSFORMERS = new ConcurrentHashMap<ClassFileTransformer, LambdaFactory>(); /** * The target instance that is a factory for creating lambdas. */ private final Object target; /** * The dispatcher method to invoke for creating a new lambda instance. */ private final Method dispatcher; /** * Creates a new lambda factory. * * @param target The target instance that is a factory for creating lambdas. * @param dispatcher The dispatcher method to invoke for creating a new lambda instance. */ public LambdaFactory(Object target, Method dispatcher) { this.target = target; this.dispatcher = dispatcher; } /** * Registers a class file transformer together with a factory for creating a lambda expression. It is possible to call this method independently * of the class loader's context as the supplied injector makes sure that the manipulated collection is the one that is held by the system class * loader. * * @param classFileTransformer The class file transformer to register. * @param classFileFactory The lambda class file factory to use. This factory must define a visible instance method with the signature * {@code byte[] make(Object, String, Object, Object, Object, Object, boolean, List, List, Collection}. The arguments provided * are the invokedynamic call site's lookup object, the lambda method's name, the factory method's type, the lambda method's * type, the target method's handle, the specialized method type of the lambda expression, a boolean to indicate * serializability, a list of marker interfaces, a list of additional bridges and a collection of class file transformers to * apply. * @return {@code true} if this is the first registered transformer. This indicates that the {@code LambdaMetafactory} must be instrumented to delegate * to this alternative factory. */ @SuppressWarnings("all") public static boolean register(ClassFileTransformer classFileTransformer, Object classFileFactory) { try { TypeDescription typeDescription = new TypeDescription.ForLoadedType(LambdaFactory.class); Class<?> lambdaFactory = ClassInjector.UsingReflection.ofSystemClassLoader() .inject(Collections.singletonMap(typeDescription, ClassFileLocator.ForClassLoader.read(LambdaFactory.class).resolve())) .get(typeDescription); @SuppressWarnings("unchecked") Map<ClassFileTransformer, Object> classFileTransformers = (Map<ClassFileTransformer, Object>) lambdaFactory .getField(FIELD_NAME) .get(null); synchronized (classFileTransformers) { try { return classFileTransformers.isEmpty(); } finally { classFileTransformers.put(classFileTransformer, lambdaFactory .getConstructor(Object.class, Method.class) .newInstance(classFileFactory, classFileFactory.getClass().getMethod("make", Object.class, String.class, Object.class, Object.class, Object.class, Object.class, boolean.class, List.class, List.class, Collection.class))); } } } catch (RuntimeException exception) { throw exception; } catch (Exception exception) { throw new IllegalStateException("Could not register class file transformer", exception); } } /** * Releases a class file transformer. * * @param classFileTransformer The class file transformer to release. * @return {@code true} if the removed transformer was the last class file transformer registered. This indicates that the {@code LambdaMetafactory} must * be instrumented to no longer delegate to this alternative factory. */ @SuppressWarnings("all") public static boolean release(ClassFileTransformer classFileTransformer) { try { @SuppressWarnings("unchecked") Map<ClassFileTransformer, ?> classFileTransformers = (Map<ClassFileTransformer, ?>) ClassLoader.getSystemClassLoader() .loadClass(LambdaFactory.class.getName()) .getField(FIELD_NAME) .get(null); synchronized (classFileTransformers) { return classFileTransformers.remove(classFileTransformer) != null && classFileTransformers.isEmpty(); } } catch (RuntimeException exception) { throw exception; } catch (Exception exception) { throw new IllegalStateException("Could not release class file transformer", exception); } } /** * Applies this lambda meta factory. * * @param caller A lookup context representing the creating class of this lambda expression. * @param invokedName The name of the lambda expression's represented method. * @param invokedType The type of the lambda expression's factory method. * @param samMethodType The type of the lambda expression's represented method. * @param implMethod A handle representing the target of the lambda expression's method. * @param instantiatedMethodType A specialization of the type of the lambda expression's represented method. * @param serializable {@code true} if the lambda expression should be serializable. * @param markerInterfaces A list of interfaces for the lambda expression to represent. * @param additionalBridges A list of additional bridge methods to be implemented by the lambda expression. * @param classFileTransformers A collection of class file transformers to apply when creating the class. * @return A binary representation of the transformed class file. */ private byte[] invoke(Object caller, String invokedName, Object invokedType, Object samMethodType, Object implMethod, Object instantiatedMethodType, boolean serializable, List<Class<?>> markerInterfaces, List<?> additionalBridges, Collection<ClassFileTransformer> classFileTransformers) { try { return (byte[]) dispatcher.invoke(target, caller, invokedName, invokedType, samMethodType, implMethod, instantiatedMethodType, serializable, markerInterfaces, additionalBridges, classFileTransformers); } catch (RuntimeException exception) { throw exception; } catch (Exception exception) { throw new IllegalStateException("Cannot create class for lambda expression", exception); } } /** * Dispatches the creation of a new class representing a class file. * * @param caller A lookup context representing the creating class of this lambda expression. * @param invokedName The name of the lambda expression's represented method. * @param invokedType The type of the lambda expression's factory method. * @param samMethodType The type of the lambda expression's represented method. * @param implMethod A handle representing the target of the lambda expression's method. * @param instantiatedMethodType A specialization of the type of the lambda expression's represented method. * @param serializable {@code true} if the lambda expression should be serializable. * @param markerInterfaces A list of interfaces for the lambda expression to represent. * @param additionalBridges A list of additional bridge methods to be implemented by the lambda expression. * @return A binary representation of the transformed class file. */ public static byte[] make(Object caller, String invokedName, Object invokedType, Object samMethodType, Object implMethod, Object instantiatedMethodType, boolean serializable, List<Class<?>> markerInterfaces, List<?> additionalBridges) { return CLASS_FILE_TRANSFORMERS.values().iterator().next().invoke(caller, invokedName, invokedType, samMethodType, implMethod, instantiatedMethodType, serializable, markerInterfaces, additionalBridges, CLASS_FILE_TRANSFORMERS.keySet()); } }
//package com.eastpoint.chrysalis; package org.apache.fop.render.pcl; // FOP import org.apache.fop.render.PrintRenderer; import org.apache.fop.messaging.MessageHandler; import org.apache.fop.image.ImageArea; import org.apache.fop.image.FopImage; import org.apache.fop.apps.FOPException; import org.apache.fop.fo.properties.*; import org.apache.fop.datatypes.*; import org.apache.fop.pdf.PDFPathPaint; import org.apache.fop.pdf.PDFColor; import org.apache.fop.layout.*; import org.apache.fop.layout.inline.*; import org.apache.fop.image.*; import org.apache.fop.dom.svg.SVGArea; import org.w3c.dom.svg.SVGSVGElement; // Java import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; public class PCLRenderer extends PrintRenderer { /** the current stream to add PCL commands to */ public PCLStream currentStream; private int pageHeight = 7920; // These variables control the virtual paggination functionality. public int curdiv = 0; private int divisions = -1; public int paperheight = -1; // Paper height in decipoints? public int orientation = -1; // -1=default/unknown, 0=portrait, 1=landscape. public int topmargin = -1; // Top margin in decipoints? public int leftmargin = -1; // Left margin in decipoints? private int fullmargin = 0; private final boolean debug = false; private int xoffset = -180; // X Offset to allow for PCL implicit 1/4" left margin. /** * Create the PCL renderer */ public PCLRenderer() { } /** * set the PCL document's producer * * @param producer string indicating application producing PCL */ public void setProducer(String producer) { } /** * render the areas into PCL * * @param areaTree the laid-out area tree * @param stream the Outputstream to write the PCL to */ public void render(AreaTree areaTree, OutputStream stream) throws IOException, FOPException { MessageHandler.logln("rendering areas to PCL"); idReferences=areaTree.getIDReferences(); //this.pdfResources = this.pdfDoc.getResources(); //this.pdfDoc.setIDReferences(idReferences); Enumeration e = areaTree.getPages().elements(); currentStream = new PCLStream(stream); // Set orientation. if ( orientation > -1 ) currentStream.add("\033&l" + orientation + "O"); else currentStream.add("\033&l0O"); if ( orientation == 1 || orientation == 3 ) xoffset = -144; else xoffset = -180; // Reset the margins. currentStream.add("\033" + "9\033&l0E"); while (e.hasMoreElements()) { this.renderPage((Page) e.nextElement()); } if ( !idReferences.isEveryIdValid() ) { //throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n"); MessageHandler.errorln("Warning: The following id's were referenced but not found: "+idReferences.getInvalidIds() + "\n"); } MessageHandler.logln("writing out PCL"); stream.flush(); } /** * add a line to the current stream * * @param x1 the start x location in millipoints * @param y1 the start y location in millipoints * @param x2 the end x location in millipoints * @param y2 the end y location in millipoints * @param th the thickness in millipoints * @param stroke the line color */ protected void addLine(int x1, int y1, int x2, int y2, int th, PDFPathPaint stroke) { if ( x1 == x2 ) addRect(x1 - (th/2), y1, th, y2 - y1 + 1, stroke, stroke); else if ( y1 == y2 ) addRect(x1, y1 + (th/2), x2 - x1 + 1, th, stroke, stroke); } /** * add a line to the current stream * * @param x1 the start x location in millipoints * @param y1 the start y location in millipoints * @param x2 the end x location in millipoints * @param y2 the end y location in millipoints * @param th the thickness in millipoints * @param rs the rule style * @param stroke the line color */ protected void addLine(int x1, int y1, int x2, int y2, int th, int rs, PDFPathPaint stroke) { int dashon = 0; int dashoff = 0; //if ( rs != null && rs.length() > 5 && rs.charAt(0) == '[' && rs.charAt(1) != ']' && rs.charAt(4) == ']' ) // dashon = rs.charAt(1) - '0'; // dashoff = rs.charAt(3) - '0'; switch (rs) { case org.apache.fop.fo.properties.RuleStyle.DASHED: dashon = 3; dashoff = 3; break; case org.apache.fop.fo.properties.RuleStyle.DOTTED: dashon = 1; dashoff = 3; break; } if ( x1 == x2 ) { if ( dashon > 0 && dashoff > 0 ) { int start = y1; int len = th * dashon; while ( start < y2 ) { if ( start + len > y2 ) len = y2 - start; addRect(x1 - (th/2), start, th, len, stroke, stroke); start += (len + dashoff * th); } } else addRect(x1 - (th/2), y1, th, y2 - y1 + 1, stroke, stroke); } else if ( y1 == y2 ) { if ( dashon > 0 && dashoff > 0 ) { int start = x1; int len = th * dashon; while ( start < x2 ) { if ( start + len > x2 ) len = x2 - start; addRect(start, y1 + (th/2), len, th, stroke, stroke); start += (len + dashoff * th); } } else addRect(x1, y1 + (th/2), x2 - x1 + 1, th, stroke, stroke); } } /** * add a rectangle to the current stream * * @param x the x position of left edge in millipoints * @param y the y position of top edge in millipoints * @param w the width in millipoints * @param h the height in millipoints * @param stroke the stroke color/gradient */ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke) { if ( h < 0 ) h *= -1; if (h < 720 || w < 720) { if ( w < 720 ) w = 720; if ( h < 720 ) h = 720; addRect(x, y, w, h, stroke, stroke); } else { addRect(x, y, w, 720, stroke, stroke); addRect(x, y, 720, h, stroke, stroke); addRect(x + w - 720, y, 720, h, stroke, stroke); addRect(x, y - h + 720, w, 720, stroke, stroke); } } /** * add a filled rectangle to the current stream * * @param x the x position of left edge in millipoints * @param y the y position of top edge in millipoints * @param w the width in millipoints * @param h the height in millipoints * @param fill the fill color/gradient * @param stroke the stroke color/gradient */ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke, PDFPathPaint fill) { if ((w == 0) || (h == 0)) return; if ( h < 0 ) h *= -1; PDFColor sc = (PDFColor)stroke; PDFColor fc = (PDFColor)fill; sc.setColorSpace(ColorSpace.DEVICE_RGB); fc.setColorSpace(ColorSpace.DEVICE_RGB); int lineshade = (int)(100 - ((0.3f * sc.red() + 0.59f * sc.green() + 0.11f * sc.blue()) * 100f)); int fillshade = (int)(100 - ((0.3f * fc.red() + 0.59f * fc.green() + 0.11f * fc.blue()) * 100f)); int xpos = xoffset + (x / 100); if ( xpos < 0 ) { xpos = 0; MessageHandler.errorln("PCLRenderer.addRect() WARNING: Horizontal position out of bounds."); } currentStream.add("\033*v1O\033&a" + xpos + "h" + (pageHeight - (y / 100)) + "V" + "\033*c" + (w / 100) + "h" + (h / 100) + "V" + "\033*c" + lineshade + "G" + "\033*c2P"); if ( fillshade != lineshade && (w >= 720 || h >= 720) ) { xpos = xoffset + ((x + 240) / 100); if ( xpos < 0 ) { xpos = 0; MessageHandler.errorln("PCLRenderer.addRect() WARNING: Horizontal position out of bounds."); } currentStream.add("\033&a" + xpos + "h" + (pageHeight - ((y + 240)) / 100) + "V" + "\033*c" + ((w - 480) / 100) + "h" + ((h - 480) / 100) + "V" + "\033*c" + fillshade + "G" + "\033*c2P"); } // Reset pattern transparency mode. currentStream.add("\033*v0O"); } boolean printBMP(FopImage img, int x, int y, int w, int h) throws FopImageException { // Print the passed image file in PCL. byte imgmap[] = img.getBitmaps(); int ix = 0; int iy = 0; int indx = 0; int iw = img.getWidth(); int ih = img.getHeight(); int bytewidth = (iw / 8); if ( (iw % 8) != 0 ) bytewidth++; byte ib; char ic[] = new char[bytewidth * 2]; char icu[] = new char[bytewidth]; int lastcount = -1; byte lastbyte = 0; int icwidth = 0; int cr = 0; int cg = 0; int cb = 0; int grey = 0; boolean iscolor = img.getColorSpace().getColorSpace() != ColorSpace.DEVICE_GRAY; int dcount = 0; int xres = (iw * 72000) / w; int yres = (ih * 72000) / h; int resolution = xres; if ( yres > xres ) resolution = yres; if ( resolution > 300 ) resolution = 600; else if ( resolution > 150 ) resolution = 300; else if ( resolution > 100 ) resolution = 150; else if ( resolution > 75 ) resolution = 100; else resolution = 75; if ( debug ) System.out.println("PCLRenderer.printBMP() iscolor = " + iscolor); // Setup for graphics currentStream.add("\033*t" + resolution + "R\033*r0F\033*r1A"); // Transfer graphics data for ( iy = 0 ; iy < ih ; iy++ ) { ib = 0; //int padding = iw % 8; //if ( padding != 0 ) // padding = 8 - padding; //padding = 0; //indx = (ih - iy - 1 + padding) * iw; indx = iy * iw; if ( iscolor ) indx *= 3; //currentStream.add("\033*b" + bytewidth + "W"); for ( ix = 0 ; ix < iw ; ix++ ) { if ( iscolor ) { cr = imgmap[indx++] & 0xFF; cg = imgmap[indx++] & 0xFF; cb = imgmap[indx++] & 0xFF; grey = (cr * 30 + cg * 59 + cb * 11) / 100; } else grey = imgmap[indx++] & 0xFF; if ( grey < 128 ) ib |= (1 << (7 - (ix % 8))); if ( (ix % 8) == 7 || ((ix + 1) == iw)) { if ( icwidth < bytewidth ) { if ( lastcount >= 0 ) { if ( ib == lastbyte ) lastcount++; else { ic[icwidth++] = (char)(lastcount & 0xFF); ic[icwidth++] = (char)lastbyte; lastbyte = ib; lastcount = 0; } } else { lastbyte = ib; lastcount = 0; } if ( lastcount == 255 || ((ix + 1) == iw) ) { ic[icwidth++] = (char)(lastcount & 0xFF); ic[icwidth++] = (char)lastbyte; lastbyte = 0; lastcount = -1; } } icu[ix / 8] = (char)ib; ib = 0; } } if ( icwidth < bytewidth ) { currentStream.add("\033*b1m" + icwidth + "W"); currentStream.add(new String(ic, 0, icwidth)); } else { currentStream.add("\033*b0m" + bytewidth + "W"); currentStream.add(new String(icu)); } lastcount = -1; icwidth = 0; } // End graphics currentStream.add("\033*rB"); return(true); } /** * render image area to PCL * * @param area the image area to render */ public void renderImageArea(ImageArea area) { int x = this.currentAreaContainerXPosition + area.getXOffset(); int y = this.currentYPosition; int w = area.getContentWidth(); int h = area.getHeight(); this.currentYPosition -= h; FopImage img = area.getImage(); int xpos = xoffset + (x / 100); if ( xpos < 0 ) { xpos = 0; MessageHandler.errorln("PCLRenderer.renderImageArea() WARNING: Horizontal position out of bounds."); } currentStream.add("\033&a" + xpos + "h" + (pageHeight - (y / 100)) + "V"); try { printBMP(img, x, y, w, h); } catch ( FopImageException e ) { //e.printStackTrace(System.out); MessageHandler.errorln("PCLRenderer.renderImageArea() Error printing BMP (" + e.toString() + ")"); } } /** render a foreign object area */ public void renderForeignObjectArea(ForeignObjectArea area) { // if necessary need to scale and align the content this.currentXPosition = this.currentXPosition + area.getXOffset(); this.currentYPosition = this.currentYPosition; switch (area.getAlign()) { case TextAlign.START: break; case TextAlign.END: break; case TextAlign.CENTER: case TextAlign.JUSTIFY: break; } switch (area.getVerticalAlign()) { case VerticalAlign.BASELINE: break; case VerticalAlign.MIDDLE: break; case VerticalAlign.SUB: break; case VerticalAlign.SUPER: break; case VerticalAlign.TEXT_TOP: break; case VerticalAlign.TEXT_BOTTOM: break; case VerticalAlign.TOP: break; case VerticalAlign.BOTTOM: break; } // in general the content will not be text // align and scale switch (area.scalingMethod()) { case Scaling.UNIFORM: break; case Scaling.NON_UNIFORM: break; } // if the overflow is auto (default), scroll or visible // then the contents should not be clipped, since this // is considered a printing medium. switch (area.getOverflow()) { case Overflow.VISIBLE: case Overflow.SCROLL: case Overflow.AUTO: break; case Overflow.HIDDEN: break; } area.getObject().render(this); this.currentXPosition += area.getEffectiveWidth(); // this.currentYPosition -= area.getEffectiveHeight(); } /** * render SVG area to PCL * * @param area the SVG area to render */ public void renderSVGArea(SVGArea area) { if ( debug ) System.out.println("PCLRenderer.renderSVGArea(" + area + ")"); int x = this.currentXPosition; int y = this.currentYPosition; SVGSVGElement svg = area.getSVGDocument().getRootElement(); int w = (int)(svg.getWidth().getBaseVal().getValue() * 1000); int h = (int)(svg.getHeight().getBaseVal().getValue() * 1000); /* * Clip to the svg area. * Note: To have the svg overlay (under) a text area then use * an fo:block-container */ // TODO - translate and clip to viewbox PCLSVGRenderer svgRenderer = new PCLSVGRenderer(this, area.getFontState(), currentFontName, currentFontSize, currentXPosition, currentYPosition, pageHeight, xoffset); svgRenderer.renderSVG(svg, x, y); //currentStream.add(svgRenderer.getString()); //currentStream.add("Q\n"); } public void setFont(String name, float size) { int fontcode = 0; if ( name.length() > 1 && name.charAt(0) == 'F' ) { try { fontcode = Integer.parseInt(name.substring(1)); } catch (Exception e) { e.printStackTrace(); } } switch (fontcode) { case 1: // F1 = Helvetica //currentStream.add("\033(8U\033(s1p" + (size / 1000) + "v0s0b24580T"); // Arial is more common among PCL5 printers than Helvetica - so use Arial currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v0s0b16602T"); break; case 2: // F2 = Helvetica Oblique currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v1s0b16602T"); break; case 3: // F3 = Helvetica Bold currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v0s3b16602T"); break; case 4: // F4 = Helvetica Bold Oblique currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v1s3b16602T"); break; case 5: // F5 = Times Roman //currentStream.add("\033(8U\033(s1p" + (size / 1000) + "v0s0b25093T"); // Times New is more common among PCL5 printers than Times - so use Times New currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v0s0b16901T"); break; case 6: // F6 = Times Italic currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v1s0b16901T"); break; case 7: // F7 = Times Bold currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v0s3b16901T"); break; case 8: // F8 = Times Bold Italic currentStream.add("\033(0N\033(s1p" + (size / 1000) + "v1s3b16901T"); break; case 9: // F9 = Courier currentStream.add("\033(0N\033(s0p" + (120.01f / (size / 1000.00f)) + "h0s0b4099T"); break; case 10: // F10 = Courier Oblique currentStream.add("\033(0N\033(s0p" + (120.01f / (size / 1000.00f)) + "h1s0b4099T"); break; case 11: // F11 = Courier Bold currentStream.add("\033(0N\033(s0p" + (120.01f / (size / 1000.00f)) + "h0s3b4099T"); break; case 12: // F12 = Courier Bold Oblique currentStream.add("\033(0N\033(s0p" + (120.01f / (size / 1000.00f)) + "h1s3b4099T"); break; case 13: // F13 = Symbol currentStream.add("\033(19M\033(s1p" + (size / 1000) + "v0s0b16686T"); //currentStream.add("\033(9U\033(s1p" + (size / 1000) + "v0s0b25093T"); // ECMA Latin 1 Symbol Set in Times Roman??? break; case 14: // F14 = Zapf Dingbats currentStream.add("\033(14L\033(s1p" + (size / 1000) + "v0s0b45101T"); break; default: currentStream.add("\033(0N\033(s" + (size / 1000) + "V"); break; } } /** * render inline area to PCL * * @param area inline area to render */ public void renderWordArea(WordArea area) { String name = area.getFontState().getFontName(); int size = area.getFontState().getFontSize(); float red = area.getRed(); float green = area.getGreen(); float blue = area.getBlue(); PDFColor theAreaColor = new PDFColor((double) area.getRed(), (double) area.getGreen(), (double) area.getBlue()); //currentStream.add("\033*c" + (int)(100 - ((0.3f * red + 0.59f * green + 0.11f * blue) * 100f)) + "G\033*v2T"); currentStream.add("\033*v1O\033*c" + (int)(100 - ((0.3f * red + 0.59f * green + 0.11f * blue) * 100f)) + "G\033*v2T"); if ((!name.equals(this.currentFontName)) || (size != this.currentFontSize)) { this.currentFontName = name; this.currentFontSize = size; setFont(name, size); } this.currentFill = theAreaColor; int rx = this.currentXPosition; int bl = this.currentYPosition; String s; if ( area.getPageNumberID()!=null ) { // this text is a page number, so resolve it s = idReferences.getPageNumber(area.getPageNumberID()); if(s==null) s=""; } else { s = area.getText(); } addWordLines(area, rx, bl, size, theAreaColor); int xpos = xoffset + (rx / 100); if ( xpos < 0 ) { xpos = 0; MessageHandler.errorln("PCLRenderer.renderWordArea() WARNING: Horizontal position out of bounds."); } currentStream.add("\033&a" + xpos + "h" + (pageHeight - (bl / 100)) + "V" + s); this.currentXPosition += area.getContentWidth(); } /** * render page into PCL * * @param page page to render */ public void renderPage(Page page) { if ( debug ) System.out.println("PCLRenderer.renderPage() page.Height() = " + page.getHeight()); BodyAreaContainer body; AreaContainer before, after, start, end; if ( paperheight > 0 && divisions == -1 ) divisions = paperheight / (page.getHeight() / 100); if ( debug ) System.out.println("PCLRenderer.renderPage() paperheight=" + paperheight + " divisions=" + divisions); // Set top margin. //float fullmargin = 0; if ( divisions > 0 ) fullmargin = paperheight * curdiv / divisions; if ( topmargin > 0 ) fullmargin += topmargin; if ( debug ) System.out.println("PCLRenderer.renderPage() curdiv=" + curdiv + " fullmargin=" + fullmargin); //if ( fullmargin > 0 ) // currentStream.add("\033&l" + (fullmargin / 15f) + "c1e8C"); //this.currentYPosition = fullmargin * 100; if ( paperheight > 0 ) pageHeight = (paperheight / divisions) + fullmargin; else pageHeight = page.getHeight() / 100; if ( debug ) System.out.println("PCLRenderer.renderPage() Set currentYPosition=" + this.currentYPosition); if ( leftmargin > 0 && curdiv == 0 ) currentStream.add("\033&k" + (leftmargin / 6f) + "H\033&a1L\033&k12H"); body = page.getBody(); before = page.getBefore(); after = page.getAfter(); start = page.getStart(); end = page.getEnd(); this.currentFontName = ""; this.currentFontSize = 0; renderBodyAreaContainer(body); if (before != null) renderAreaContainer(before); if (after != null) renderAreaContainer(after); if (start != null) renderAreaContainer(start); if (end != null) renderAreaContainer(end); // End page. if ( ++curdiv == divisions || divisions == -1 ) { curdiv = 0; currentStream.add("\f"); } // Links, etc not implemented... /* currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream, page.getWidth()/1000, page.getHeight()/1000, page); if (page.hasLinks()) { currentAnnotList = this.pdfDoc.makeAnnotList(); currentPage.setAnnotList(currentAnnotList); Enumeration e = page.getLinkSets().elements(); while (e.hasMoreElements()) { LinkSet linkSet = (LinkSet) e.nextElement(); linkSet.align(); String dest = linkSet.getDest(); int linkType = linkSet.getLinkType(); Enumeration f = linkSet.getRects().elements(); while (f.hasMoreElements()) { LinkedRectangle lrect = (LinkedRectangle) f.nextElement(); currentAnnotList.addLink( this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType)); } } } else { // just to be on the safe side currentAnnotList = null; } */ } }
package org.apache.xerces.framework; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.FileNotFoundException; import java.io.Reader; import java.net.URL; import java.net.MalformedURLException; import java.util.Locale; import java.util.Hashtable; import java.util.ResourceBundle; import java.util.Stack; import java.util.ListResourceBundle; import org.apache.xerces.readers.DefaultReaderFactory; import org.apache.xerces.readers.XMLDeclRecognizer; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.readers.XMLEntityReaderFactory; import org.apache.xerces.utils.ChunkyByteArray; import org.apache.xerces.utils.ChunkyCharArray; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.apache.xerces.utils.XMLMessageProvider; import org.apache.xerces.utils.XMLMessages; import org.apache.xerces.utils.ImplementationMessages; // REVISIT - use component factory import org.apache.xerces.validators.dtd.DTDValidator; import org.apache.xerces.validators.schema.XSchemaValidator; import org.apache.xerces.validators.datatype.DatatypeMessageProvider; import org.apache.xerces.validators.schema.SchemaMessageProvider; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.Parser; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.LocatorImpl; /** * This is the base class of all standard parsers. * * @version */ public abstract class XMLParser implements XMLErrorReporter, XMLEntityHandler, XMLDocumentScanner.EventHandler, DTDValidator.EventHandler, Locator { // Constants // protected protected static final String SAX2_FEATURES_PREFIX = "http://xml.org/sax/features/"; protected static final String SAX2_PROPERTIES_PREFIX = "http://xml.org/sax/properties/"; protected static final String XERCES_FEATURES_PREFIX = "http://apache.org/xml/features/"; protected static final String XERCES_PROPERTIES_PREFIX = "http://apache.org/xml/properties/"; // private /** Features recognized by this parser. */ private static final String RECOGNIZED_FEATURES[] = { // SAX2 core "http://xml.org/sax/features/validation", "http://xml.org/sax/features/external-general-entities", "http://xml.org/sax/features/external-parameter-entities", "http://xml.org/sax/features/namespaces", // Xerces "http://apache.org/xml/features/validation/dynamic", "http://apache.org/xml/features/validation/default-attribute-values", "http://apache.org/xml/features/validation/validate-content-models", "http://apache.org/xml/features/validation/validate-datatypes", "http://apache.org/xml/features/validation/warn-on-duplicate-attdef", "http://apache.org/xml/features/validation/warn-on-undeclared-elemdef", "http://apache.org/xml/features/allow-java-encodings", "http://apache.org/xml/features/continue-after-fatal-error", }; /** Properties recognized by this parser. */ private static final String RECOGNIZED_PROPERTIES[] = { // SAX2 core "http://xml.org/sax/properties/namespace-sep", "http://xml.org/sax/properties/xml-string", // Xerces }; // debugging /** Set to true and recompile to print exception stack trace. */ private static final boolean PRINT_EXCEPTION_STACK_TRACE = false; // Data // state private XMLAttrList fAttrList = null; protected boolean fParseInProgress = false; private boolean fNeedReset = false; // features /** Continue after fatal error. */ private boolean fContinueAfterFatalError; // properties /** Error handler. */ private ErrorHandler fErrorHandler; // literal strings private char[] fCharRefData = null; private int[] fElementTypeStack = new int[8]; private int[] fElementEntityStack = new int[8]; private boolean fCalledStartDocument = false; private int fXMLLang = -1; protected String fNamespaceSep = ""; // validators protected XMLValidator fValidator = null; protected DTDValidator fDTDValidator = null; protected XSchemaValidator fSchemaValidator = null; private boolean fCheckedForSchema = false; // other private Locator fLocator = null; private Locale fLocale = null; private LocatorImpl fAttrNameLocator = null; private boolean fSeenRootElement = false; private boolean fStandaloneDocument = false; private int fCDATASymbol = -1; protected boolean fNamespacesEnabled = false; private boolean fSendCharDataAsCharArray = false; private boolean fValidating = false; private boolean fScanningDTD = false; private StringPool.CharArrayRange fCurrentElementCharArrayRange = null; // error information private static XMLMessageProvider fgXMLMessages = new XMLMessages(); private static XMLMessageProvider fgImplementationMessages = new ImplementationMessages(); private static XMLMessageProvider fgSchemaMessages = new SchemaMessageProvider(); private static XMLMessageProvider fgDatatypeMessages= new DatatypeMessageProvider(); protected XMLDocumentScanner fScanner = null; protected StringPool fStringPool = null; protected XMLErrorReporter fErrorReporter = null; protected XMLEntityHandler fEntityHandler = null; protected XMLEntityReaderFactory fReaderFactory = null; protected int fElementDepth = 0; protected int fCurrentElementType = -1; protected int fCurrentElementEntity = -1; protected boolean fInElementContent = false; // Constructors /** * Constructor */ protected XMLParser() { fStringPool = new StringPool(); fErrorReporter = this; fEntityHandler = this; // set framework properties fScanner = new XMLDocumentScanner(/*XMLDocumentScanner.EventHandler*/this, fStringPool, fErrorReporter, fEntityHandler, new ChunkyCharArray(fStringPool)); // other inits XMLCharacterProperties.initCharFlags(); fAttrList = new XMLAttrList(fStringPool); fLocator = this; fReaderFactory = new DefaultReaderFactory(); // REVISIT - add all other instance variables... fCDATASymbol = fStringPool.addSymbol("CDATA"); fDTDValidator = new DTDValidator(/*DTDValidator.EventHandler*/this, fStringPool, fErrorReporter, fEntityHandler); // set features try { setContinueAfterFatalError(false); } catch (SAXException e) {} // ignore } // <init>() // Public methods // features and properties /** * Returns a list of features that this parser recognizes. * This method will never return null; if no features are * recognized, this method will return a zero length array. * * @see #isFeatureRecognized * @see #setFeature * @see #getFeature */ public String[] getFeaturesRecognized() { return RECOGNIZED_FEATURES; } /** * Returns true if the specified feature is recognized. * * @see #getFeaturesRecognized * @see #setFeature * @see #getFeature */ public boolean isFeatureRecognized(String featureId) { String[] recognizedFeatures = getFeaturesRecognized(); for (int i = 0; i < recognizedFeatures.length; i++) { if (featureId.equals(recognizedFeatures[i])) return true; } return false; } /** * Returns a list of properties that this parser recognizes. * This method will never return null; if no properties are * recognized, this method will return a zero length array. * * @see #isPropertyRecognized * @see #setProperty * @see #getProperty */ public String[] getPropertiesRecognized() { return RECOGNIZED_PROPERTIES; } /** * Returns true if the specified property is recognized. * * @see #getPropertiesRecognized * @see #setProperty * @see #getProperty */ public boolean isPropertyRecognized(String propertyId) { String[] recognizedProperties = getPropertiesRecognized(); for (int i = 0; i < recognizedProperties.length; i++) { if (propertyId.equals(recognizedProperties[i])) return true; } return false; } // initialization /** * Setup for application-driven parsing. * * @param source the input source to be parsed. * @see #parseSome */ public boolean parseSomeSetup(InputSource source) throws Exception { if (fNeedReset) resetOrCopy(); fParseInProgress = true; fNeedReset = true; return fEntityHandler.startReadingFromDocument(source); } /** * Application-driven parsing. * * @see #parseSomeSetup */ public boolean parseSome() throws Exception { if (!fScanner.parseSome(false)) { fParseInProgress = false; return false; } return true; } // resetting /** Reset parser instance so that it can be reused. */ public void reset() throws Exception { fStringPool.reset(); fAttrList.reset(fStringPool); resetCommon(); } // reset() // properties (the normal kind) /** * Sets the locator. * * @param locator The new locator. */ public void setLocator(Locator locator) { fLocator = locator; } /** * return the locator being used by the parser * * @return the parser's active locator */ public final Locator getLocator() { return fLocator; } /** * Set the reader factory. */ public void setReaderFactory(XMLEntityReaderFactory readerFactory) { fReaderFactory = readerFactory; fReaderFactory.setSendCharDataAsCharArray(fSendCharDataAsCharArray); } // DTD callbacks /** * Callback for processing instruction in DTD. * * @param target the string pool index of the PI's target * @param data the string pool index of the PI's data * @exception java.lang.Exception */ public void processingInstructionInDTD(int target, int data) throws Exception { fStringPool.releaseString(target); fStringPool.releaseString(data); } /** * Callback for comment in DTD. * * @param comment the string pool index of the comment text * @exception java.lang.Exception */ public void commentInDTD(int comment) throws Exception { fStringPool.releaseString(comment); } // Public abstract methods // document callbacks /** * Callback for start of document * * If the there is no version info, encoding info, or standalone info, * the corresponding argument will be set to -1. * * @param version string pool index of the version attribute's value * @param encoding string pool index of the encoding attribute's value * @param standAlone string pool index of the standalone attribute's value * @exception java.lang.Exception */ public abstract void startDocument(int version, int encoding, int standAlone) throws Exception; /** * callback for the end of document. * * @exception java.lang.Exception */ public abstract void endDocument() throws Exception; /** * callback for the start of a namespace declaration scope. * * @param prefix string pool index of the namespace prefix being declared * @param uri string pool index of the namespace uri begin bound * @param java.lang.Exception */ public abstract void startNamespaceDeclScope(int prefix, int uri) throws Exception; /** * callback for the end a namespace declaration scope. * * @param prefix string pool index of the namespace prefix being declared * @exception java.lang.Exception */ public abstract void endNamespaceDeclScope(int prefix) throws Exception; /** * Supports DOM Level 2 internalSubset additions. * Called when the internal subset is completely scanned. */ public abstract void internalSubset(int internalSubset); /** * callback for the start of element. * * @param elementType element handle for the element being scanned * @param attrList attrList containing the attributes of the element * @param attrListHandle handle into attrList. Allows attributes to be retreived. * @exception java.lang.Exception */ public abstract void startElement(int elementType, XMLAttrList attrList, int attrListHandle) throws Exception; /** * callback for end of element. * * @param elementType element handle for the element being scanned * @exception java.lang.Exception */ public abstract void endElement(int elementType) throws Exception; /** * callback for start of entity reference. * * @param entityName string pool index of the entity name * @param entityType the XMLEntityHandler.ENTITYTYPE_* type * @see org.apache.xerces.readers.XMLEntityHandler * @param entityContext the XMLEntityHandler.CONTEXT_* type for where * the entity reference appears * @see org.apache.xerces.readers.XMLEntityHandler * @exception java.lang.Exception */ public abstract void startEntityReference(int entityName, int entityType, int entityContext) throws Exception; /** * callback for end of entity reference. * * @param entityName string pool index of the entity anem * @param entityType the XMLEntityHandler.ENTITYTYPE_* type * @see org.apache.xerces.readers.XMLEntityHandler * @param entityContext the XMLEntityHandler.CONTEXT_* type for where * the entity reference appears * @see org.apache.xerces.readers.XMLEntityHandler * @exception java.lang.Exception */ public abstract void endEntityReference(int entityName, int entityType, int entityContext) throws Exception; /** * callback for start of CDATA section. * this callback marks the start of a CDATA section * * @exception java.lang.Exception */ public abstract void startCDATA() throws Exception; /** * callback for end of CDATA section. * this callback marks the end of a CDATA section * * @exception java.lang.Exception */ public abstract void endCDATA() throws Exception; /** * callback for processing instruction. * * @param target string pool index of the PI target * @param data string pool index of the PI data * @exception java.lang.Exception */ public abstract void processingInstruction(int target, int data) throws Exception; /** * callback for comment. * * @param comment string pool index of the comment text * @exception java.lang.Exception */ public abstract void comment(int comment) throws Exception; /** * callback for characters (string pool form). * * @param data string pool index of the characters that were scanned * @exception java.lang.Exception */ public abstract void characters(int data) throws Exception; /** * callback for characters. * * @param ch character array containing the characters that were scanned * @param start offset in ch where scanned characters begin * @param length length of scanned characters in ch * @exception java.lang.Exception */ public abstract void characters(char ch[], int start, int length) throws Exception; /** * callback for ignorable whitespace. * * @param data string pool index of ignorable whitespace * @exception java.lang.Exception */ public abstract void ignorableWhitespace(int data) throws Exception; /** * callback for ignorable whitespace. * * @param ch character array containing the whitespace that was scanned * @param start offset in ch where scanned whitespace begins * @param length length of scanned whitespace in ch * @exception java.lang.Exception */ public abstract void ignorableWhitespace(char ch[], int start, int length) throws Exception; // DTD callbacks /** * callback for the start of the DTD * This function will be called when a &lt;!DOCTYPE...&gt; declaration is * encountered. * * @param rootElementType element handle for the root element of the document * @param publicId string pool index of the DTD's public ID * @param systemId string pool index of the DTD's system ID * @exception java.lang.Exception */ public abstract void startDTD(int rootElementType, int publicId, int systemId) throws Exception; /** * callback for the end of the DTD * This function will be called at the end of the DTD. */ public abstract void endDTD() throws Exception; /** * callback for an element declaration. * * @param elementType element handle of the element being declared * @param contentSpec contentSpec for the element being declared * @see XMLValidator.ContentSpec * @exception java.lang.Exception */ public abstract void elementDecl(int elementType, XMLValidator.ContentSpec contentSpec) throws Exception; /** * callback for an attribute list declaration. * * @param elementType element handle for the attribute's element * @param attrName string pool index of the attribute name * @param attType type of attribute * @param enumString String representing the values of the enumeration, * if the attribute is of enumerated type, or null if it is not. * @param attDefaultType an integer value denoting the DefaultDecl value * @param attDefaultValue string pool index of this attribute's default value * or -1 if there is no defaultvalue * @exception java.lang.Exception */ public abstract void attlistDecl(int elementType, int attrName, int attType, String enumString, int attDefaultType, int attDefaultValue) throws Exception; /** * callback for an internal parameter entity declaration. * * @param entityName string pool index of the entity name * @param entityValue string pool index of the entity replacement text * @exception java.lang.Exception */ public abstract void internalPEDecl(int entityName, int entityValue) throws Exception; /** * callback for an external parameter entity declaration. * * @param entityName string pool index of the entity name * @param publicId string pool index of the entity's public id. * @param systemId string pool index of the entity's system id. * @exception java.lang.Exception */ public abstract void externalPEDecl(int entityName, int publicId, int systemId) throws Exception; /** * callback for internal general entity declaration. * * @param entityName string pool index of the entity name * @param entityValue string pool index of the entity replacement text * @exception java.lang.Exception */ public abstract void internalEntityDecl(int entityName, int entityValue) throws Exception; /** * callback for external general entity declaration. * * @param entityName string pool index of the entity name * @param publicId string pool index of the entity's public id. * @param systemId string pool index of the entity's system id. * @exception java.lang.Exception */ public abstract void externalEntityDecl(int entityName, int publicId, int systemId) throws Exception; /** * callback for an unparsed entity declaration. * * @param entityName string pool index of the entity name * @param publicId string pool index of the entity's public id. * @param systemId string pool index of the entity's system id. * @param notationName string pool index of the notation name. * @exception java.lang.Exception */ public abstract void unparsedEntityDecl(int entityName, int publicId, int systemId, int notationName) throws Exception; /** * callback for a notation declaration. * * @param notationName string pool index of the notation name * @param publicId string pool index of the notation's public id. * @param systemId string pool index of the notation's system id. * @exception java.lang.Exception */ public abstract void notationDecl(int notationName, int publicId, int systemId) throws Exception; // Protected methods // SAX2 core features protected void setValidation(boolean validate) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/validation): parse is in progress.\n"+ "http://xml.org/sax/features/validation"); } try { fDTDValidator.setValidationEnabled(validate); getSchemaValidator().setValidationEnabled(validate); } catch (Exception ex) { throw new SAXNotSupportedException(ex.getMessage()); } } /** * Returns true if validation is turned on. * * @see #setValidation */ protected boolean getValidation() throws SAXNotRecognizedException, SAXNotSupportedException { return fDTDValidator.getValidationEnabled(); } protected void setExternalGeneralEntities(boolean expand) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/external-general-entities): parse is in progress.\n"+ "http://xml.org/sax/features/external-general-entities"); } if (!expand) { throw new SAXNotSupportedException("http://xml.org/sax/features/external-general-entities"); } } /** * <b>Note: This feature is always true.</b> * <p> * Returns true if external general entities are expanded. * * @see #setExternalGeneralEntities */ protected boolean getExternalGeneralEntities() throws SAXNotRecognizedException, SAXNotSupportedException { return true; } protected void setExternalParameterEntities(boolean expand) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/external-general-entities): parse is in progress.\n"+ "http://xml.org/sax/features/external-general-entities"); } if (!expand) { throw new SAXNotSupportedException("http://xml.org/sax/features/external-parameter-entities"); } } /** * <b>Note: This feature is always true.</b> * <p> * Returns true if external parameter entities are expanded. * * @see #setExternalParameterEntities */ protected boolean getExternalParameterEntities() throws SAXNotRecognizedException, SAXNotSupportedException { return true; } protected void setNamespaces(boolean process) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/namespaces): parse is in progress.\n"+ "http://xml.org/sax/features/namespaces"); } fNamespacesEnabled = process; fDTDValidator.setNamespacesEnabled(process); getSchemaValidator().setNamespacesEnabled(process); } /** * Returns true if the parser preprocesses namespaces. * * @see #setNamespaces */ protected boolean getNamespaces() throws SAXNotRecognizedException, SAXNotSupportedException { return fNamespacesEnabled; } // Xerces features protected void setValidationDynamic(boolean dynamic) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { // REVISIT: Localize this message. -Ac throw new SAXNotSupportedException("http://apache.org/xml/features/validation/dynamic: parse is in progress"); } try { fDTDValidator.setDynamicValidationEnabled(dynamic); getSchemaValidator().setDynamicValidationEnabled(dynamic); } catch (Exception ex) { throw new SAXNotSupportedException(ex.getMessage()); } } /** * Returns true if validation is based on whether a document * contains a grammar. * * @see #setValidationDynamic */ protected boolean getValidationDynamic() throws SAXNotRecognizedException, SAXNotSupportedException { return fDTDValidator.getDynamicValidationEnabled(); } protected void setValidationWarnOnDuplicateAttdef(boolean warn) throws SAXNotRecognizedException, SAXNotSupportedException { fDTDValidator.setWarningOnDuplicateAttDef(warn); getSchemaValidator().setWarningOnDuplicateAttDef(warn); } /** * Returns true if an error is emitted when an attribute is redefined * in the grammar. * * @see #setValidationWarnOnDuplicateAttdef */ protected boolean getValidationWarnOnDuplicateAttdef() throws SAXNotRecognizedException, SAXNotSupportedException { return fDTDValidator.getWarningOnDuplicateAttDef(); } protected void setValidationWarnOnUndeclaredElemdef(boolean warn) throws SAXNotRecognizedException, SAXNotSupportedException { fDTDValidator.setWarningOnUndeclaredElements(warn); getSchemaValidator().setWarningOnUndeclaredElements(warn); } /** * Returns true if the parser emits an error when an undeclared * element is referenced in the grammar. * * @see #setValidationWarnOnUndeclaredElemdef */ protected boolean getValidationWarnOnUndeclaredElemdef() throws SAXNotRecognizedException, SAXNotSupportedException { return fDTDValidator.getWarningOnUndeclaredElements(); } protected void setAllowJavaEncodings(boolean allow) throws SAXNotRecognizedException, SAXNotSupportedException { fReaderFactory.setAllowJavaEncodingName(allow); } /** * Returns true if Java encoding names are allowed in the XML document. * * @see #setAllowJavaEncodings */ protected boolean getAllowJavaEncodings() throws SAXNotRecognizedException, SAXNotSupportedException { return fReaderFactory.getAllowJavaEncodingName(); } protected void setContinueAfterFatalError(boolean continueAfterFatalError) throws SAXNotRecognizedException, SAXNotSupportedException { fContinueAfterFatalError = continueAfterFatalError; } /** * Returns true if the parser continues after a fatal error. * * @see #setContinueAfterFatalError */ protected boolean getContinueAfterFatalError() throws SAXNotRecognizedException, SAXNotSupportedException { return fContinueAfterFatalError; } // SAX2 core properties protected void setNamespaceSep(String separator) throws SAXNotRecognizedException, SAXNotSupportedException { // REVISIT: Ask someone what it could possibly hurt to allow // the application to change this in mid-parse. if (fParseInProgress) { // REVISIT: Localize this message. throw new SAXNotSupportedException("http://xml.org/sax/properties/namespace-sep: parse is in progress"); } fNamespaceSep = separator; } /** * Returns the namespace separator. * * @see #setNamespaceSep */ protected String getNamespaceSep() throws SAXNotRecognizedException, SAXNotSupportedException { return fNamespaceSep; } protected String getXMLString() throws SAXNotRecognizedException, SAXNotSupportedException { throw new SAXNotSupportedException("http://xml.org/sax/properties/xml-string"); } // resetting /** * Reset or copy parser * Allows parser instance reuse */ protected void resetOrCopy() throws Exception { fStringPool = new StringPool(); fAttrList = new XMLAttrList(fStringPool); resetCommon(); } // resetOrCopy() private void resetCommon() throws Exception { fScanner.reset(fStringPool, new ChunkyCharArray(fStringPool)); fValidating = false; fScanningDTD = false; resetEntityHandler(); fValidator = null; fDTDValidator.reset(fStringPool); if (fSchemaValidator != null) fSchemaValidator.reset(fStringPool, fErrorReporter, fEntityHandler); fCheckedForSchema = false; fNeedReset = false; fCalledStartDocument = false; fSeenRootElement = false; fStandaloneDocument = false; fCDATASymbol = fStringPool.addSymbol("CDATA"); fXMLLang = -1; // REVISIT - add all other instance variables... fElementDepth = 0; fCurrentElementType = -1; fCurrentElementEntity = -1; fInElementContent = false; } // properties /** Returns the XML Schema validator. */ protected XSchemaValidator getSchemaValidator() { if (fSchemaValidator == null) fSchemaValidator = new XSchemaValidator(fStringPool, fErrorReporter, fEntityHandler); return fSchemaValidator; } /** * Set char data processing preference. */ protected void setSendCharDataAsCharArray(boolean flag) { fSendCharDataAsCharArray = flag; fReaderFactory.setSendCharDataAsCharArray(fSendCharDataAsCharArray); } // Parser/XMLReader methods // NOTE: This class does *not* implement the org.xml.sax.Parser // interface but it does share some common methods. -Ac // handlers /** * Sets the resolver used to resolve external entities. The EntityResolver * interface supports resolution of public and system identifiers. * * @param resolver The new entity resolver. Passing a null value will * uninstall the currently installed resolver. */ public void setEntityResolver(EntityResolver resolver) { fEntityResolver = resolver; } /** * Return the current entity resolver. * * @return The current entity resolver, or null if none * has been registered. * @see #setEntityResolver */ public EntityResolver getEntityResolver() { return fEntityResolver; } /** * Sets the error handler. * * @param handler The new error handler. */ public void setErrorHandler(ErrorHandler handler) { fErrorHandler = handler; } /** * Return the current error handler. * * @return The current error handler, or null if none * has been registered. * @see #setErrorHandler */ public ErrorHandler getErrorHandler() { return fErrorHandler; } // parsing /** * Parses the specified input source. * * @param source The input source. * * @exception org.xml.sax.SAXException Throws exception on SAX error. * @exception java.io.IOException Throws exception on i/o error. */ public void parse(InputSource source) throws SAXException, IOException { if (fParseInProgress) { throw new org.xml.sax.SAXException("FWK005 parse may not be called while parsing."); // REVISIT - need to add new error message } try { if (parseSomeSetup(source)) { fScanner.parseSome(true); } fParseInProgress = false; } catch (org.xml.sax.SAXException ex) { fParseInProgress = false; if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (IOException ex) { fParseInProgress = false; if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (Exception ex) { fParseInProgress = false; if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw new org.xml.sax.SAXException(ex); } } // parse(InputSource) /** * Parses the input source specified by the given system identifier. * <p> * This method is equivalent to the following: * <pre> * parse(new InputSource(systemId)); * </pre> * * @param source The input source. * * @exception org.xml.sax.SAXException Throws exception on SAX error. * @exception java.io.IOException Throws exception on i/o error. */ public void parse(String systemId) throws SAXException, IOException { InputSource source = new InputSource(systemId); parse(source); try { Reader reader = source.getCharacterStream(); if (reader != null) { reader.close(); } else { InputStream is = source.getByteStream(); if (is != null) { is.close(); } } } catch (IOException e) { // ignore } } // parse(String) // locale /** * Set the locale to use for messages. * * @param locale The locale object to use for localization of messages. * * @exception SAXException An exception thrown if the parser does not * support the specified locale. * * @see org.xml.sax.Parser */ public void setLocale(Locale locale) throws SAXException { if (fParseInProgress) { throw new org.xml.sax.SAXException("FWK006 setLocale may not be called while parsing"); // REVISIT - need to add new error message } fLocale = locale; fgXMLMessages.setLocale(locale); fgImplementationMessages.setLocale(locale); } // setLocale(Locale) // resolver // XMLErrorReporter methods /** * Report an error. * * @param locator Location of error. * @param errorDomain The error domain. * @param majorCode The major code of the error. * @param minorCode The minor code of the error. * @param args Arguments for replacement text. * @param errorType The type of the error. * * @exception Exception Thrown on error. * * @see XMLErrorReporter#ERRORTYPE_WARNING * @see XMLErrorReporter#ERRORTYPE_FATAL_ERROR */ public void reportError(Locator locator, String errorDomain, int majorCode, int minorCode, Object args[], int errorType) throws Exception { // create the appropriate message SAXParseException spe; if (errorDomain.equals(XMLMessages.XML_DOMAIN)) { spe = new SAXParseException(fgXMLMessages.createMessage(fLocale, majorCode, minorCode, args), locator); } else if (errorDomain.equals(XMLMessages.XMLNS_DOMAIN)) { spe = new SAXParseException(fgXMLMessages.createMessage(fLocale, majorCode, minorCode, args), locator); } else if (errorDomain.equals(ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN)) { spe = new SAXParseException(fgImplementationMessages.createMessage(fLocale, majorCode, minorCode, args), locator); } else if (errorDomain.equals(SchemaMessageProvider.SCHEMA_DOMAIN)) { spe = new SAXParseException(fgSchemaMessages.createMessage(fLocale, majorCode, minorCode, args), locator); } else if (errorDomain.equals(DatatypeMessageProvider.DATATYPE_DOMAIN)) { spe = new SAXParseException(fgDatatypeMessages.createMessage(fLocale, majorCode, minorCode, args), locator); } else { throw new RuntimeException("FWK007 Unknown error domain \"" + errorDomain + "\"."+"\n"+errorDomain); } // default error handling if (fErrorHandler == null) { if (errorType == XMLErrorReporter.ERRORTYPE_FATAL_ERROR && !fContinueAfterFatalError) { throw spe; } return; } // make appropriate callback if (errorType == XMLErrorReporter.ERRORTYPE_WARNING) { fErrorHandler.warning(spe); } else if (errorType == XMLErrorReporter.ERRORTYPE_FATAL_ERROR) { fErrorHandler.fatalError(spe); if (!fContinueAfterFatalError) { Object[] fatalArgs = { spe.getMessage() }; throw new SAXException(fgImplementationMessages.createMessage(fLocale, ImplementationMessages.FATAL_ERROR, 0, fatalArgs)); } } else { fErrorHandler.error(spe); } } // reportError(Locator,String,int,int,Object[],int) // Configurable methods // This interface is no longer a part of SAX2. These methods have // been added directly to the new XMLReader interface. In addition, // the throws clause has changed from throws SAXException to throws // SAXNotRecognizedException, SAXNotSupportedException /** * Set the state of a feature. * * Set the state of any feature in a SAX2 parser. The parser * might not recognize the feature, and if it does recognize * it, it might not be able to fulfill the request. * * @param featureId The unique identifier (URI) of the feature. * @param state The requested state of the feature (true or false). * * @exception org.xml.sax.SAXNotRecognizedException If the * requested feature is not known. * @exception org.xml.sax.SAXNotSupportedException If the * requested feature is known, but the requested * state is not supported. * @exception org.xml.sax.SAXException If there is any other * problem fulfilling the request. */ public void setFeature(String featureId, boolean state) throws SAXNotRecognizedException, SAXNotSupportedException { // SAX2 Features if (featureId.startsWith(SAX2_FEATURES_PREFIX)) { String feature = featureId.substring(SAX2_FEATURES_PREFIX.length()); // Validate (true) or don't validate (false). if (feature.equals("validation")) { setValidation(state); return; } // Expand external general entities (true) or don't expand (false). if (feature.equals("external-general-entities")) { setExternalGeneralEntities(state); return; } // Expand external parameter entities (true) or don't expand (false). if (feature.equals("external-parameter-entities")) { setExternalParameterEntities(state); return; } // Preprocess namespaces (true) or don't preprocess (false). See also if (feature.equals("namespaces")) { setNamespaces(state); return; } // Not recognized } // Xerces Features else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) { String feature = featureId.substring(XERCES_FEATURES_PREFIX.length()); // Allows the parser to validate a document only when it // contains a grammar. Validation is turned on/off based // on each document instance, automatically. if (feature.equals("validation/dynamic")) { setValidationDynamic(state); return; } if (feature.equals("validation/default-attribute-values")) { // REVISIT throw new SAXNotSupportedException(featureId); } if (feature.equals("validation/validate-content-models")) { // REVISIT throw new SAXNotSupportedException(featureId); } if (feature.equals("validation/validate-datatypes")) { // REVISIT throw new SAXNotSupportedException(featureId); } // Emits an error when an attribute is redefined. if (feature.equals("validation/warn-on-duplicate-attdef")) { setValidationWarnOnDuplicateAttdef(state); return; } // Emits an error when an element's content model // references an element, by name, that is not declared // in the grammar. if (feature.equals("validation/warn-on-undeclared-elemdef")) { setValidationWarnOnUndeclaredElemdef(state); return; } // Allows the use of Java encoding names in the XML // and TextDecl lines. if (feature.equals("allow-java-encodings")) { setAllowJavaEncodings(state); return; } // Allows the parser to continue after a fatal error. // Normally, a fatal error would stop the parse. if (feature.equals("continue-after-fatal-error")) { setContinueAfterFatalError(state); return; } // Not recognized } // Not recognized throw new SAXNotRecognizedException(featureId); } // setFeature(String,boolean) /** * Query the state of a feature. * * Query the current state of any feature in a SAX2 parser. The * parser might not recognize the feature. * * @param featureId The unique identifier (URI) of the feature * being set. * @return The current state of the feature. * @exception org.xml.sax.SAXNotRecognizedException If the * requested feature is not known. * @exception org.xml.sax.SAXException If there is any other * problem fulfilling the request. */ public boolean getFeature(String featureId) throws SAXNotRecognizedException, SAXNotSupportedException { // SAX2 Features if (featureId.startsWith(SAX2_FEATURES_PREFIX)) { String feature = featureId.substring(SAX2_FEATURES_PREFIX.length()); // Validate (true) or don't validate (false). if (feature.equals("validation")) { return getValidation(); } // Expand external general entities (true) or don't expand (false). if (feature.equals("external-general-entities")) { return getExternalGeneralEntities(); } // Expand external parameter entities (true) or don't expand (false). if (feature.equals("external-parameter-entities")) { return getExternalParameterEntities(); } // Preprocess namespaces (true) or don't preprocess (false). See also if (feature.equals("namespaces")) { return getNamespaces(); } // Not recognized } // Xerces Features else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) { String feature = featureId.substring(XERCES_FEATURES_PREFIX.length()); // Allows the parser to validate a document only when it // contains a grammar. Validation is turned on/off based // on each document instance, automatically. if (feature.equals("validation/dynamic")) { return getValidationDynamic(); } if (feature.equals("validation/default-attribute-values")) { // REVISIT throw new SAXNotRecognizedException(featureId); } if (feature.equals("validation/validate-content-models")) { // REVISIT throw new SAXNotRecognizedException(featureId); } if (feature.equals("validation/validate-datatypes")) { // REVISIT throw new SAXNotRecognizedException(featureId); } // Emits an error when an attribute is redefined. if (feature.equals("validation/warn-on-duplicate-attdef")) { return getValidationWarnOnDuplicateAttdef(); } // Emits an error when an element's content model // references an element, by name, that is not declared // in the grammar. if (feature.equals("validation/warn-on-undeclared-elemdef")) { return getValidationWarnOnUndeclaredElemdef(); } // Allows the use of Java encoding names in the XML // and TextDecl lines. if (feature.equals("allow-java-encodings")) { return getAllowJavaEncodings(); } // Allows the parser to continue after a fatal error. // Normally, a fatal error would stop the parse. if (feature.equals("continue-after-fatal-error")) { return getContinueAfterFatalError(); } // Not recognized } // Not recognized throw new SAXNotRecognizedException(featureId); } // getFeature(String):boolean /** * Set the value of a property. * * Set the value of any property in a SAX2 parser. The parser * might not recognize the property, and if it does recognize * it, it might not support the requested value. * * @param propertyId The unique identifier (URI) of the property * being set. * @param Object The value to which the property is being set. * @exception org.xml.sax.SAXNotRecognizedException If the * requested property is not known. * @exception org.xml.sax.SAXNotSupportedException If the * requested property is known, but the requested * value is not supported. * @exception org.xml.sax.SAXException If there is any other * problem fulfilling the request. */ public void setProperty(String propertyId, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { // SAX2 Properties if (propertyId.startsWith(SAX2_PROPERTIES_PREFIX)) { String property = propertyId.substring(SAX2_PROPERTIES_PREFIX.length()); // Value type: String // Access: read/write, pre-parse only // Set the separator to be used between the URI part of a name and the // local part of a name when namespace processing is being performed // default, the separator is a single space. This property may not be // set while a parse is in progress (throws a SAXNotSupportedException). if (property.equals("namespace-sep")) { try { setNamespaceSep((String)value); } catch (ClassCastException e) { throw new SAXNotSupportedException(propertyId); } return; } // Value type: String // Access: read-only // Get the literal string of characters associated with the current // event. If the parser recognises and supports this property but is // not currently parsing text, it should return null (this is a good // way to check for availability before the parse begins). if (property.equals("xml-string")) { // REVISIT - we should probably ask xml-dev for a precise definition // of what this is actually supposed to return, and in exactly which // circumstances. throw new SAXNotSupportedException(propertyId); } // Not recognized } // SAX2 Handlers /* else if (propertyId.startsWith(SAX2_HANDLERS_PREFIX)) { // // No handlers defined yet that are common to all parsers. // } */ // Xerces Properties /* else if (propertyId.startsWith(XERCES_PROPERTIES_PREFIX)) { // // No properties defined yet that are common to all parsers. // } */ // Not recognized throw new SAXNotRecognizedException(propertyId); } // setProperty(String,Object) /** * Query the value of a property. * * Return the current value of a property in a SAX2 parser. * The parser might not recognize the property. * * @param propertyId The unique identifier (URI) of the property * being set. * @return The current value of the property. * @exception org.xml.sax.SAXNotRecognizedException If the * requested property is not known. * @exception org.xml.sax.SAXException If there is any other * problem fulfilling the request. * @see org.xml.sax.Configurable#getProperty */ public Object getProperty(String propertyId) throws SAXNotRecognizedException, SAXNotSupportedException { // SAX2 Properties if (propertyId.startsWith(SAX2_PROPERTIES_PREFIX)) { String property = propertyId.substring(SAX2_PROPERTIES_PREFIX.length()); // Value type: String // Access: read/write, pre-parse only // Set the separator to be used between the URI part of a name and the // local part of a name when namespace processing is being performed // default, the separator is a single space. This property may not be // set while a parse is in progress (throws a SAXNotSupportedException). if (property.equals("namespace-sep")) { return getNamespaceSep(); } // Value type: String // Access: read-only // Get the literal string of characters associated with the current // event. If the parser recognises and supports this property but is // not currently parsing text, it should return null (this is a good // way to check for availability before the parse begins). if (property.equals("xml-string")) { return getXMLString(); } // Not recognized } // SAX2 Handlers /* else if (propertyId.startsWith(SAX2_HANDLERS_PREFIX)) { // // No handlers defined yet that are common to all parsers. // } */ // Xerces Properties /* else if (propertyId.startsWith(XERCES_PROPERTIES_PREFIX)) { // // No properties defined yet that are common to all parsers. // } */ // Not recognized throw new SAXNotRecognizedException(propertyId); } // getProperty(String):Object // XMLDocumentScanner methods /** * Returns true if the specified version is valid. * */ public boolean validVersionNum(String version) { return XMLCharacterProperties.validVersionNum(version); } /** * Returns true if the specified encoding is valid. * */ public boolean validEncName(String encoding) { return XMLCharacterProperties.validEncName(encoding); } // callbacks /** * Call the start document callback. */ public void callStartDocument(int version, int encoding, int standalone) throws Exception { if (!fCalledStartDocument) { startDocument(version, encoding, standalone); fCalledStartDocument = true; } } /** * Call the end document callback. */ public void callEndDocument() throws Exception { if (fCalledStartDocument) endDocument(); } /** Call the start element callback. */ public void callStartElement(int elementType) throws Exception { // 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; if (fValidator == null) { fValidator = fDTDValidator; } fValidator.rootElementSpecified(elementType); fStringPool.resetShuffleCount(); } fInElementContent = fValidator.startElement(elementType, fAttrList); int attrListHandle = fAttrList.attrListHandle(); if (attrListHandle != -1) { fAttrList.endAttrList(); // REVISIT - we should check for this more efficiently... if (fXMLLang == -1) fXMLLang = fStringPool.addSymbol("xml:lang"); int index = fAttrList.getFirstAttr(attrListHandle); while (index != -1) { if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) { fScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index)); break; } index = fAttrList.getNextAttr(index); } } startElement(elementType, fAttrList, attrListHandle); int elementEntity = fEntityHandler.getReaderId(); if (fElementDepth == fElementTypeStack.length) { int[] newStack = new int[fElementDepth * 2]; System.arraycopy(fElementTypeStack, 0, newStack, 0, fElementDepth); fElementTypeStack = newStack; newStack = new int[fElementDepth * 2]; System.arraycopy(fElementEntityStack, 0, newStack, 0, fElementDepth); fElementEntityStack = newStack; } fCurrentElementType = elementType; fCurrentElementEntity = elementEntity; fElementTypeStack[fElementDepth] = elementType; fElementEntityStack[fElementDepth] = elementEntity; fElementDepth++; } // callStartElement(int) /** Call the end element callback. */ public boolean callEndElement(int readerId) throws Exception { int elementType = fCurrentElementType; 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); } endElement(elementType); fInElementContent = fValidator.endElement(elementType); if (fElementDepth throw new RuntimeException("FWK008 Element stack underflow"); } if (fElementDepth == 0) { fCurrentElementType = - 1; fCurrentElementEntity = -1; return true; } fCurrentElementType = fElementTypeStack[fElementDepth - 1]; fCurrentElementEntity = fElementEntityStack[fElementDepth - 1]; return false; } /** Call the processing instruction callback. */ public void callProcessingInstruction(int target, int data) throws Exception { processingInstruction(target, data); } /** Call the comment callback. */ public void callComment(int comment) throws Exception { comment(comment); } /** Call the characters callback. */ 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 (fSendCharDataAsCharArray) { if (!fInElementContent) fValidator.characters(fCharRefData, 0, count); characters(fCharRefData, 0, count); } else { int index = fStringPool.addString(new String(fCharRefData, 0, count)); if (!fInElementContent) fValidator.characters(index); characters(index); } } // scanning /** * Scan an attribute value. * * @param elementType * @param attrName * @return XMLDocumentScanner.RESULT_SUCCESS if the attribute was created, * XMLDocumentScanner.RESULT_NOT_WELL_FORMED if the scan failed, or * XMLDocumentScanner.RESULT_DUPLICATE_ATTR if the attribute is a duplicate. * @exception java.lang.Exception */ public int scanAttValue(int elementType, int attrName) throws Exception { fAttrNameLocator = getLocatorImpl(fAttrNameLocator); int attValue = fScanner.scanAttValue(elementType, attrName, fValidating/* && attType != fCDATASymbol*/); if (attValue == -1) { return XMLDocumentScanner.RESULT_FAILURE; } if (!fCheckedForSchema) { fCheckedForSchema = true; if (attrName == fStringPool.addSymbol("xmlns")) { // default namespacedecl fValidator = getSchemaValidator(); String fs = fEntityHandler.expandSystemId(fStringPool.toString(attValue)); InputSource is = fEntityResolver == null ? null : fEntityResolver.resolveEntity(null, fs); if (is == null) { is = new InputSource(fs); } fSchemaValidator.loadSchema(is); } } if (!fValidator.attributeSpecified(elementType, fAttrList, attrName, fAttrNameLocator, attValue)) { return XMLDocumentScanner.RESULT_DUPLICATE_ATTR; } return XMLDocumentScanner.RESULT_SUCCESS; } /** Scans an element type. */ public int scanElementType(XMLEntityHandler.EntityReader entityReader, char fastchar) throws Exception { if (!fNamespacesEnabled) { return entityReader.scanName(fastchar); } int elementType = entityReader.scanQName(fastchar); if (fNamespacesEnabled && 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(' '); } return elementType; } /** Scans an expected element type. */ public boolean scanExpectedElementType(XMLEntityHandler.EntityReader entityReader, char fastchar) throws Exception { if (fCurrentElementCharArrayRange == null) fCurrentElementCharArrayRange = fStringPool.createCharArrayRange(); fStringPool.getCharArrayRange(fCurrentElementType, fCurrentElementCharArrayRange); return entityReader.scanExpectedName(fastchar, fCurrentElementCharArrayRange); } /** Scans an attribute name. */ public int scanAttributeName(XMLEntityHandler.EntityReader entityReader, int elementType) throws Exception { if (!fSeenRootElement) { fSeenRootElement = true; if (fValidator == null) { fValidator = fDTDValidator; } fValidator.rootElementSpecified(elementType); fStringPool.resetShuffleCount(); } if (!fNamespacesEnabled) { return entityReader.scanName('='); } int attrName = entityReader.scanQName('='); 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(' '); } return attrName; } /** Scan doctype decl. */ public void scanDoctypeDecl(boolean standalone) throws Exception { fScanningDTD = true; fCheckedForSchema = true; fStandaloneDocument = standalone; fValidator = fDTDValidator; fDTDValidator.scanDoctypeDecl(standalone); fScanningDTD = false; } /** * Tell the parser that we are validating */ public void setValidating(boolean flag) throws Exception { fValidating = flag; } private LocatorImpl getLocatorImpl(LocatorImpl fillin) { if (fillin == null) return new LocatorImpl(this); fillin.setPublicId(getPublicId()); fillin.setSystemId(getSystemId()); fillin.setLineNumber(getLineNumber()); fillin.setColumnNumber(getColumnNumber()); return fillin; } // XMLEntityHandler methods /** * Character data. */ public void processCharacters(char[] chars, int offset, int length) throws Exception { if (fValidating && !fInElementContent) fValidator.characters(chars, offset, length); characters(chars, offset, length); } /** * Character data. */ public void processCharacters(int data) throws Exception { if (fValidating && !fInElementContent) fValidator.characters(data); characters(data); } /** * White space. */ public void processWhitespace(char[] chars, int offset, int length) throws Exception { if (fInElementContent) { if (fStandaloneDocument && fValidating) fValidator.ignorableWhitespace(chars, offset, length); ignorableWhitespace(chars, offset, length); } else { if (fValidating && !fInElementContent) fValidator.characters(chars, offset, length); characters(chars, offset, length); } } /** * White space. */ public void processWhitespace(int data) throws Exception { if (fInElementContent) { if (fStandaloneDocument && fValidating) fValidator.ignorableWhitespace(data); ignorableWhitespace(data); } else { if (fValidating && !fInElementContent) fValidator.characters(data); characters(data); } } // Data private class ReaderState { XMLEntityHandler.EntityReader reader; InputSource source; int entityName; int entityType; int entityContext; String publicId; String systemId; int readerId; int depth; ReaderState nextReaderState; } private ReaderState fReaderStateFreeList = null; private EntityResolver fEntityResolver = null; private byte[] fEntityTypeStack = null; private int[] fEntityNameStack = null; private int fEntityStackDepth = 0; private Stack fReaderStack = new Stack(); private XMLEntityHandler.EntityReader fReader = null; private InputSource fSource = null; private int fEntityName = -1; private int fEntityType = -1; private int fEntityContext = -1; private String fPublicId = null; private String fSystemId = null; private int fReaderId = -1; private int fReaderDepth = -1; private int fNextReaderId = 0; private NullReader fNullReader = null; /** * Resets the entity handler. */ private void resetEntityHandler() { fReaderStack.removeAllElements(); fEntityStackDepth = 0; fReader = null; fSource = null; fEntityName = -1; fEntityType = -1; fEntityContext = -1; fPublicId = null; fSystemId = null; fReaderId = -1; fReaderDepth = -1; fNextReaderId = 0; } /** * get the Entity reader. */ public XMLEntityHandler.EntityReader getEntityReader() { return fReader; } /** * Adds a recognizer. * * @param recognizer The XML recognizer to add. */ public void addRecognizer(XMLDeclRecognizer recognizer) { fReaderFactory.addRecognizer(recognizer); } /** * Expands a system id and returns the system id as a URL, if * it can be expanded. A return value of null means that the * identifier is already expanded. An exception thrown * indicates a failure to expand the id. * * @param systemId The systemId to be expanded. * * @return Returns the URL object representing the expanded system * identifier. A null value indicates that the given * system identifier is already expanded. * */ public String expandSystemId(String systemId) { return expandSystemId(systemId, fSystemId); } private String expandSystemId(String systemId, String currentSystemId) { String id = systemId; // check for bad parameters id if (id == null || id.length() == 0) { return systemId; } // if id already expanded, return try { URL url = new URL(id); if (url != null) { return systemId; } } catch (MalformedURLException e) { // continue on... } // normalize id id = fixURI(id); // normalize base URL base = null; URL url = null; try { if (currentSystemId == null) { String dir; try { dir = fixURI(System.getProperty("user.dir")); } catch (SecurityException se) { dir = ""; } if (!dir.endsWith("/")) { dir = dir + "/"; } base = new URL("file", "", dir); } else { base = new URL(currentSystemId); } // expand id url = new URL(base, id); } catch (Exception e) { // let it go through } if (url == null) { return systemId; } return url.toString(); } // Private methods /** * Fixes a platform dependent filename to standard URI form. * * @param str The string to fix. * * @return Returns the fixed URI string. */ private static String fixURI(String str) { // handle platform dependent strings str = str.replace(java.io.File.separatorChar, '/'); // Windows fix if (str.length() >= 2) { char ch1 = str.charAt(1); if (ch1 == ':') { char ch0 = Character.toUpperCase(str.charAt(0)); if (ch0 >= 'A' && ch0 <= 'Z') { str = "/" + str; } } } // done return str; } private void sendEndOfInputNotifications() throws Exception { boolean moreToFollow = fReaderStack.size() > 1; fScanner.endOfInput(fEntityName, moreToFollow); if (fScanningDTD) fDTDValidator.endOfInput(fEntityName, moreToFollow); } private void sendReaderChangeNotifications() throws Exception { fScanner.readerChange(fReader, fReaderId); if (fScanningDTD) fDTDValidator.readerChange(fReader, fReaderId); } private void sendStartEntityNotifications() throws Exception { startEntityReference(fEntityName, fEntityType, fEntityContext); } private void sendEndEntityNotifications() throws Exception { endEntityReference(fEntityName, fEntityType, fEntityContext); } /** * set up the reader stack to read from the document entity */ public boolean startReadingFromDocument(InputSource source) throws Exception { pushEntity(false, -2); // Document Entity fSystemId = null; pushNullReader(); fEntityName = -2; // Document Entity fEntityType = ENTITYTYPE_DOCUMENT; fEntityContext = CONTEXT_DOCUMENT; fReaderDepth = 0; fReaderId = fNextReaderId++; fPublicId = source.getPublicId(); fSystemId = source.getSystemId(); sendStartEntityNotifications(); fSystemId = expandSystemId(fSystemId, null); fSource = source; boolean xmlDecl = true; // xmlDecl if true, textDecl if false try { fReader = fReaderFactory.createReader(fEntityHandler, fErrorReporter, source, fSystemId, xmlDecl, fStringPool); } catch (MalformedURLException mu) { fReader = null; String errorSystemId = fSystemId; sendEndEntityNotifications(); popReader(); popEntity(); Object[] args = { errorSystemId }; fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.IO0, 0, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } catch (FileNotFoundException fnf) { fReader = null; String errorSystemId = fSystemId; sendEndEntityNotifications(); popReader(); popEntity(); Object[] args = { errorSystemId }; fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.IO0, 0, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } catch (java.io.UnsupportedEncodingException uee) { fReader = null; sendEndEntityNotifications(); popReader(); popEntity(); String encoding = uee.getMessage(); if (encoding == null) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ENCODING_REQUIRED, XMLMessages.P81_REQUIRED, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } else if (!XMLCharacterProperties.validEncName(encoding)) { Object[] args = { encoding }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ENCODINGDECL_INVALID, XMLMessages.P81_INVALID_VALUE, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } else { Object[] args = { encoding }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ENCODING_NOT_SUPPORTED, XMLMessages.P81_NOT_SUPPORTED, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } } sendReaderChangeNotifications(); return fReader != null; } /** * start reading from an external DTD subset */ public void startReadingFromExternalSubset(String publicId, String systemId, int readerDepth) throws Exception { pushEntity(true, -1); pushReader(); pushNullReader(); fEntityName = -1; // External Subset fEntityType = ENTITYTYPE_EXTERNAL_SUBSET; fEntityContext = CONTEXT_EXTERNAL_SUBSET; fReaderDepth = readerDepth; fReaderId = fNextReaderId++; fPublicId = publicId; fSystemId = systemId; startReadingFromExternalEntity(false); } /** * stop reading from an external DTD subset */ public void stopReadingFromExternalSubset() throws Exception { if (!(fReader instanceof NullReader)) throw new RuntimeException("FWK004 cannot happen 18"+"\n18"); popReader(); sendReaderChangeNotifications(); } /** * start reading from an external entity */ public boolean startReadingFromEntity(int entityName, int readerDepth, int context) throws Exception { if (context > XMLEntityHandler.CONTEXT_IN_CONTENT) return startReadingFromParameterEntity(entityName, readerDepth, context); int entityHandle = fValidator.lookupEntity(entityName); if (entityHandle < 0) { int minorCode = XMLMessages.VC_ENTITY_DECLARED; int errorType = XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR; // REVISIT - the following test in insufficient... if (fEntityContext == CONTEXT_DOCUMENT || fEntityContext == CONTEXT_IN_ATTVALUE) { minorCode = XMLMessages.WFC_ENTITY_DECLARED; errorType = XMLErrorReporter.ERRORTYPE_FATAL_ERROR; } Object[] args = { fStringPool.toString(entityName) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ENTITY_NOT_DECLARED, minorCode, args, errorType); return false; } if (context == CONTEXT_IN_CONTENT) { if (fValidator.isUnparsedEntity(entityHandle)) { Object[] args = { fStringPool.toString(entityName) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_REFERENCE_TO_UNPARSED_ENTITY, XMLMessages.WFC_PARSED_ENTITY, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); return false; } } else { if (fValidator.isExternalEntity(entityHandle)) { Object[] args = { fStringPool.toString(entityName) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_REFERENCE_TO_EXTERNAL_ENTITY, XMLMessages.WFC_NO_EXTERNAL_ENTITY_REFERENCES, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); return false; } } if (!pushEntity(false, entityName)) { Object[] args = { fStringPool.toString(entityName), entityReferencePath(false, entityName) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_RECURSIVE_REFERENCE, XMLMessages.WFC_NO_RECURSION, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); return false; } pushReader(); fEntityName = entityName; fEntityContext = context; fReaderDepth = readerDepth; fReaderId = fNextReaderId++; if (context != CONTEXT_IN_CONTENT || !fValidator.externalReferenceInContent(entityHandle)) { fEntityType = ENTITYTYPE_INTERNAL; fPublicId = null/*"Internal Entity: " + fStringPool.toString(entityName)*/; fSystemId = fSystemId; // keep expandSystemId happy int value = -1; if (context == CONTEXT_IN_CONTENT || context == CONTEXT_IN_DEFAULTATTVALUE) value = fValidator.getEntityValue(entityHandle); else value = fValidator.valueOfReferenceInAttValue(entityHandle); startReadingFromInternalEntity(value, false); return false; } fEntityType = ENTITYTYPE_EXTERNAL; fPublicId = fValidator.getPublicIdOfEntity(entityHandle); fSystemId = fValidator.getSystemIdOfEntity(entityHandle); return startReadingFromExternalEntity(true); } private boolean startReadingFromParameterEntity(int peName, int readerDepth, int context) throws Exception { int entityHandle = fValidator.lookupParameterEntity(peName); if (entityHandle == -1) { // The error is generated by the validator (strange... it is a VC, not a WFC...) return false; } if (!pushEntity(true, peName)) { Object[] args = { fStringPool.toString(peName), entityReferencePath(true, peName) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_RECURSIVE_PEREFERENCE, XMLMessages.WFC_NO_RECURSION, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); return false; } pushReader(); fEntityName = peName; fEntityContext = context; fReaderDepth = readerDepth; fReaderId = fNextReaderId++; if (!fValidator.isExternalParameterEntity(entityHandle)) { fEntityType = ENTITYTYPE_INTERNAL_PE; fPublicId = null/*"Internal Entity: %" + fStringPool.toString(peName)*/; fSystemId = fSystemId; // keep expandSystemId happy int value = fValidator.getParameterEntityValue(entityHandle); startReadingFromInternalEntity(value, fEntityContext == CONTEXT_IN_ENTITYVALUE ? false : true); return false; } fEntityType = ENTITYTYPE_EXTERNAL_PE; fPublicId = fValidator.getPublicIdOfParameterEntity(entityHandle); fSystemId = fValidator.getSystemIdOfParameterEntity(entityHandle); return startReadingFromExternalEntity(true); } private void startReadingFromInternalEntity(int value, boolean addSpaces) throws Exception { if (fEntityContext == CONTEXT_IN_ENTITYVALUE) { // REVISIT - consider optimizing the case where the entire entity value // consists of a single reference to a parameter entity and do not append // the value to fLiteralData again, but re-use the offset/length of the // referenced entity for the value of this entity. } fSource = null; sendStartEntityNotifications(); fReader = fReaderFactory.createStringReader(this, fErrorReporter, fSendCharDataAsCharArray, getLineNumber(), getColumnNumber(), value, fStringPool, addSpaces); // REVISIT - string reader needs better location support sendReaderChangeNotifications(); } private boolean startReadingFromExternalEntity(boolean checkForTextDecl) throws Exception { if (fEntityContext == CONTEXT_IN_ENTITYVALUE) { // REVISIT - Can we get the spec changed ? // There is a perverse edge case to handle here... We have a reference // to an external PE within a literal EntityValue. For the PE to be // well-formed, it must match the extPE production, but the code that // appends the replacement text to the entity value is in no position // to do a complete well-formedness check !! } if (fEntityContext == CONTEXT_IN_DTD_WITHIN_MARKUP) { // REVISIT - Can we get the spec changed ? // There is a perverse edge case to handle here... We have a reference // to an external PE within markup. For the PE to be well-formed, it // must match the extPE production, which is probably not going to be // very useful expanded in the middle of a markup declaration. The // problem is that an empty file, a file containing just whitespace or // another PE that is just empty or whitespace, matches extPE !! } sendStartEntityNotifications(); ReaderState rs = (ReaderState) fReaderStack.peek(); fSystemId = expandSystemId(fSystemId, rs.systemId); fSource = fEntityResolver == null ? null : fEntityResolver.resolveEntity(fPublicId, fSystemId); if (fSource == null) { fSource = new InputSource(fSystemId); if (fPublicId != null) fSource.setPublicId(fPublicId); } boolean textDecl = false; // xmlDecl if true, textDecl if false try { fReader = fReaderFactory.createReader(fEntityHandler, fErrorReporter, fSource, fSystemId, textDecl, fStringPool); } catch (MalformedURLException mu) { fReader = null; String errorSystemId = fSystemId; sendEndEntityNotifications(); popReader(); popEntity(); Object[] args = { errorSystemId }; fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.IO0, 0, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } catch (FileNotFoundException fnf) { fReader = null; String errorSystemId = fSystemId; sendEndEntityNotifications(); popReader(); popEntity(); Object[] args = { errorSystemId }; fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.IO0, 0, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } catch (java.io.UnsupportedEncodingException uee) { fReader = null; sendEndEntityNotifications(); popReader(); popEntity(); String encoding = uee.getMessage(); if (encoding == null) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ENCODING_REQUIRED, XMLMessages.P81_REQUIRED, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } else if (!XMLCharacterProperties.validEncName(encoding)) { Object[] args = { encoding }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ENCODINGDECL_INVALID, XMLMessages.P81_INVALID_VALUE, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } else { Object[] args = { encoding }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ENCODING_NOT_SUPPORTED, XMLMessages.P81_NOT_SUPPORTED, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } } if (fReader == null || !checkForTextDecl) { sendReaderChangeNotifications(); return false; } int readerId = fReaderId; sendReaderChangeNotifications(); boolean parseTextDecl = fReader.lookingAtChar('<', false); if (readerId != fReaderId) parseTextDecl = false; return parseTextDecl; } // reader stack private void pushNullReader() { ReaderState rs = fReaderStateFreeList; if (rs == null) rs = new ReaderState(); else fReaderStateFreeList = rs.nextReaderState; if (fNullReader == null) fNullReader = new NullReader(); rs.reader = fNullReader; rs.source = null; rs.entityName = -1; // Null Entity rs.entityType = -1; // Null Entity rs.entityContext = -1; // Null Entity rs.publicId = "Null Entity"; rs.systemId = fSystemId; rs.readerId = fNextReaderId++; rs.depth = -1; rs.nextReaderState = null; fReaderStack.push(rs); } private void pushReader() { ReaderState rs = fReaderStateFreeList; if (rs == null) rs = new ReaderState(); else fReaderStateFreeList = rs.nextReaderState; rs.reader = fReader; rs.source = fSource; rs.entityName = fEntityName; rs.entityType = fEntityType; rs.entityContext = fEntityContext; rs.publicId = fPublicId; rs.systemId = fSystemId; rs.readerId = fReaderId; rs.depth = fReaderDepth; rs.nextReaderState = null; fReaderStack.push(rs); } private void popReader() { if (fReaderStack.empty()) throw new RuntimeException("FWK004 cannot happen 19"+"\n19"); ReaderState rs = (ReaderState) fReaderStack.pop(); fReader = rs.reader; fSource = rs.source; fEntityName = rs.entityName; fEntityType = rs.entityType; fEntityContext = rs.entityContext; fPublicId = rs.publicId; fSystemId = rs.systemId; fReaderId = rs.readerId; fReaderDepth = rs.depth; rs.nextReaderState = fReaderStateFreeList; fReaderStateFreeList = rs; } // entity stack /** * start an entity declaration */ public boolean startEntityDecl(boolean isPE, int entityName) throws Exception { if (!pushEntity(isPE, entityName)) { int majorCode = isPE ? XMLMessages.MSG_RECURSIVE_PEREFERENCE : XMLMessages.MSG_RECURSIVE_REFERENCE; Object[] args = { fStringPool.toString(entityName), entityReferencePath(isPE, entityName) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, XMLMessages.WFC_NO_RECURSION, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); return false; } return true; } /** * end an entity declaration */ public void endEntityDecl() throws Exception { popEntity(); } private boolean pushEntity(boolean isPE, int entityName) throws Exception { if (entityName >= 0) { for (int i = 0; i < fEntityStackDepth; i++) { if (fEntityNameStack[i] == entityName && fEntityTypeStack[i] == (isPE ? 1 : 0)) { return false; } } } if (fEntityTypeStack == null) { fEntityTypeStack = new byte[8]; fEntityNameStack = new int[8]; } else if (fEntityStackDepth == fEntityTypeStack.length) { byte[] newTypeStack = new byte[fEntityStackDepth * 2]; System.arraycopy(fEntityTypeStack, 0, newTypeStack, 0, fEntityStackDepth); fEntityTypeStack = newTypeStack; int[] newNameStack = new int[fEntityStackDepth * 2]; System.arraycopy(fEntityNameStack, 0, newNameStack, 0, fEntityStackDepth); fEntityNameStack = newNameStack; } fEntityTypeStack[fEntityStackDepth] = (byte)(isPE ? 1 : 0); fEntityNameStack[fEntityStackDepth] = entityName; fEntityStackDepth++; return true; } private String entityReferencePath(boolean isPE, int entityName) { StringBuffer sb = new StringBuffer(); sb.append("(top-level)"); for (int i = 0; i < fEntityStackDepth; i++) { if (fEntityNameStack[i] >= 0) { sb.append('-'); sb.append(fEntityTypeStack[i] == 1 ? '%' : '&'); sb.append(fStringPool.toString(fEntityNameStack[i])); sb.append(';'); } } sb.append('-'); sb.append(isPE ? '%' : '&'); sb.append(fStringPool.toString(entityName)); sb.append(';'); return sb.toString(); } private void popEntity() throws Exception { fEntityStackDepth } /** * This method is provided for scanner implementations. */ public int getReaderId() { return fReaderId; } /** * This method is provided for scanner implementations. */ public void setReaderDepth(int depth) { fReaderDepth = depth; } /** * This method is provided for scanner implementations. */ public int getReaderDepth() { return fReaderDepth; } /** * Return the public identifier of the <code>InputSource</code> that we are processing. * * @return The public identifier, or null if not provided. */ public String getPublicId() { return fPublicId; } /** * Return the system identifier of the <code>InputSource</code> that we are processing. * * @return The system identifier, or null if not provided. */ public String getSystemId() { return fSystemId; } /** * Return the line number of the current position within the document that we are processing. * * @return The current line number. */ public int getLineNumber() { return fReader.getLineNumber(); } /** * Return the column number of the current position within the document that we are processing. * * @return The current column number. */ public int getColumnNumber() { return fReader.getColumnNumber(); } /** * This method is called by the reader subclasses at the * end of input, and also by the scanner directly to force * a reader change during error recovery. */ public XMLEntityHandler.EntityReader changeReaders() throws Exception { sendEndOfInputNotifications(); sendEndEntityNotifications(); popReader(); sendReaderChangeNotifications(); popEntity(); return fReader; } // We use the null reader after we have reached the // end of input for the document or external subset. private final class NullReader implements XMLEntityHandler.EntityReader { public NullReader() { } public int currentOffset() { return -1; } public int getLineNumber() { return -1; } public int getColumnNumber() { return -1; } public void setInCDSect(boolean inCDSect) { } public boolean getInCDSect() { return false; } public void append(XMLEntityHandler.CharBuffer charBuffer, int offset, int length) { } public int addString(int offset, int length) { return -1; } public int addSymbol(int offset, int length) { return -1; } public boolean lookingAtChar(char ch, boolean skipPastChar) { return false; } public boolean lookingAtValidChar(boolean skipPastChar) { return false; } public boolean lookingAtSpace(boolean skipPastChar) { return false; } public void skipToChar(char ch) { } public void skipPastSpaces() { } public void skipPastName(char fastcheck) { } public void skipPastNmtoken(char fastcheck) { } public boolean skippedString(char[] s) { return false; } public int scanInvalidChar() { return -1; } public int scanCharRef(boolean hex) { return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; } public int scanStringLiteral() { return XMLEntityHandler.STRINGLIT_RESULT_QUOTE_REQUIRED; } public int scanAttValue(char qchar, boolean asSymbol) { return XMLEntityHandler.ATTVALUE_RESULT_INVALID_CHAR; } public int scanEntityValue(int qchar, boolean createString) { return XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR; } public boolean scanExpectedName(char fastcheck, StringPool.CharArrayRange expectedName) { return false; } public int scanQName(char fastcheck) { return -1; } public int scanName(char fastcheck) { return -1; } public int scanContent(int elementType) throws Exception { return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } } // class XMLParser
package org.apache.xerces.impl.v2.xpath; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLChar; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; /** * Bare minimum XPath parser. * * @author Andy Clark, IBM * @version $Id$ */ public class XPath { // Constants private static final boolean DEBUG_ALL = false; private static final boolean DEBUG_XPATH_PARSE = DEBUG_ALL || false; private static final boolean DEBUG_ANY = DEBUG_XPATH_PARSE; // Data /** Expression. */ protected String fExpression; /** Symbol table. */ protected SymbolTable fSymbolTable; /** Location paths. */ protected LocationPath[] fLocationPaths; // Constructors /** Constructs an XPath object from the specified expression. */ public XPath(String xpath, SymbolTable symbolTable, NamespaceContext context) throws XPathException { fExpression = xpath; fSymbolTable = symbolTable; parseExpression(context); } // <init>(String,SymbolTable,NamespaceContext) // Public methods /** * Returns a representation of all location paths for this XPath. * XPath = locationPath ( '|' locationPath) */ public LocationPath[] getLocationPaths() { LocationPath[] ret=new LocationPath[fLocationPaths.length]; for (int i=0;i<fLocationPaths.length;i++){ ret[i]=(LocationPath)fLocationPaths[i].clone(); } return ret; } // getLocationPath(LocationPath) /** Returns a representation of the first location path for this XPath. */ public LocationPath getLocationPath() { return (LocationPath)fLocationPaths[0].clone(); } // getLocationPath(LocationPath) // Object methods /** Returns a string representation of this object. */ public String toString() { StringBuffer buf=new StringBuffer(); for (int i=0;i<fLocationPaths.length;i++){ if (i>0){ buf.append("|"); } buf.append(fLocationPaths[i].toString()); } return buf.toString(); } // toString():String // Private methods /** * This method is implemented by using the XPathExprScanner and * examining the list of tokens that it returns. */ private void parseExpression(final NamespaceContext context) throws XPathException { // tokens final XPath.Tokens xtokens = new XPath.Tokens(fSymbolTable); // scanner XPath.Scanner scanner = new XPath.Scanner(fSymbolTable) { protected void addToken(XPath.Tokens tokens, int token) throws XPathException { if ( token == XPath.Tokens.EXPRTOKEN_ATSIGN || token == XPath.Tokens.EXPRTOKEN_AXISNAME_ATTRIBUTE || token == XPath.Tokens.EXPRTOKEN_AXISNAME_CHILD || //token == XPath.Tokens.EXPRTOKEN_AXISNAME_SELF || token == XPath.Tokens.EXPRTOKEN_DOUBLE_COLON || //token == XPath.Tokens.EXPRTOKEN_NAMETEST_ANY || token == XPath.Tokens.EXPRTOKEN_NAMETEST_QNAME || //token == XPath.Tokens.EXPRTOKEN_NODETYPE_NODE || token == XPath.Tokens.EXPRTOKEN_OPERATOR_SLASH || token == XPath.Tokens.EXPRTOKEN_PERIOD || //added to conform to PR Spec token == XPath.Tokens.EXPRTOKEN_NAMETEST_ANY || token == XPath.Tokens.EXPRTOKEN_NAMETEST_NAMESPACE || token == XPath.Tokens.EXPRTOKEN_OPERATOR_DOUBLE_SLASH || token == XPath.Tokens.EXPRTOKEN_OPERATOR_UNION ) { super.addToken(tokens, token); return; } StringBuffer str = new StringBuffer(); str.append("token not supported: "); String tokenName = tokens.getTokenName(token); if (tokenName != null) { str.append('"'); str.append(tokenName); str.append('"'); } else { str.append('('); str.append(token); str.append(')'); } String message = str.toString(); throw new XPathException(message); } }; int length = fExpression.length(); boolean success = scanner.scanExpr(fSymbolTable, xtokens, fExpression, 0, length); //fTokens.dumpTokens(); java.util.Vector stepsVector = new java.util.Vector(); java.util.Vector locationPathsVector= new java.util.Vector(); int tokenCount = xtokens.getTokenCount(); boolean firstTokenOfLocationPath=true; final String emptySymbol = fSymbolTable.addSymbol(""); for (int i = 0; i < tokenCount; i++) { int token = xtokens.getToken(i); boolean isNamespace=false; switch (token) { case XPath.Tokens.EXPRTOKEN_OPERATOR_UNION :{ if (i == 0) { throw new XPathException("not allowed to have '|' at the beginning of an xpath value"); } int size = stepsVector.size(); if (size == 0) { throw new XPathException("not allowed to have '||'"); } Step[] steps = new Step[size]; stepsVector.copyInto(steps); // add location path locationPathsVector.addElement(new LocationPath(steps)); //reset stepsVector stepsVector.removeAllElements(); firstTokenOfLocationPath=true; break; } case XPath.Tokens.EXPRTOKEN_AXISNAME_ATTRIBUTE: { // consume "::" token and drop through i++; } case XPath.Tokens.EXPRTOKEN_ATSIGN: { // consume QName token if (i == tokenCount - 1) { throw new XPathException("missing attribute name"); } token = xtokens.getToken(++i); if (token != XPath.Tokens.EXPRTOKEN_NAMETEST_QNAME && token!= XPath.Tokens.EXPRTOKEN_NAMETEST_ANY && token!= XPath.Tokens.EXPRTOKEN_NAMETEST_NAMESPACE) { throw new XPathException("expected \""+xtokens.getTokenName(XPath.Tokens.EXPRTOKEN_NAMETEST_QNAME)+ "\" or \""+xtokens.getTokenName( XPath.Tokens.EXPRTOKEN_NAMETEST_ANY)+ "\" or \""+xtokens.getTokenName( XPath.Tokens.EXPRTOKEN_NAMETEST_NAMESPACE)+ "\", found "+xtokens.getTokenName(token)); } boolean isNamespaceAtt=false; switch (token) { case XPath.Tokens.EXPRTOKEN_NAMETEST_ANY:{ Axis axis = new Axis(Axis.ATTRIBUTE); NodeTest nodeTest = new NodeTest(NodeTest.WILDCARD); Step step = new Step(axis, nodeTest); stepsVector.addElement(step); break; } case XPath.Tokens.EXPRTOKEN_NAMETEST_NAMESPACE:{ isNamespaceAtt=true; } case XPath.Tokens.EXPRTOKEN_NAMETEST_QNAME:{ token = xtokens.getToken(++i); String prefix = xtokens.getTokenString(token); String uri = null; if (context != null && prefix != emptySymbol) { uri = context.getURI(prefix); } if (prefix != emptySymbol && context != null && uri == null) { throw new XPathException("prefix "+prefix+" not bound to namespace URI"); } if (isNamespaceAtt) { // build step Axis axis = new Axis(Axis.ATTRIBUTE); NodeTest nodeTest = new NodeTest(prefix, uri); Step step = new Step(axis, nodeTest); stepsVector.addElement(step); break; } token = xtokens.getToken(++i); String localpart = xtokens.getTokenString(token); String rawname = prefix != emptySymbol ? fSymbolTable.addSymbol(prefix+':'+localpart) : localpart; // build step Axis axis = new Axis(Axis.ATTRIBUTE); NodeTest nodeTest = new NodeTest(new QName(prefix, localpart, rawname, uri)); Step step = new Step(axis, nodeTest); stepsVector.addElement(step); break; } } firstTokenOfLocationPath=false; break; } /** * A location path representation for an XPath expression. * * @author Andy Clark, IBM */ public static class LocationPath implements Cloneable { // Data /** List of steps. */ public Step[] steps; // Constructors /** Creates a location path from a series of steps. */ public LocationPath(Step[] steps) { this.steps = steps; } // <init>(Step[]) /** Copy constructor. */ protected LocationPath(LocationPath path) { steps = new Step[path.steps.length]; for (int i = 0; i < steps.length; i++) { steps[i] = (Step)path.steps[i].clone(); } } // <init>(LocationPath) // Object methods /** Returns a string representation of this object. */ public String toString() { StringBuffer str = new StringBuffer(); for (int i = 0; i < steps.length; i++) { if (i > 0 && (steps[i-1].axis.type!=Axis.DESCENDANT && steps[i].axis.type!=Axis.DESCENDANT) ){ str.append('/'); } str.append(steps[i].toString()); } // DEBUG: This code is just for debugging and should *not* // be left in because it will mess up hashcodes of // serialized versions of this object. -Ac if (false) { str.append('['); String s = super.toString(); str.append(s.substring(s.indexOf('@'))); str.append(']'); } return str.toString(); } // toString():String /** Returns a clone of this object. */ public Object clone() { return new LocationPath(this); } // clone():Object } // class locationPath /** * A location path step comprised of an axis and node test. * * @author Andy Clark, IBM */ public static class Step implements Cloneable { // Data /** Axis. */ public Axis axis; /** Node test. */ public NodeTest nodeTest; // Constructors /** Constructs a step from an axis and node test. */ public Step(Axis axis, NodeTest nodeTest) { this.axis = axis; this.nodeTest = nodeTest; } // <init>(Axis,NodeTest) /** Copy constructor. */ protected Step(Step step) { axis = (Axis)step.axis.clone(); nodeTest = (NodeTest)step.nodeTest.clone(); } // <init>(Step) // Object methods /** Returns a string representation of this object. */ public String toString() { /** Returns a clone of this object. */ /** * Axis. * * @author Andy Clark, IBM */ public static class Axis implements Cloneable { // Constants /** Type: child. */ public static final short CHILD = 1; /** Type: attribute. */ public static final short ATTRIBUTE = 2; /** Type: self. */ public static final short SELF = 3; /** Type: descendant. */ public static final short DESCENDANT = 4; // Data /** Axis type. */ public short type; // Constructors /** Constructs an axis with the specified type. */ public Axis(short type) { this.type = type; } // <init>(short) /** Copy constructor. */ protected Axis(Axis axis) { type = axis.type; } // <init>(Axis) // Object methods /** Returns a string representation of this object. */ public String toString() { switch (type) { case CHILD: return "child"; case ATTRIBUTE: return "attribute"; case SELF: return "self"; case DESCENDANT: return "descendant"; } return "???"; } // toString():String /** Returns a clone of this object. */ public Object clone() { return new Axis(this); } // clone():Object } // class Axis /** * Node test. * * @author Andy Clark, IBM */ public static class NodeTest implements Cloneable { // Constants /** Type: qualified name. */ public static final short QNAME = 1; /** Type: wildcard. */ public static final short WILDCARD = 2; /** Type: node. */ public static final short NODE = 3; /** Type: namespace */ public static final short NAMESPACE= 4; // Data /** Node test type. */ public short type; /** Node qualified name. */ public final QName name = new QName(); // Constructors /** Constructs a node test of type WILDCARD or NODE. */ public NodeTest(short type) { this.type = type; } // <init>(int) /** Constructs a node test of type QName. */ public NodeTest(QName name) { this.type = QNAME; this.name.setValues(name); } // <init>(QName) /** Constructs a node test of type Namespace. */ public NodeTest(String prefix, String uri) { this.type = NAMESPACE; this.name.setValues(prefix, null, null, uri); } // <init>(String,String) /** Copy constructor. */ public NodeTest(NodeTest nodeTest) { type = nodeTest.type; name.setValues(nodeTest.name); } // <init>(NodeTest) // Object methods /** Returns a string representation of this object. */ public String toString() { switch (type) { case QNAME: { if (name.prefix.length() !=0) { if (name.uri != null) { return name.prefix+':'+name.localpart; } return "{"+name.uri+'}'+name.prefix+':'+name.localpart; } return name.localpart; } case NAMESPACE: { if (name.prefix.length() !=0) { if (name.uri != null) { return name.prefix+":*"; } return "{"+name.uri+'}'+name.prefix+":*"; } return "???:*"; } case WILDCARD: { return "*"; } case NODE: { return "node()"; } } return "???"; } // toString():String /** Returns a clone of this object. */ public Object clone() { return new NodeTest(this); } // clone():Object } // class NodeTest // xpath implementation // NOTE: The XPath implementation classes are kept internal because // this implementation is just a temporary hack until a better // and/or more appropriate implementation can be written. // keeping the code in separate source files would "muddy" the // CVS directory when it's not needed. -Ac /** * @author Glenn Marcy, IBM * @author Andy Clark, IBM * * @version $Id$ */ private static final class Tokens { static final boolean DUMP_TOKENS = false; /** * [28] ExprToken ::= '(' | ')' | '[' | ']' | '.' | '..' | '@' | ',' | '::' * | NameTest | NodeType | Operator | FunctionName * | AxisName | Literal | Number | VariableReference */ public static final int EXPRTOKEN_OPEN_PAREN = 0, EXPRTOKEN_CLOSE_PAREN = 1, EXPRTOKEN_OPEN_BRACKET = 2, EXPRTOKEN_CLOSE_BRACKET = 3, EXPRTOKEN_PERIOD = 4, EXPRTOKEN_DOUBLE_PERIOD = 5, EXPRTOKEN_ATSIGN = 6, EXPRTOKEN_COMMA = 7, EXPRTOKEN_DOUBLE_COLON = 8, // [37] NameTest ::= '*' | NCName ':' '*' | QName // followed by symbol handle of NCName or QName EXPRTOKEN_NAMETEST_ANY = 9, EXPRTOKEN_NAMETEST_NAMESPACE = 10, EXPRTOKEN_NAMETEST_QNAME = 11, // [38] NodeType ::= 'comment' | 'text' | 'processing-instruction' | 'node' EXPRTOKEN_NODETYPE_COMMENT = 12, EXPRTOKEN_NODETYPE_TEXT = 13, EXPRTOKEN_NODETYPE_PI = 14, EXPRTOKEN_NODETYPE_NODE = 15, // [32] Operator ::= OperatorName // | MultiplyOperator // [33] OperatorName ::= 'and' | 'or' | 'mod' | 'div' // [34] MultiplyOperator ::= '*' EXPRTOKEN_OPERATOR_AND = 16, EXPRTOKEN_OPERATOR_OR = 17, EXPRTOKEN_OPERATOR_MOD = 18, EXPRTOKEN_OPERATOR_DIV = 19, EXPRTOKEN_OPERATOR_MULT = 20, EXPRTOKEN_OPERATOR_SLASH = 21, EXPRTOKEN_OPERATOR_DOUBLE_SLASH = 22, EXPRTOKEN_OPERATOR_UNION = 23, EXPRTOKEN_OPERATOR_PLUS = 24, EXPRTOKEN_OPERATOR_MINUS = 25, EXPRTOKEN_OPERATOR_EQUAL = 26, EXPRTOKEN_OPERATOR_NOT_EQUAL = 27, EXPRTOKEN_OPERATOR_LESS = 28, EXPRTOKEN_OPERATOR_LESS_EQUAL = 29, EXPRTOKEN_OPERATOR_GREATER = 30, EXPRTOKEN_OPERATOR_GREATER_EQUAL = 31, //EXPRTOKEN_FIRST_OPERATOR = EXPRTOKEN_OPERATOR_AND, //EXPRTOKEN_LAST_OPERATOR = EXPRTOKEN_OPERATOR_GREATER_EQUAL, // [35] FunctionName ::= QName - NodeType // followed by symbol handle EXPRTOKEN_FUNCTION_NAME = 32, // [6] AxisName ::= 'ancestor' | 'ancestor-or-self' // | 'attribute' // | 'child' // | 'descendant' | 'descendant-or-self' // | 'following' | 'following-sibling' // | 'namespace' // | 'parent' // | 'preceding' | 'preceding-sibling' // | 'self' EXPRTOKEN_AXISNAME_ANCESTOR = 33, EXPRTOKEN_AXISNAME_ANCESTOR_OR_SELF = 34, EXPRTOKEN_AXISNAME_ATTRIBUTE = 35, EXPRTOKEN_AXISNAME_CHILD = 36, EXPRTOKEN_AXISNAME_DESCENDANT = 37, EXPRTOKEN_AXISNAME_DESCENDANT_OR_SELF = 38, EXPRTOKEN_AXISNAME_FOLLOWING = 39, EXPRTOKEN_AXISNAME_FOLLOWING_SIBLING = 40, EXPRTOKEN_AXISNAME_NAMESPACE = 41, EXPRTOKEN_AXISNAME_PARENT = 42, EXPRTOKEN_AXISNAME_PRECEDING = 43, EXPRTOKEN_AXISNAME_PRECEDING_SIBLING = 44, EXPRTOKEN_AXISNAME_SELF = 45, // [29] Literal ::= '"' [^"]* '"' | "'" [^']* "'" // followed by symbol handle for literal EXPRTOKEN_LITERAL = 46, // [30] Number ::= Digits ('.' Digits?)? | '.' Digits // [31] Digits ::= [0-9]+ // followed by number handle EXPRTOKEN_NUMBER = 47, // [36] VariableReference ::= '$' QName // followed by symbol handle for QName EXPRTOKEN_VARIABLE_REFERENCE = 48; public static final String[] fgTokenNames = { "EXPRTOKEN_OPEN_PAREN", "EXPRTOKEN_CLOSE_PAREN", "EXPRTOKEN_OPEN_BRACKET", "EXPRTOKEN_CLOSE_BRACKET", "EXPRTOKEN_PERIOD", "EXPRTOKEN_DOUBLE_PERIOD", "EXPRTOKEN_ATSIGN", "EXPRTOKEN_COMMA", "EXPRTOKEN_DOUBLE_COLON", "EXPRTOKEN_NAMETEST_ANY", "EXPRTOKEN_NAMETEST_NAMESPACE", "EXPRTOKEN_NAMETEST_QNAME", "EXPRTOKEN_NODETYPE_COMMENT", "EXPRTOKEN_NODETYPE_TEXT", "EXPRTOKEN_NODETYPE_PI", "EXPRTOKEN_NODETYPE_NODE", "EXPRTOKEN_OPERATOR_AND", "EXPRTOKEN_OPERATOR_OR", "EXPRTOKEN_OPERATOR_MOD", "EXPRTOKEN_OPERATOR_DIV", "EXPRTOKEN_OPERATOR_MULT", "EXPRTOKEN_OPERATOR_SLASH", "EXPRTOKEN_OPERATOR_DOUBLE_SLASH", "EXPRTOKEN_OPERATOR_UNION", "EXPRTOKEN_OPERATOR_PLUS", "EXPRTOKEN_OPERATOR_MINUS", "EXPRTOKEN_OPERATOR_EQUAL", "EXPRTOKEN_OPERATOR_NOT_EQUAL", "EXPRTOKEN_OPERATOR_LESS", "EXPRTOKEN_OPERATOR_LESS_EQUAL", "EXPRTOKEN_OPERATOR_GREATER", "EXPRTOKEN_OPERATOR_GREATER_EQUAL", "EXPRTOKEN_FUNCTION_NAME", "EXPRTOKEN_AXISNAME_ANCESTOR", "EXPRTOKEN_AXISNAME_ANCESTOR_OR_SELF", "EXPRTOKEN_AXISNAME_ATTRIBUTE", "EXPRTOKEN_AXISNAME_CHILD", "EXPRTOKEN_AXISNAME_DESCENDANT", "EXPRTOKEN_AXISNAME_DESCENDANT_OR_SELF", "EXPRTOKEN_AXISNAME_FOLLOWING", "EXPRTOKEN_AXISNAME_FOLLOWING_SIBLING", "EXPRTOKEN_AXISNAME_NAMESPACE", "EXPRTOKEN_AXISNAME_PARENT", "EXPRTOKEN_AXISNAME_PRECEDING", "EXPRTOKEN_AXISNAME_PRECEDING_SIBLING", "EXPRTOKEN_AXISNAME_SELF", "EXPRTOKEN_LITERAL", "EXPRTOKEN_NUMBER", "EXPRTOKEN_VARIABLE_REFERENCE" }; private static final int INITIAL_TOKEN_COUNT = 1 << 8; private int[] fTokens = new int[INITIAL_TOKEN_COUNT]; private int fTokenCount = 0; // for writing private SymbolTable fSymbolTable; // REVISIT: Code something better here. -Ac private java.util.Hashtable fSymbolMapping = new java.util.Hashtable(); // REVISIT: Code something better here. -Ac private java.util.Hashtable fTokenNames = new java.util.Hashtable(); // Constructors public Tokens(SymbolTable symbolTable) { fSymbolTable = symbolTable; final String[] symbols = { "ancestor", "ancestor-or-self", "attribute", "child", "descendant", "descendant-or-self", "following", "following-sibling", "namespace", "parent", "preceding", "preceding-sibling", "self", }; for (int i = 0; i < symbols.length; i++) { fSymbolMapping.put(fSymbolTable.addSymbol(symbols[i]), new Integer(i)); } fTokenNames.put(new Integer(EXPRTOKEN_OPEN_PAREN), "EXPRTOKEN_OPEN_PAREN"); fTokenNames.put(new Integer(EXPRTOKEN_CLOSE_PAREN), "EXPRTOKEN_CLOSE_PAREN"); fTokenNames.put(new Integer(EXPRTOKEN_OPEN_BRACKET), "EXPRTOKEN_OPEN_BRACKET"); fTokenNames.put(new Integer(EXPRTOKEN_CLOSE_BRACKET), "EXPRTOKEN_CLOSE_BRACKET"); fTokenNames.put(new Integer(EXPRTOKEN_PERIOD), "EXPRTOKEN_PERIOD"); fTokenNames.put(new Integer(EXPRTOKEN_DOUBLE_PERIOD), "EXPRTOKEN_DOUBLE_PERIOD"); fTokenNames.put(new Integer(EXPRTOKEN_ATSIGN), "EXPRTOKEN_ATSIGN"); fTokenNames.put(new Integer(EXPRTOKEN_COMMA), "EXPRTOKEN_COMMA"); fTokenNames.put(new Integer(EXPRTOKEN_DOUBLE_COLON), "EXPRTOKEN_DOUBLE_COLON"); fTokenNames.put(new Integer(EXPRTOKEN_NAMETEST_ANY), "EXPRTOKEN_NAMETEST_ANY"); fTokenNames.put(new Integer(EXPRTOKEN_NAMETEST_NAMESPACE), "EXPRTOKEN_NAMETEST_NAMESPACE"); fTokenNames.put(new Integer(EXPRTOKEN_NAMETEST_QNAME), "EXPRTOKEN_NAMETEST_QNAME"); fTokenNames.put(new Integer(EXPRTOKEN_NODETYPE_COMMENT), "EXPRTOKEN_NODETYPE_COMMENT"); fTokenNames.put(new Integer(EXPRTOKEN_NODETYPE_TEXT), "EXPRTOKEN_NODETYPE_TEXT"); fTokenNames.put(new Integer(EXPRTOKEN_NODETYPE_PI), "EXPRTOKEN_NODETYPE_PI"); fTokenNames.put(new Integer(EXPRTOKEN_NODETYPE_NODE), "EXPRTOKEN_NODETYPE_NODE"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_AND), "EXPRTOKEN_OPERATOR_AND"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_OR), "EXPRTOKEN_OPERATOR_OR"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_MOD), "EXPRTOKEN_OPERATOR_MOD"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_DIV), "EXPRTOKEN_OPERATOR_DIV"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_MULT), "EXPRTOKEN_OPERATOR_MULT"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_SLASH), "EXPRTOKEN_OPERATOR_SLASH"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_DOUBLE_SLASH), "EXPRTOKEN_OPERATOR_DOUBLE_SLASH"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_UNION), "EXPRTOKEN_OPERATOR_UNION"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_PLUS), "EXPRTOKEN_OPERATOR_PLUS"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_MINUS), "EXPRTOKEN_OPERATOR_MINUS"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_EQUAL), "EXPRTOKEN_OPERATOR_EQUAL"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_NOT_EQUAL), "EXPRTOKEN_OPERATOR_NOT_EQUAL"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_LESS), "EXPRTOKEN_OPERATOR_LESS"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_LESS_EQUAL), "EXPRTOKEN_OPERATOR_LESS_EQUAL"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_GREATER), "EXPRTOKEN_OPERATOR_GREATER"); fTokenNames.put(new Integer(EXPRTOKEN_OPERATOR_GREATER_EQUAL), "EXPRTOKEN_OPERATOR_GREATER_EQUAL"); fTokenNames.put(new Integer(EXPRTOKEN_FUNCTION_NAME), "EXPRTOKEN_FUNCTION_NAME"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_ANCESTOR), "EXPRTOKEN_AXISNAME_ANCESTOR"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_ANCESTOR_OR_SELF), "EXPRTOKEN_AXISNAME_ANCESTOR_OR_SELF"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_ATTRIBUTE), "EXPRTOKEN_AXISNAME_ATTRIBUTE"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_CHILD), "EXPRTOKEN_AXISNAME_CHILD"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_DESCENDANT), "EXPRTOKEN_AXISNAME_DESCENDANT"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_DESCENDANT_OR_SELF), "EXPRTOKEN_AXISNAME_DESCENDANT_OR_SELF"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_FOLLOWING), "EXPRTOKEN_AXISNAME_FOLLOWING"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_FOLLOWING_SIBLING), "EXPRTOKEN_AXISNAME_FOLLOWING_SIBLING"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_NAMESPACE), "EXPRTOKEN_AXISNAME_NAMESPACE"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_PARENT), "EXPRTOKEN_AXISNAME_PARENT"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_PRECEDING), "EXPRTOKEN_AXISNAME_PRECEDING"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_PRECEDING_SIBLING), "EXPRTOKEN_AXISNAME_PRECEDING_SIBLING"); fTokenNames.put(new Integer(EXPRTOKEN_AXISNAME_SELF), "EXPRTOKEN_AXISNAME_SELF"); fTokenNames.put(new Integer(EXPRTOKEN_LITERAL), "EXPRTOKEN_LITERAL"); fTokenNames.put(new Integer(EXPRTOKEN_NUMBER), "EXPRTOKEN_NUMBER"); fTokenNames.put(new Integer(EXPRTOKEN_VARIABLE_REFERENCE), "EXPRTOKEN_VARIABLE_REFERENCE"); } // Public methods /** * @author Glenn Marcy, IBM * @author Andy Clark, IBM * * @version $Id$ */ private static class Scanner { /** * 7-bit ASCII subset * * 0 1 2 3 4 5 6 7 8 9 A B C D E F * 0, 0, 0, 0, 0, 0, 0, 0, 0, HT, LF, 0, 0, CR, 0, 0, // 0 * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 * SP, !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, // 2 * 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, :, ;, <, =, >, ?, // 3 * @, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, // 4 * P, Q, R, S, T, U, V, W, X, Y, Z, [, \, ], ^, _, // 5 * `, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, // 6 * p, q, r, s, t, u, v, w, x, y, z, {, |, }, ~, DEL // 7 */ private static final byte CHARTYPE_INVALID = 0, // invalid XML character CHARTYPE_OTHER = 1, // not special - one of "#%&;?\^`{}~" or DEL CHARTYPE_WHITESPACE = 2, // one of "\t\n\r " (0x09, 0x0A, 0x0D, 0x20) CHARTYPE_EXCLAMATION = 3, // '!' (0x21) CHARTYPE_QUOTE = 4, // '\"' or '\'' (0x22 and 0x27) CHARTYPE_DOLLAR = 5, // '$' (0x24) CHARTYPE_OPEN_PAREN = 6, // '(' (0x28) CHARTYPE_CLOSE_PAREN = 7, // ')' (0x29) CHARTYPE_STAR = 8, // '*' (0x2A) CHARTYPE_PLUS = 9, // '+' (0x2B) CHARTYPE_COMMA = 10, // ',' (0x2C) CHARTYPE_MINUS = 11, // '-' (0x2D) CHARTYPE_PERIOD = 12, // '.' (0x2E) CHARTYPE_SLASH = 13, // '/' (0x2F) CHARTYPE_DIGIT = 14, // '0'-'9' (0x30 to 0x39) CHARTYPE_COLON = 15, // ':' (0x3A) CHARTYPE_LESS = 16, // '<' (0x3C) CHARTYPE_EQUAL = 17, // '=' (0x3D) CHARTYPE_GREATER = 18, // '>' (0x3E) CHARTYPE_ATSIGN = 19, // '@' (0x40) CHARTYPE_LETTER = 20, // 'A'-'Z' or 'a'-'z' (0x41 to 0x5A and 0x61 to 0x7A) CHARTYPE_OPEN_BRACKET = 21, // '[' (0x5B) CHARTYPE_CLOSE_BRACKET = 22, // ']' (0x5D) CHARTYPE_UNDERSCORE = 23, // '_' (0x5F) CHARTYPE_UNION = 24, // '|' (0x7C) CHARTYPE_NONASCII = 25; // Non-ASCII Unicode codepoint (>= 0x80) private static byte[] fASCIICharMap = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4, 1, 5, 1, 1, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 1, 16, 17, 18, 1, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 1, 22, 1, 23, 1, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 1, 24, 1, 1, 1 }; /** * Symbol literals */ /** Symbol table. */ /** Constructs an XPath expression scanner. */ public boolean scanExpr(SymbolTable symbolTable, XPath.Tokens tokens, String data, int currentOffset, int endOffset) throws XPathException { int nameOffset; String nameHandle, prefixHandle; boolean starIsMultiplyOperator = false; int ch; final String emptySymbol = fSymbolTable.addSymbol(""); currentOffset = scanNumber(tokens, data, endOffset, currentOffset/*, encoding*/); currentOffset = scanNumber(tokens, data, endOffset, currentOffset/*, encoding*/); /* void allocateProducer(byte[] data, int offset, int length, EncodingSupport encoding) { XPathStringProducer sp = fStringProducers[fStringProducerCount]; if (sp != null) { sp = sp.setState(data, offset, length, encoding); } else { sp = new XPathStringProducer(data, offset, length, encoding); } fStringProducers[fStringProducerCount++] = sp; } void finalizeProducer(byte[] data) { fStringProducerCount--; } private class XPathStringProducer { byte[] fData = null; int fOffset = -1; int fLength = -1; String fEncoding = null; XPathStringProducer(byte[] data, int offset, int length, EncodingSupport encoding) { init(data, offset, length, encoding); } XPathStringProducer setState(byte[] bytes, int offset, int length, EncodingSupport encoding) { init(bytes, offset, length, encoding); return this; } void init(byte[] data, int offset, int length, EncodingSupport encoding) { fData = data; fOffset = offset; fLength = length; fEncoding = encoding; } String getEncoding() { return fEncoding; } void finalizeProducer() { // do nothing } int addSymbol(int offset, int length) { return fSymbolTable.addSymbol(fData, offset, length, fEncoding); } } private XPathStringProducer[] fStringProducers = new XPathStringProducer[8]; private int fStringProducerCount = 0; private XPathStringProducer getStringProducer(byte[] data) { XPathStringProducer sp = null; for (int i = 0; i < fStringProducerCount; i++) { if (fStringProducers[i].fData == data) { return fStringProducers[i]; } } throw new RuntimeException("No StringProducer"); } */ // [30] Number ::= Digits ('.' Digits?)? | '.' Digits // [31] Digits ::= [0-9]+ private int scanNumber(XPath.Tokens tokens, String/*byte[]*/ data, int endOffset, int currentOffset/*, EncodingSupport encoding*/) { int ch = data.charAt(currentOffset); int whole = 0; int part = 0; while (ch >= '0' && ch <= '9') { whole = (whole * 10) + (ch - '0'); if (++currentOffset == endOffset) { break; } ch = data.charAt(currentOffset); } if (ch == '.') { if (++currentOffset < endOffset) { int start = currentOffset; ch = data.charAt(currentOffset); while (ch >= '0' && ch <= '9') { part = (part * 10) + (ch - '0'); if (++currentOffset == endOffset) { break; } ch = data.charAt(currentOffset); } if (part != 0) { /** * This method adds the specified token to the token list. By * default, this method allows all tokens. However, subclasses * of the XPathExprScanner can override this method in order * to disallow certain tokens from being used in the scanned * XPath expression. This is a convenient way of allowing only * a subset of XPath. */ protected void addToken(XPath.Tokens tokens, int token) throws XPathException { tokens.addToken(token); } // addToken(int) } // class Scanner /** * @author Glenn Marcy, IBM * @author Andy Clark, IBM * * @version $Id$ */ /** Main program entry. */
package cf.commonpoint; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cf.commonpoint.cputility.XMLParser; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * * @author Sanjeet Singh R */ public class CPFilter { public static void redirect(String indicator,HttpServletRequest request,HttpServletResponse response) throws IOException, ParserConfigurationException, SAXException { switch(indicator) { case "https": String serverName=request.getServerName(); String requestURI=request.getRequestURI(); response.sendRedirect("https://"+serverName+requestURI); case "login": String uri="C:\\Security-Framework\\SecurityFramework\\src\\cf\\commonpoint\\config\\cpconfig.xml"; String node="login-page"; String redirectURI=XMLParser.getNodeValue(uri, node); response.sendRedirect(redirectURI); } } }
package com.gravity.fauna; import org.newdawn.slick.geom.Vector2f; import com.gravity.entity.PhysicsEntity; import com.gravity.geom.Rect; import com.gravity.levels.GameplayControl; import com.gravity.physics.GravityPhysics; import com.gravity.physics.PhysicalState; import com.gravity.root.GameSounds; public class Player extends PhysicsEntity<GravityPhysics> { public static enum Movement { LEFT, RIGHT, STOP } public static int TOP_LEFT = 0, TOP_RIGHT = 1, BOT_RIGHT = 2, BOT_LEFT = 3; // PLAYER STARTING CONSTANTS (Units = pixels, milliseconds) private static final float JUMP_POWER = 0.48f; // .6 before reset private static final float MOVEMENT_INCREMENT = 1f / 8f; private static final Rect BASE_SHAPE = new Rect(0f, 0f, 30f, 48f); private static final Vector2f DEFAULT_VELOCITY = new Vector2f(0, 0); private final float MAX_SLING_STRENGTH = 0.75f; // 1 before reset private final float SLING_SPEED = 1f / 400f; // 500f before reset private final float JUMP_COOLDOWN = 50f; private final GameplayControl control; // GAME STATE STUFF private final String name; private Movement requested = Movement.STOP; private boolean jumpExecuted = false; private float jumpCooldown = JUMP_COOLDOWN; private boolean moveInProgress = false; public boolean slingshot; public float slingshotStrength = 0; public boolean lastWalkedRight = true; public Player(GameplayControl control, GravityPhysics physics, String name, Vector2f startpos) { super(new PhysicalState(BASE_SHAPE.translate(startpos.x + 1, startpos.y), DEFAULT_VELOCITY.copy(), 0f), physics); this.name = name; this.control = control; } public String getName() { return name; } public boolean isRunning() { return moveInProgress && !physics.entitiesHitOnGround(this).isEmpty(); } public boolean isRising() { return physics.entitiesHitOnGround(this).isEmpty() && state.velY < 0; } public boolean isFalling() { return physics.entitiesHitOnGround(this).isEmpty() && state.velY >= 0; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Player [name="); builder.append(name); builder.append(", state="); builder.append(state); builder.append("]"); return builder.toString(); } public void kill() { control.playerDies(this); } // //////////////////////////KEY-PRESS METHODS/////////////////////////////// /** * @param jumping * true if keydown, false if keyup */ public void jump(boolean jumping) { if (jumping && !jumpExecuted && !physics.entitiesHitOnGround(this).isEmpty()) { jumpExecuted = true; GameSounds.playJumpSound(); // TODO: clean this up setPhysicalState(state.setVelocity(state.velX, state.velY - JUMP_POWER)); } } /** * * @param direction */ public void move(Movement direction) { switch (direction) { case LEFT: case RIGHT: { requested = direction; break; } case STOP: { requested = direction; if (moveInProgress) { moveInProgress = false; float vel = state.velX; if (vel >= 0) { setPhysicalState(state.setVelocity(Math.max(0, vel - MOVEMENT_INCREMENT), state.velY)); } else { setPhysicalState(state.setVelocity(Math.min(0, vel + MOVEMENT_INCREMENT), state.velY)); } } break; } } } /** * * @param pressed * true if keydown, false if keyup */ public void specialKey(boolean pressed) { if (pressed) { slingshot = true; } else { slingshot = false; control.specialMoveSlingshot(this, slingshotStrength); } } public void slingshotMe(float strength, Vector2f direction) { Vector2f velocity = direction.copy().normalise().scale(strength); state = state.setVelocity(velocity.x, velocity.y); moveInProgress = false; } // //////////////////////////ON-TICK METHODS///////////////////////////////// @Override public void startUpdate(float millis) { super.startUpdate(millis); if (jumpExecuted) { jumpCooldown -= millis; if (jumpCooldown <= 0f) { jumpCooldown = JUMP_COOLDOWN; jumpExecuted = false; } } } @Override public void finishUpdate(float millis) { super.finishUpdate(millis); switch (requested) { case LEFT: moveInProgress = true; lastWalkedRight = false; setPhysicalState(state.setVelocity(Math.min(state.velX, -MOVEMENT_INCREMENT), state.velY)); break; case RIGHT: moveInProgress = true; lastWalkedRight = true; setPhysicalState(state.setVelocity(Math.max(state.velX, MOVEMENT_INCREMENT), state.velY)); break; default: // no-op } if (slingshot) { slingshotStrength = MAX_SLING_STRENGTH; } else { slingshotStrength = 0; } } @Override public void unavoidableCollisionFound() { System.out.println("Player " + this.toString() + " was probably squashed by a moving platform."); kill(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.ui.panel; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.data.Interval; import org.broad.igv.feature.Chromosome; import org.broad.igv.feature.Locus; import org.broad.igv.feature.genome.Genome; import org.broad.igv.feature.genome.GenomeManager; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.ObservableForObject; import java.util.Observer; /** * @author jrobinso */ public class ReferenceFrame { private static Logger log = Logger.getLogger(ReferenceFrame.class); /** * The nominal viewport width in pixels. */ public static int binsPerTile = 700; private String name; /** * The chromosome currently in view */ protected String chrName = "chrAll"; /** * The minimum zoom level for the current screen size + chromosome combination. */ private int minZoom = 0; /** * The maximum zoom level. Set to prevent integer overflow. This is a function * of chromosome length. */ public int maxZoom = 23; /** * Minimum allowed scale in base pairs / pixel * TODO Does this ever change, couldn't it be static and/or final? */ private double minScale = 1.0 / 14; /** * The current zoom level. Zoom level -1 corresponds to the whole * genome view (chromosome "all") */ protected int zoom = minZoom; /** * X location of the frame in pixels */ volatile int pixelX; /** * Width of the frame in pixels */ protected int widthInPixels; /** * The number of tiles for this zoom level, = 2^zoom */ private double nTiles = 1; /** * The maximum virtual pixel value. */ //private double maxPixel; /** * The origin in bp */ protected volatile double origin = 0; /** * The location (x axis) locationScale in base pairs / virtual pixel */ protected volatile double locationScale; protected Locus initialLocus; /** * A temporary holder. We set the end location and then * later zoom/origin/etc. calculations are made */ protected int setEnd = 0; protected ObservableForObject<String> chromoObservable; public ReferenceFrame(String name) { this.name = name; Genome genome = getGenome(); this.chrName = genome == null ? "" : genome.getHomeChromosome(); chromoObservable = new ObservableForObject<String>(chrName); } public ReferenceFrame(ReferenceFrame otherFrame) { this.chrName = otherFrame.chrName; this.initialLocus = otherFrame.initialLocus; this.locationScale = otherFrame.locationScale; this.minScale = otherFrame.minScale; this.minZoom = otherFrame.minZoom; this.name = otherFrame.name; this.nTiles = otherFrame.nTiles; this.origin = otherFrame.origin; this.pixelX = otherFrame.pixelX; this.setEnd = otherFrame.setEnd; this.widthInPixels = otherFrame.widthInPixels; this.zoom = otherFrame.zoom; chromoObservable = new ObservableForObject<String>(chrName); } /** * Set the position and width of the frame, in pixels * @param pixelX * @param widthInPixels */ public synchronized void setBounds(int pixelX, int widthInPixels) { this.pixelX = pixelX; if (this.widthInPixels != widthInPixels) { this.widthInPixels = widthInPixels; computeLocationScale(); computeZoom(); } } /** * Sets zoom level and recomputes scale, iff newZoom != oldZoom * min/maxZoom are recalculated and respected, * and the locationScale is recomputed * @param newZoom */ protected void setZoom(int newZoom){ if(zoom != newZoom){ synchronized (this){ setZoomWithinLimits(newZoom); computeLocationScale(); } } } /** * Set the origin of the frame, guarding against chromosome boundaries * * @param position */ public void setOrigin(double position) { int windowLengthBP = (int) (widthInPixels * getScale()); double newOrigin; if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_SOFT_CLIPPED)) { newOrigin = Math.max(-1000, Math.min(position, getChromosomeLength() + 1000 - windowLengthBP)); } else { newOrigin = Math.max(0, Math.min(position, getChromosomeLength() - windowLengthBP)); } origin = newOrigin; } private synchronized void setZoomWithinLimits(int newZoom){ computeMinZoom(); computeMaxZoom(); zoom = Math.max(minZoom, Math.min(maxZoom, newZoom)); nTiles = Math.pow(2, zoom); } /** * Increment the zoom level by {@code zoomIncrement}, leaving * the center the same * @param zoomIncrement */ public void doZoomIncrement(int zoomIncrement) { double currentCenter = getGenomeCenterPosition(); doIncrementZoom(zoomIncrement, currentCenter); } /** * Set the zoom level to {@code newZoom}, leaving * the center the same * @param newZoom */ public void doSetZoom(int newZoom) { double currentCenter = getGenomeCenterPosition(); doSetZoomCenter(newZoom, currentCenter); } public void doIncrementZoom(final int zoomIncrement, final double newCenter) { doSetZoomCenter(getZoom() + zoomIncrement, newCenter); } /** * Intended to be called by UI elements, this method * performs all actions necessary to set a new zoom * and center location * @param newZoom * @param newCenter */ public void doSetZoomCenter(final int newZoom, final double newCenter) { if (chrName.equals(Globals.CHR_ALL)) { chrName = getGenome().getHomeChromosome(); } if (chrName.equals(Globals.CHR_ALL)) { // Translate the location to chromosome number synchronized (this){ jumpToChromosomeForGenomeLocation(newCenter); } IGV.getInstance().chromosomeChangeEvent(chrName); } else { setZoom(newZoom); // Adjust origin so newCenter is centered centerOnLocation(newCenter); } IGV.repaintPanelsHeadlessSafe(); recordHistory(); // This is a hack, this is not a drag event but is a "jump" DragEventManager.getInstance().dragStopped(); } protected double getGenomeCenterPosition() { return origin + ((widthInPixels / 2) * getScale()); } /** * Return the current locationScale in base pairs / pixel * * @return */ public double getScale() { if (locationScale <= 0) { computeLocationScale(); } return locationScale; } public void invalidateLocationScale() { this.locationScale = -1; } /** * Change the frame to the specified chromosome. * * @param name * @param force */ public synchronized void setChromosomeName(String name, boolean force) { if ((chrName == null) || !name.equals(chrName) || force) { chrName = name; origin = 0; setEnd = -1; this.zoom = -1; setZoom(0); chromoObservable.setChangedAndNotify(); } } /** * Recalculate the locationScale, based on {@link #setEnd}, {@link #origin}, and * {@link #widthInPixels} * DOES NOT alter zoom value */ private synchronized void computeLocationScale() { Genome genome = getGenome(); //Should consider getting rid of this. We don't have //a chromosome length without a genome, not always a problem if (genome != null) { if (setEnd > 0 && widthInPixels > 0) { this.locationScale = ((setEnd - origin) / widthInPixels); setEnd = -1; } else { double virtualPixelSize = getTilesTimesBinsPerTile(); double nPixel = Math.max(virtualPixelSize, widthInPixels); this.locationScale = (((double) getChromosomeLength()) / nPixel); } } } /** * Recalculate the zoom value based on current start/end * locationScale is not altered * */ private void computeZoom() { int newZoom = calculateZoom(getOrigin(), getEnd()); setZoomWithinLimits(newZoom); } /** * Compute the minimum zoom level for the data panel width. This is defined as the maximum * zoom level for which all data bins will fit in the window without loss of * data, i.e. the maximum zoom level for which nBins < nPixels. The number * of bins is defined as * nBins = 2^z * so minZoom is the value z such that nBins < dataPanelWidth */ protected void computeMinZoom() { if (this.chrName.equals(Globals.CHR_ALL)) { minZoom = 0; } else { minZoom = Math.max(0, (int) (Math.log((widthInPixels / binsPerTile)) / Globals.log2)); } } /** * Record the current state of the frame in history. * It is recommended that this NOT be called from within ReferenceFrame, * and callers use it after making all changes */ public void recordHistory() { IGV.getInstance().getSession().getHistory().push(getFormattedLocusString(), zoom); } private void jumpToChromosomeForGenomeLocation(double locationMB) { double startMB = 0; for (String chr : getGenome().getLongChromosomeNames()) { double endMB = startMB + getGenome().getChromosome(chr).getLength() / 1000.0; if ((locationMB > startMB) && (locationMB <= endMB)) { this.setChromosomeName(chr); break; } startMB = endMB; } } public void shiftOriginPixels(int delta) { double shiftBP = delta * getScale(); setOrigin(origin + shiftBP); IGV.repaintPanelsHeadlessSafe(); } public void snapToGrid() { setOrigin(Math.round(origin)); IGV.repaintPanelsHeadlessSafe(); } public void centerOnLocation(String chr, double chrLocation) { if (!chrName.equals(chr)) { setChromosomeName(chr); } centerOnLocation(chrLocation); } public void centerOnLocation(double chrLocation) { double windowWidth = (widthInPixels * getScale()) / 2; setOrigin(Math.round(chrLocation - windowWidth)); } public boolean windowAtEnd() { double windowLengthBP = widthInPixels * getScale(); return origin + windowLengthBP + 1 > getChromosomeLength(); } /** * Move the frame to the specified position. New zoom is calculated * based on limits. * * @param chr * @param start * @param end */ public void jumpTo(String chr, int start, int end) { Locus locus = new Locus(chr, start, end); this.jumpTo(locus); } public void jumpTo(Locus locus) { String chr = locus.getChr(); int start = locus.getStart(); int end = locus.getEnd(); Genome genome = getGenome(); if (chr != null) { if (genome.getChromosome(chr) == null && !chr.contains(Globals.CHR_ALL)) { MessageUtils.showMessage(chr + " is not a valid chromosome."); return; } } this.initialLocus = locus; Chromosome chromosome = genome == null ? null : genome.getChromosome(chr); if (chromosome != null) { end = Math.min(chromosome.getLength(), end); } synchronized (this) { this.chrName = chr; if (start >= 0 && end >= 0) { this.setOrigin(start); this.setEnd = end; computeLocationScale(); setZoomWithinLimits(calculateZoom(this.getOrigin(), this.getEnd())); } } if (log.isDebugEnabled()) { log.debug("Data panel width = " + widthInPixels); log.debug("New start = " + (int) origin); log.debug("New end = " + (int) getEnd()); log.debug("New center = " + (int) getCenter()); log.debug("Scale = " + locationScale); } //Mostly for testing IGV.repaintPanelsHeadlessSafe(); } /** * Compute the maximum zoom level, which is a function of chromosome length. */ private void computeMaxZoom() { Genome genome = getGenome(); // Compute max zoom. Assume window size @ max zoom of ~ 50 bp if (genome != null && chrName != null && genome.getChromosome(chrName) != null) { if (chrName.equals(Globals.CHR_ALL)) { maxZoom = 0; } else { int chrLength = genome.getChromosome(chrName).getLength(); maxZoom = (int) (Math.log(chrLength / 50.0) / Globals.log2) + 1; } } } /** * Calculate the zoom level given start/end in bp. * Doesn't change anything * @param start * @param end * @return */ protected int calculateZoom(double start, double end) { return (int) (Math.log(getChromosomeLength() / (end - start)) / Globals.log2) + 1; } protected Genome getGenome() { return GenomeManager.getInstance().getCurrentGenome(); } public double getOrigin() { return origin; } public double getCenter() { return origin + getScale() * widthInPixels / 2; } public double getEnd() { return origin + getScale() * widthInPixels; } public int getZoom() { return zoom; } /** * Return the maximum zoom level * * @return */ public int getMaxZoom() { return maxZoom; } public int getAdjustedZoom() { return zoom - minZoom; } public double getMaxPixel() { return getTilesTimesBinsPerTile(); } public void addObserver(Observer observer) { chromoObservable.addObserver(observer); } public void deleteObserver(Observer observer) { chromoObservable.deleteObserver(observer); } public void deleteObservers() { chromoObservable.deleteObservers(); } /** * @param name */ public void setChromosomeName(String name) { setChromosomeName(name, false); } public String getChrName() { return chrName; } // TODO -- this parameter shouldn't be stored here. Maybe in a specialized // layout manager? public int getWidthInPixels() { return widthInPixels; } /** * Return the chromosome position corresponding to the pixel index. The * pixel index is the pixel "position" translated by -origin. * * @param screenPosition * @return */ public double getChromosomePosition(int screenPosition) { return origin + getScale() * screenPosition; } /** * Return the screen position corresponding to the chromosomal position. * * @param chromosomePosition * @return */ public int getScreenPosition(double chromosomePosition) { return (int) ((chromosomePosition - origin) / getScale()); } public Chromosome getChromosome() { Genome genome = getGenome(); if (genome == null) { return null; } return genome.getChromosome(chrName); } public int getChromosomeLength() { Genome genome = getGenome(); if (genome == null) { return 1; } if (chrName.equals("All")) { // TODO -- remove the hardcoded unit divider ("1000") return (int) (genome.getNominalLength() / 1000); // return genome.getLength(); } else { if (getChromosome() == null) { log.error("Null chromosome: " + chrName); if (genome == null || genome.getChromosomes().size() == 0) { return 1; } else { return genome.getChromosomes().iterator().next().getLength(); } } return getChromosome().getLength(); } } public double getTilesTimesBinsPerTile() { return nTiles * (double) binsPerTile; } public int getMidpoint() { return pixelX + widthInPixels / 2; } /** * Get the UCSC style locus string corresponding to the current view. THe UCSC * conventions are followed for coordinates, specifically the internal representation * is "zero" based (first base is numbered 0) but the display representation is * "one" based (first base is numbered 1). Consequently 1 is added to the * computed positions. * * @return */ public String getFormattedLocusString() { if (zoom == 0) { return getChrName(); } else { Range range = getCurrentRange(); return Locus.getFormattedLocusString(range.getChr(), range.getStart(), range.getEnd()); } } public Range getCurrentRange() { int start = 0; int end = widthInPixels; int startLoc = (int) getChromosomePosition(start) + 1; int endLoc = (int) getChromosomePosition(end); Range range = new Range(getChrName(), startLoc, endLoc); return range; } public void reset() { jumpTo(FrameManager.getLocus(name)); } public String getName() { return name; } public Locus getInitialLocus() { return initialLocus; } public int getMinZoom() { return minZoom; } public boolean isExomeMode() { return false; } public void setName(String name) { this.name = name; } public boolean overlaps(Interval interval) { return this.getChrName().equals(interval.getChr()) && this.getOrigin() <= interval.getEnd() && this.getEnd() >= interval.getStart(); } public static class Range { private String chr; private int start; private int end; public Range(String chr, int start, int end) { this.chr = chr; this.start = start; this.end = end; } public String getChr() { return chr; } public int getStart() { return start; } public int getEnd() { return end; } public int getLength() { return end - start; } } }
package org.cipher.utils; import org.cipher.utils.math.Matrix; import java.lang.reflect.Array; import java.lang.reflect.Type; public final class CryptMatrixGenerator<T> { private final Class<T> clazzType; private int column; private int row; private Matrix matrix; private CryptMatrixGenerator(CryptMatrixGeneratorBuilder builder) { this.clazzType = builder.clazzType; this.column= builder.column; this.row = builder.row; createCryptMatrix(); } @SuppressWarnings("T casting can cause problems") private void createCryptMatrix() { T[][] genericCryptMatrix = ((T[][]) Array.newInstance(clazzType, this.row, this.column)); this.matrix = new Matrix(genericCryptMatrix); } public void fill(T ... values) { T[][] tmpGenericData = (T[][]) matrix.getData(); int index = 0; for (int i = 0; i < tmpGenericData.length; i++) { for (int j = 0; j < tmpGenericData[i].length; j++) { tmpGenericData[i][j] = values[index++]; } } this.matrix.setData(tmpGenericData); } public Matrix getGenereratedCryptMatrix() { return matrix; } public static class CryptMatrixGeneratorBuilder<T> { //default values private int column = 5; private int row = 5; private final Class<T> clazzType; public CryptMatrixGeneratorBuilder(Class<T> clazzType) { if (clazzType == null) throw new IllegalArgumentException("Type can not be null"); this.clazzType = clazzType; } public CryptMatrixGeneratorBuilder withSize(int size) { if (size < 0) throw new IllegalArgumentException("Size can not be negative"); this.column = this.row = size; return this; } public CryptMatrixGeneratorBuilder withColumn(int column) { if (column < 0) throw new IllegalArgumentException("Column size can not be negative"); this.column = column; return this; } public CryptMatrixGeneratorBuilder withRow(int row) { if (row < 0) throw new IllegalArgumentException("Row size can to be negative"); this.row = row; return this; } public CryptMatrixGenerator build() { return new CryptMatrixGenerator(this); } } }
package orc.run.porce; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.frame.VirtualFrame; import orc.run.porce.runtime.CPSCallResponseHandler; import orc.run.porce.runtime.Counter; import orc.run.porce.runtime.PorcEClosure; import orc.run.porce.runtime.PorcEExecutionRef; import orc.run.porce.runtime.Terminator; public class InterceptedCall extends CallBase { protected InterceptedCall(Expression target, Expression[] arguments, PorcEExecutionRef execution) { super(target, arguments, execution); } public Object executeWithValues(final VirtualFrame frame, final Object newTarget, final Object[] newArguments) { final PorcEClosure pub = (PorcEClosure) newArguments[0]; final Counter counter = (Counter) newArguments[1]; final Terminator term = (Terminator) newArguments[2]; // Token: Passed to handle from arguments. final CPSCallResponseHandler handle = new CPSCallResponseHandler(execution.get(), pub, counter, term, getCallSiteId()); invokeInterceptedWithBoundary(handle, newTarget, newArguments); return PorcEUnit.SINGLETON; } @TruffleBoundary private void invokeInterceptedWithBoundary(final CPSCallResponseHandler handle, final Object newTarget, final Object[] newArguments) { execution.get().invokeIntercepted(handle, newTarget, buildArgumentValues(newArguments)); } @Override public Object execute(final VirtualFrame frame) { final Object targetValue = executeTargetClosure(frame); final Object[] argumentValues = new Object[arguments.length]; executeArguments(argumentValues, 0, 0, frame); return executeWithValues(frame, targetValue, argumentValues); } protected Object[] buildArgumentValues(final Object[] newArguments) { final Object[] argumentValues = new Object[newArguments.length - 3]; System.arraycopy(newArguments, 3, argumentValues, 0, argumentValues.length); return argumentValues; } public static InterceptedCall create(Expression target, Expression[] arguments, PorcEExecutionRef execution) { return new InterceptedCall(target, arguments, execution); } }
package org.exist.xquery; import org.exist.xquery.util.ExpressionDumper; import org.exist.xquery.value.AtomicValue; import org.exist.xquery.value.Item; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.StringValue; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Node constructor for attribute nodes. * * @author wolf */ public class AttributeConstructor extends NodeConstructor { final String qname; final List<Object> contents = new ArrayList<Object>(5); boolean isNamespaceDecl = false; public AttributeConstructor(XQueryContext context, String name) { super(context); if(name.startsWith("xmlns")) isNamespaceDecl = true; this.qname = name; } public void addValue(String value) { contents.add(value); } public void addEnclosedExpr(Expression expr) throws XPathException { if(isNamespaceDecl) throw new XPathException(this, "enclosed expressions are not allowed in namespace " + "declaration attributes"); contents.add(expr); } public String getQName() { return qname; } public boolean isNamespaceDeclaration() { return isNamespaceDecl; } /* (non-Javadoc) * @see org.exist.xquery.Expression#analyze(org.exist.xquery.Expression) */ public void analyze(AnalyzeContextInfo contextInfo) throws XPathException { super.analyze(contextInfo); contextInfo.setParent(this); for(Object next : contents) { if(next instanceof Expression) ((Expression)next).analyze(contextInfo); } } /* (non-Javadoc) * @see org.exist.xquery.Expression#eval(org.exist.xquery.StaticContext, org.exist.dom.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item) */ public Sequence eval( Sequence contextSequence, Item contextItem) throws XPathException { StringBuilder buf = new StringBuilder(); for(Object next : contents) { if(next instanceof Expression) evalEnclosedExpr(((Expression)next).eval(contextSequence, contextItem), buf); else buf.append(next); } //TODO : include that tricky attribute normalization here StringValue result = new StringValue(buf.toString()); // String values as expressions are already expanded by // the parser -- Alex //result.expand(); return result; } private void evalEnclosedExpr(Sequence seq, StringBuilder buf) throws XPathException { Item item; AtomicValue atomic; for(SequenceIterator i = seq.iterate(); i.hasNext();) { item = i.nextItem(); atomic = item.atomize(); buf.append(atomic.getStringValue()); if(i.hasNext()) buf.append(' '); } } /** * If this is a namespace declaration attribute, return * the single string value of the attribute. */ public String getLiteralValue() { if(contents.size() == 0) return ""; return (String)contents.get(0); } /* (non-Javadoc) * @see org.exist.xquery.Expression#dump(org.exist.xquery.util.ExpressionDumper) */ public void dump(ExpressionDumper dumper) { dumper.display("attribute "); //TODO : remove curly braces if Qname dumper.display("{"); dumper.display(qname); dumper.display("} "); dumper.display("{"); dumper.startIndent(); for(Object next : contents) { if(next instanceof Expression) ((Expression)next).dump(dumper); else dumper.display(next); } dumper.endIndent(); dumper.nl().display("} "); } public String toString() { StringBuilder result = new StringBuilder(); result.append("attribute "); //TODO : remove curly braces if Qname result.append("{"); result.append(qname); result.append("} "); result.append("{"); for(Object next : contents) { if(next instanceof Expression) result.append(next.toString()); else result.append(next.toString()); } result.append("} "); return result.toString(); } /* (non-Javadoc) * @see org.exist.xquery.NodeConstructor#resetState() */ @Override public void resetState(boolean postOptimization) { super.resetState(postOptimization); for(Object object : contents) { if(object instanceof Expression) ((Expression)object).resetState(postOptimization); } } public Iterator<Object> contentIterator() { return contents.iterator(); } }
package org.exist.xquery; import org.exist.dom.QName; import org.exist.xquery.util.ExpressionDumper; import org.exist.xquery.value.BooleanValue; import org.exist.xquery.value.Item; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.Type; /** * Represents a quantified expression: "some ... in ... satisfies", * "every ... in ... satisfies". * * @author Wolfgang Meier (wolfgang@exist-db.org) */ public class QuantifiedExpression extends BindingExpression { public final static int SOME = 0; public final static int EVERY = 1; private int mode = SOME; /** * @param context */ public QuantifiedExpression(XQueryContext context, int mode) { super(context); this.mode = mode; } /* (non-Javadoc) * @see org.exist.xquery.BindingExpression#analyze(org.exist.xquery.Expression, int, org.exist.xquery.OrderSpec[]) */ public void analyze(Expression parent, int flags, OrderSpec orderBy[]) throws XPathException { LocalVariable mark = context.markLocalVariables(); context.declareVariable(new LocalVariable(QName.parse(context, varName, null))); inputSequence.analyze(this, flags); returnExpr.analyze(this, flags); context.popLocalVariables(mark); } public Sequence eval(Sequence contextSequence, Item contextItem, Sequence resultSequence) throws XPathException { if (contextItem != null) contextSequence = contextItem.toSequence(); LocalVariable mark = context.markLocalVariables(); LocalVariable var = new LocalVariable(QName.parse(context, varName, null)); context.declareVariable(var); Sequence inSeq = inputSequence.eval(contextSequence); Sequence satisfiesSeq; boolean found = false; for(SequenceIterator i = inSeq.iterate(); i.hasNext(); ) { contextItem = i.nextItem(); var.setValue(contextItem.toSequence()); var.checkType(); satisfiesSeq = returnExpr.eval(contextSequence); found = satisfiesSeq.effectiveBooleanValue(); if((mode == SOME && found) || (mode == EVERY && !found)) break; } context.popLocalVariables(mark); return found ? BooleanValue.TRUE : BooleanValue.FALSE; } /* (non-Javadoc) * @see org.exist.xquery.Expression#dump(org.exist.xquery.util.ExpressionDumper) */ public void dump(ExpressionDumper dumper) { dumper.display(mode == SOME ? "some" : "every"); dumper.display(" $").display(varName).display(" in"); dumper.startIndent(); inputSequence.dump(dumper); dumper.endIndent().nl(); dumper.display("satisfies"); dumper.startIndent(); returnExpr.dump(dumper); dumper.endIndent(); } /* (non-Javadoc) * @see org.exist.xquery.Expression#returnsType() */ public int returnsType() { return Type.BOOLEAN; } /* (non-Javadoc) * @see org.exist.xquery.AbstractExpression#getDependencies() */ public int getDependencies() { return Dependency.CONTEXT_ITEM | Dependency.CONTEXT_SET; } }
package org.jitsi.meet.test; import org.openqa.selenium.*; import org.openqa.selenium.chrome.*; /** * The static fixture which holds the drivers to access the conference * participant pages. * * @author Damian Minkov */ public class ConferenceFixture { public static final String JITSI_MEET_URL_PROP = "jitsi-meet.instance.url"; public static String currentRoomName; /** * The focus in the tests. */ private static WebDriver focus; /** * The second participant. */ private static WebDriver secondParticipant; /** * Returns the currently allocated focus. * @return the currently allocated focus. */ public static WebDriver getFocus() { return focus; } /** * Returns the currently allocated second participant. * @return the currently allocated second participant. */ public static WebDriver getSecondParticipant() { if(secondParticipant == null) { // this will only happen if some test that quits the // second participant fails, and couldn't open it startParticipant(); } return secondParticipant; } /** * Starts the focus, the first participant that generates the random * room name. */ public static void startFocus() { focus = startChromeInstance(); currentRoomName = "torture" + String.valueOf((int)(Math.random()*1000000)); openRoom(focus); } /** * Opens the room for the given participant. * @param participant to open the current test room. */ public static void openRoom(WebDriver participant) { participant.get(System.getProperty(JITSI_MEET_URL_PROP) + "/" + currentRoomName); // disables animations ((JavascriptExecutor) participant) .executeScript("try { jQuery.fx.off = true; } catch(e) {}"); } /** * Starts chrome instance using some default settings. * @return the webdriver instance. */ private static WebDriver startChromeInstance() { ChromeOptions ops = new ChromeOptions(); ops.addArguments("use-fake-ui-for-media-stream"); ops.addArguments("use-fake-device-for-media-stream"); /** * Start another participant reusing the already generated room name. */ public static void startParticipant() { secondParticipant = startChromeInstance(); openRoom(secondParticipant); } /** * Checks whether participant has joined the room * @param participant where we check * @param timeout the time to wait for the event. */ public static void checkParticipantToJoinRoom( WebDriver participant, long timeout) { TestUtils.waitsForBoolean( participant, "return connection.emuc.joined;", timeout); } /** * Waits the focus to get event for iceConnectionState that changes * to connected. */ public static void waitsFocusToJoinConference() { TestUtils.waitsForBoolean( focus, "return focus !== null" ,10); TestUtils.waitsForBoolean( focus, "return (typeof focus.peerconnection !== 'undefined');" ,10); // lets wait till the state becomes connected TestUtils.waitsForEqualsStrings( focus, "return focus.peerconnection.iceConnectionState;", "connected", 30 ); } /** * Waits the participant to get event for iceConnectionState that changes * to connected. */ public static void waitsSecondParticipantToJoinConference() { TestUtils.waitsForBoolean( secondParticipant, "for (sid in connection.sessions) {" + "if (connection.sessions[sid].iceConnectionState " + "!== 'connected')" + "return false;" + "}" + "return true;" ,30); } /** * Quits the participant. * @param participant to quit. */ public static void quit(WebDriver participant) { try { participant.close(); participant.quit(); } catch(Throwable t) { t.printStackTrace(); } if(participant == focus) focus = null; else if(participant == secondParticipant) secondParticipant = null; } }
package org.nutz.mvc.config; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import javax.servlet.ServletContext; import org.nutz.aop.DefaultClassDefiner; import org.nutz.castor.Castors; import org.nutz.ioc.Ioc; import org.nutz.json.Json; import org.nutz.lang.Lang; import org.nutz.lang.Mirror; import org.nutz.lang.Strings; import org.nutz.lang.util.Context; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.mvc.Loading; import org.nutz.mvc.Mvcs; import org.nutz.mvc.NutConfig; import org.nutz.mvc.NutConfigException; import org.nutz.mvc.SessionProvider; import org.nutz.mvc.annotation.LoadingBy; import org.nutz.mvc.impl.NutLoading; import org.nutz.resource.Scans; public abstract class AbstractNutConfig implements NutConfig { private static final Log log = Logs.get(); private SessionProvider sessionProvider; public AbstractNutConfig(ServletContext context) { Scans.me().init(context); Json.clearEntityCache(); } public Loading createLoading() { /* * MainModule */ Class<?> mainModule = getMainModule(); DefaultClassDefiner.init(mainModule.getClassLoader()); /* * Loading */ LoadingBy by = mainModule.getAnnotation(LoadingBy.class); if (null == by) { if (log.isDebugEnabled()) log.debug("Loading by " + NutLoading.class); return new NutLoading(); } try { if (log.isDebugEnabled()) log.debug("Loading by " + by.value()); return Mirror.me(by.value()).born(); } catch (Exception e) { throw Lang.wrapThrow(e); } } public Context getLoadingContext() { return (Context) this.getServletContext().getAttribute(Loading.CONTEXT_NAME); } public String getAppRoot() { String webinf = getServletContext().getRealPath("/WEB-INF/"); if (webinf == null) { log.info("/WEB-INF/ not Found?!"); return ""; } String root = getServletContext().getRealPath("/").replace('\\', '/'); if (root.endsWith("/")) return root.substring(0, root.length() - 1); else if (root.endsWith("/.")) return root.substring(0, root.length() - 2); return root; } public Ioc getIoc() { return Mvcs.getIoc(); } public Object getAttribute(String name) { return this.getServletContext().getAttribute(name); } public List<String> getAttributeNames() { return enum2list(this.getServletContext().getAttributeNames()); } @SuppressWarnings("unchecked") public <T> T getAttributeAs(Class<T> type, String name) { Object obj = getAttribute(name); if (null == obj) return null; if (type.isInstance(obj)) return (T) obj; return Castors.me().castTo(obj, type); } public void setAttribute(String name, Object obj) { this.getServletContext().setAttribute(name, obj); } public void setAttributeIgnoreNull(String name, Object obj) { if (null != obj) setAttribute(name, obj); } public Class<?> getMainModule() { String name = Strings.trim(getInitParameter("modules")); try { Class<?> mainModule = null; if (Strings.isBlank(name)) throw new NutConfigException("You need declare 'modules' parameter in your context configuration file or web.xml ! Only found -> " + getInitParameterNames()); mainModule = Lang.loadClass(name); log.debugf("MainModule: <%s>", mainModule.getName()); return mainModule; } catch (NutConfigException e) { throw e; } catch (Exception e) { throw new NutConfigException(e); } } public AtMap getAtMap() { return Mvcs.getAtMap(); } protected List<String> enum2list(Enumeration<?> enums) { LinkedList<String> re = new LinkedList<String>(); while (enums.hasMoreElements()) re.add(enums.nextElement().toString()); return re; } public void setSessionProvider(SessionProvider provider) { this.sessionProvider = provider; } public SessionProvider getSessionProvider() { return sessionProvider; } }
package org.ohmage.domain; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.ohmage.annotator.ErrorCodes; import org.ohmage.cache.MobilityPrivacyStateCache; import org.ohmage.domain.MobilityInformation.SensorData.AccelData; import org.ohmage.util.StringUtils; import org.ohmage.util.TimeUtils; import edu.ucla.cens.mobilityclassifier.Sample; /** * This class is responsible for individual Mobility data points. * * @author John Jenkins */ public class MobilityInformation { private static final String JSON_KEY_DATE = "date"; private static final String JSON_KEY_DATE_SHORT = "ts"; private static final String JSON_KEY_TIME = "time"; private static final String JSON_KEY_TIMEZONE = "timezone"; private static final String JSON_KEY_TIMEZONE_SHORT = "tz"; private static final String JSON_KEY_LOCATION_STATUS = "location_status"; private static final String JSON_KEY_LOCATION_STATUS_SHORT = "ls"; private static final String JSON_KEY_LOCATION = "location"; private static final String JSON_KEY_LOCATION_SHORT = "l"; private static final String JSON_KEY_SUBTYPE = "subtype"; // Mode-only private static final String JSON_KEY_MODE = "mode"; private static final String JSON_KEY_MODE_SHORT = "m"; // Sensor data private static final String JSON_KEY_DATA = "data"; private final Date date; private final long time; private final TimeZone timezone; private final MobilityPrivacyStateCache.PrivacyState privacyState; public static enum LocationStatus { VALID, NETWORK, INACCURATE, STALE, UNAVAILABLE }; private final LocationStatus locationStatus; /** * This class contains all of the information associated with a location * record. * * @author John Jenkins */ public final class Location { private static final String JSON_KEY_LATITUDE = "latitude"; private static final String JSON_KEY_LATITUDE_SHORT = "la"; private static final String JSON_KEY_LONGITUDE = "longitude"; private static final String JSON_KEY_LONGITUDE_SHORT = "lo"; private static final String JSON_KEY_ACCURACY = "accuracy"; private static final String JSON_KEY_ACCURACY_SHORT = "ac"; private static final String JSON_KEY_PROVIDER = "provider"; private static final String JSON_KEY_PROVIDER_SHORT = "pr"; private static final String JSON_KEY_TIMESTAMP = "timestamp"; private static final String JSON_KEY_TIMESTAMP_SHORT = "ts"; private final Double latitude; private final Double longitude; private final Double accuracy; private final String provider; private final Date timestamp; /** * Creates a new Location object. * * @param locationData A JSONObject representing all of the data for a * Location object. * * @throws MobilityException Thrown if the location data is null, isn't * a valid JSONObject, doesn't contain all of * the required information, or any of the * information is invalid for its type. */ private Location(JSONObject locationData) throws MobilityException { try { latitude = locationData.getDouble(JSON_KEY_LATITUDE); } catch(JSONException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_LOCATION, "The latitude is missing or invalid.", e); } try { longitude = locationData.getDouble(JSON_KEY_LONGITUDE); } catch(JSONException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_LOCATION, "The longitude is missing or invalid.", e); } try { accuracy = locationData.getDouble(JSON_KEY_ACCURACY); } catch(JSONException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_LOCATION, "The accuracy is missing or invalid.", e); } try { provider = locationData.getString(JSON_KEY_PROVIDER); } catch(JSONException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_LOCATION, "The provider is missing.", e); } try { timestamp = StringUtils.decodeDateTime(locationData.getString(JSON_KEY_TIMESTAMP)); if(timestamp == null) { throw new MobilityException(ErrorCodes.SERVER_INVALID_TIMESTAMP, "The timestamp is invalid."); } } catch(JSONException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_TIMESTAMP, "The timestamp is missing.", e); } } /** * Returns the latitude of this location. * * @return The latitude of this location. */ public final double getLatitude() { return latitude; } /** * Returns the longitude of this location. * * @return The longitude of this location. */ public final double getLongitude() { return longitude; } /** * Returns the accuracy of this location. * * @return The accuracy of this location. */ public final double getAccuracy() { return accuracy; } /** * Returns the provider of this location information. * * @return The provider of this location information. */ public final String getProvider() { return provider; } /** * Returns the timestamp for when this information was gathered. * * @return The timestamp for when this information was gathered. */ public final Date getTimestamp() { return timestamp; } /** * Creates a JSONObject that represents the information in this object. * * @param abbreviated Whether or not the keys should use their * abbreviated version. * * @return Returns a JSONObject that represents this object or null if * there is an error building the JSONObject. */ public final JSONObject toJson(final boolean abbreviated) { try { JSONObject result = new JSONObject(); result.put(((abbreviated) ? JSON_KEY_LATITUDE_SHORT : JSON_KEY_LATITUDE), latitude); result.put(((abbreviated) ? JSON_KEY_LONGITUDE_SHORT : JSON_KEY_LONGITUDE), longitude); result.put(((abbreviated) ? JSON_KEY_ACCURACY_SHORT : JSON_KEY_ACCURACY), accuracy); result.put(((abbreviated) ? JSON_KEY_PROVIDER_SHORT : JSON_KEY_PROVIDER), provider); result.put(((abbreviated) ? JSON_KEY_TIMESTAMP_SHORT : JSON_KEY_TIMESTAMP), TimeUtils.getIso8601DateTimeString(timestamp)); return result; } catch(JSONException e) { return null; } } } private final Location location; public static enum SubType { MODE_ONLY, SENSOR_DATA }; private final SubType subType; public static enum Mode { STILL, WALK, RUN, BIKE, DRIVE }; // Mode-only private final Mode mode; // Sensor data /** * This class is responsible for managing the sensor data in a single * Mobility entry. * * @author John Jenkins */ public final class SensorData { private static final String JSON_KEY_MODE = "mode"; private static final String JSON_KEY_SPEED = "speed"; private static final String JSON_KEY_ACCEL_DATA = "accel_data"; private static final String JSON_KEY_ACCEL_DATA_X = "x"; private static final String JSON_KEY_ACCEL_DATA_Y = "y"; private static final String JSON_KEY_ACCEL_DATA_Z = "z"; private static final String JSON_KEY_WIFI_DATA = "wifi_data"; private static final String JSON_KEY_WIFI_DATA_TIMESTAMP = "timestamp"; private static final String JSON_KEY_WIFI_DATA_SCAN = "scan"; private final Mode mode; private final Double speed; /** * This class is responsible for managing tri-axle acceleration data * points. * * @author John Jenkins */ public final class AccelData { private final Double x; private final Double y; private final Double z; /** * Creates a tri-axle acceleration data point. * * @param x The x-acceleration of the point. * * @param y The y-acceleration of the point. * * @param z The z-acceleration of the point. */ private AccelData(Double x, Double y, Double z) { this.x = x; this.y = y; this.z = z; } /** * Returns the x-acceleration of the data point. * * @return The x-acceleration of the data point. */ public final Double getX() { return x; } /** * Returns the y-acceleration of the data point. * * @return The y-acceleration of the data point. */ public final Double getY() { return y; } /** * Returns the z-acceleration of the data point. * * @return The z-acceleration of the data point. */ public final Double getZ() { return z; } /** * Creates a JSONObject from the information in this object. * * @return Returns a JSONObject representing this object unless * there is an error in which case null is returned. */ public final JSONObject toJson() { try { JSONObject result = new JSONObject(); result.put(JSON_KEY_ACCEL_DATA_X, x); result.put(JSON_KEY_ACCEL_DATA_Y, y); result.put(JSON_KEY_ACCEL_DATA_Z, z); return result; } catch(JSONException e) { return null; } } } private final List<AccelData> accelData; /** * This class is responsible for the WifiData in a sensor data upload. * * @author John Jenkins */ public final class WifiData { private static final String JSON_KEY_SSID = "ssid"; private static final String JSON_KEY_STRENGTH = "strength"; private final Date timestamp; private final Map<String, Double> scan; /** * Creates a WifiData point with a timestamp and all of the scan * information. * * @param timestamp A String representing the date and time that * this record was made. * * @param scan The data collected from all of the WiFi points in * range of the scan. * * @throws MobilityException Thrown if either of the parameters are * null or invalid values. */ private WifiData(String timestamp, JSONArray scan) throws MobilityException { // Validate the timestamp value. if(timestamp == null) { throw new MobilityException(ErrorCodes.SERVER_INVALID_TIMESTAMP, "The timestamp is missing."); } else if((this.timestamp = StringUtils.decodeDate(timestamp)) == null) { throw new MobilityException(ErrorCodes.SERVER_INVALID_TIMESTAMP, "The timestamp is invalid."); } // Validate the scan value. // Create the local scan map. this.scan = new HashMap<String, Double>(); // For each of the entries in the array, parse out the // necessary information. int numScans = scan.length(); for(int i = 0; i < numScans; i++) { try { JSONObject jsonObject = scan.getJSONObject(i); // Get the SSID. String ssid; try { ssid = jsonObject.getString(JSON_KEY_SSID); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_WIFI_DATA, "The SSID is missing.", e); } // Get the strength. Double strength; try { strength = jsonObject.getDouble(JSON_KEY_STRENGTH); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_WIFI_DATA, "The strength is missing or invalid.", e); } // Add them to the map. this.scan.put(ssid, strength); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_WIFI_DATA, "The scan is invalid.", e); } } } /** * Returns the timestamp representing when this scan was performed. * * @return The timestamp representing when this scan was performed. */ public final Date getTimestamp() { return timestamp; } /** * Returns an immutable copy of the scan. * * @return An immutable copy of the scan. */ public final Map<String, Double> getScan() { return Collections.unmodifiableMap(scan); } /** * Creates a JSONObject that represents the information in this * object. * * @return Returns a JSONObject that represents this object or null * if there is an error. */ public final JSONObject toJson() { try { JSONObject result = new JSONObject(); result.put(JSON_KEY_WIFI_DATA_TIMESTAMP, TimeUtils.getIso8601DateTimeString(timestamp)); JSONArray scanJson = new JSONArray(); for(String ssid : scan.keySet()) { JSONObject currScan = new JSONObject(); currScan.put(JSON_KEY_SSID, ssid); currScan.put(JSON_KEY_STRENGTH, scan.get(ssid)); scanJson.put(currScan); } result.put(JSON_KEY_WIFI_DATA_SCAN, scanJson); return result; } catch(JSONException e) { return null; } } } private final WifiData wifiData; /** * Creates a new SensorData point from a JSONObject of sensor data. * * @param sensorData The sensor data as a JSONObject. * * @throws MobilityException Thrown if the sensor data is null, not * valid sensor data, or missing some * component. */ private SensorData(JSONObject sensorData) throws MobilityException { // Get the mode. try { mode = Mode.valueOf(sensorData.getString(JSON_KEY_MODE).toUpperCase()); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_MODE, "The mode is missing.", e); } catch(IllegalArgumentException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_MODE, "The mode is not a known mode.", e); } // Get the speed. try { speed = sensorData.getDouble(JSON_KEY_SPEED); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_SPEED, "The speed is missing or invalid.", e); } // Get the accelerometer data. try { JSONArray accelDataJson = sensorData.getJSONArray(JSON_KEY_ACCEL_DATA); int numAccelDataPoints = accelDataJson.length(); // Create the resulting list and cycle through the // JSONArray adding each of the entries. accelData = new ArrayList<AccelData>(numAccelDataPoints); for(int i = 0; i < numAccelDataPoints; i++) { try { JSONObject accelDataPointJson = accelDataJson.getJSONObject(i); // Get the x-acceleration. Double x; try { x = accelDataPointJson.getDouble(JSON_KEY_ACCEL_DATA_X); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_ACCELEROMETER_DATA, "The 'x' point was missing or invalid.", e); } // Get the y-acceleration. Double y; try { y = accelDataPointJson.getDouble(JSON_KEY_ACCEL_DATA_Y); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_ACCELEROMETER_DATA, "The 'y' point was missing or invalid.", e); } // Get the z-acceleration. Double z; try { z = accelDataPointJson.getDouble(JSON_KEY_ACCEL_DATA_Z); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_ACCELEROMETER_DATA, "The 'z' point was missing or invalid.", e); } // Add a new point. accelData.add(new AccelData(x, y, z)); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_ACCELEROMETER_DATA, "An accelerometer data point is not a JSONObject.", e); } } } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_ACCELEROMETER_DATA, "The accelerometer data is missing or invalid.", e); } // Get the WiFi data. try { JSONObject wifiDataJson = sensorData.getJSONObject(JSON_KEY_WIFI_DATA); // Get the timestamp. String timestamp; try { timestamp = wifiDataJson.getString(JSON_KEY_WIFI_DATA_TIMESTAMP); } catch(JSONException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_TIMESTAMP, "The timestamp is missing.", e); } // Get the scan. JSONArray scan; try { scan = wifiDataJson.getJSONArray(JSON_KEY_WIFI_DATA_SCAN); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_WIFI_DATA, "The scan is missing.", e); } // Set the WifiData. wifiData = new WifiData(timestamp, scan); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_WIFI_DATA, "The WiFi data is missing or invalid.", e); } } /** * Returns the Mode for this record. * * @return The record's mode. */ public final Mode getMode() { return mode; } /** * Returns the speed for this record. * * @return The record's speed. */ public final Double getSpeed() { return speed; } /** * Returns all of the AccelData points for this record. * * @return All of the record's AccelData points. */ public final List<AccelData> getAccelData() { return accelData; } /** * Returns the WifiData from this record. * * @return The record's WifiData. */ public final WifiData getWifiData() { return wifiData; } /** * Creates a JSONObject that represents the information in this object. * * @return Returns a JSONObject that represents this object or null if * there is an error. */ public final JSONObject toJson() { try { JSONObject result = new JSONObject(); result.put(JSON_KEY_MODE, mode.name().toLowerCase()); if(speed == null) { // Don't put it in the JSON } else if(speed.isInfinite()) { if(Double.POSITIVE_INFINITY == speed.doubleValue()) { result.put(JSON_KEY_SPEED, "Infinity"); } else { result.put(JSON_KEY_SPEED, "-Infinity"); } } else if(speed.isNaN()) { result.put(JSON_KEY_SPEED, "NaN"); } else { result.put(JSON_KEY_SPEED, speed); } result.put(JSON_KEY_WIFI_DATA, wifiData.toJson()); JSONArray accelArray = new JSONArray(); for(AccelData accelRecord : accelData) { accelArray.put(accelRecord.toJson()); } result.put(JSON_KEY_ACCEL_DATA, accelArray); return result; } catch(JSONException e) { System.out.println("Failed to create the JSON." + e.toString()); return null; } } } private final SensorData sensorData; /** * This is the classification information computed by the server's * classifier. * * @author John Jenkins */ public final class ClassifierData { private static final String JSON_KEY_FFT = "fft"; private static final String JSON_KEY_VARIANCE = "variance"; //private static final String JSON_KEY_N95_FFT = "N95Fft"; private static final String JSON_KEY_N95_VARIANCE = "N95Variance"; private static final String JSON_KEY_AVERAGE = "average"; private static final String JSON_KEY_MODE = "mode"; private final List<Double> fft; private final Double variance; // This is no longer being collected, but it is being left here as a // reminder in case it is added again. //private final List<Double> n95Fft; private final Double n95Variance; private final Double average; private final Mode mode; /** * Creates a ClassifierData object that only contains a mode. * * @param mode The Mode from the server-side classifier. */ private ClassifierData(Mode mode) { if(mode == null) { throw new IllegalArgumentException("The mode cannot be null."); } this.fft = null; this.variance = null; this.n95Variance = null; this.average = null; this.mode = mode; } /** * Creates a ClassifierData object that contains all of the applicable * keys from the JSONObject. The only required key is the mode. * * @param classifierData The classifier data as a JSONObject. * * @throws MobilityException Thrown if the mode is missing or unknown. */ private ClassifierData(JSONObject classifierData) throws MobilityException{ try { mode = Mode.valueOf(classifierData.getString(JSON_KEY_MODE).toUpperCase()); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_MODE, "The mode is missing.", e); } catch(IllegalArgumentException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_MODE, "The mode is unknown.", e); } List<Double> tFft = null; try { JSONArray fftArray = classifierData.getJSONArray(JSON_KEY_FFT); int numEntries = fftArray.length(); tFft = new ArrayList<Double>(numEntries); for(int i = 0; i < numEntries; i++) { tFft.add(fftArray.getDouble(i)); } } catch(JSONException e) { // If it is missing we don't care. It may be that only the mode // could be calculated. } fft = tFft; Double tVariance = null; try { tVariance = classifierData.getDouble(JSON_KEY_VARIANCE); } catch(JSONException e) { // If it is missing we don't care. It may be that only the mode // could be calculated. } variance = tVariance; Double tN95Variance = null; try { tN95Variance = classifierData.getDouble(JSON_KEY_N95_VARIANCE); } catch(JSONException e) { // If it is missing we don't care. It may be that only the mode // could be calculated. } n95Variance = tN95Variance; Double tAverage = null; try { tAverage = classifierData.getDouble(JSON_KEY_AVERAGE); } catch(JSONException e) { // If it is missing we don't care. It may be that only the mode // could be calculated. } average = tAverage; } private ClassifierData(List<Double> fft, Double variance, Double n95Variance, Double average, Mode mode) { if(mode == null) { throw new IllegalArgumentException("The mode cannot be null."); } this.fft = fft; this.variance = variance; this.n95Variance = n95Variance; this.average = average; this.mode = mode; } /** * Returns the FFT array. * * @return The FFT array. May be null. */ public final List<Double> getFft() { return fft; } /** * Returns the variance. * * @return The variance. May be null. */ public final Double getVariance() { return variance; } /** * Returns the N95 variance. * * @return The N95 variance. May be null. */ public final Double getN95Variance() { return n95Variance; } /** * Returns the average. * * @return The average. May be null. */ public final Double getAverage() { return average; } /** * Returns the Mode from this classification. * * @return The Mode from this classification. */ public final Mode getMode() { return mode; } /** * Creates a JSONObject that represents the information contained in * this object. * * @return A JSONObject representing this object or null if there is an * error. */ public final JSONObject toJson() { try { JSONObject result = new JSONObject(); result.put(JSON_KEY_FFT, fft); result.put(JSON_KEY_VARIANCE, variance); result.put(JSON_KEY_N95_VARIANCE, n95Variance); result.put(JSON_KEY_AVERAGE, average); result.put(JSON_KEY_MODE, mode.name().toLowerCase()); return result; } catch(JSONException e) { System.out.println("Failed to create the JSON." + e.toString()); return null; } } } private ClassifierData classifierData; /** * This is an exception explicitly for creating a Mobility point from a * JSONObject. This allows for a central place for creating and validating * Mobility uploads and allows them to throw error codes and texts which * can be caught by validators to report back to the user. * * @author John Jenkins */ public final class MobilityException extends Exception { private static final long serialVersionUID = 1L; private final String errorCode; private final String errorText; /** * Creates a new Mobility exception that contains an error code which * corresponds to the error text describing what was wrong with this * Mobility point. * * @param errorCode The ErrorCode indicating what was wrong with this * Mobility point. * * @param errorText A human-readable description of what caused this * error. */ private MobilityException(String errorCode, String errorText) { super(errorText); this.errorCode = errorCode; this.errorText = errorText; } /** * Creates a new Mobility exception that contains an error code which * corresponds to the error text describing what was wrong with this * Mobility point and includes the Throwable that caused this * exception. * * @param errorCode The ErrorCode indicating what was wrong with this * Mobility point. * * @param errorText A human-readable description of what cuased this * error. * * @param cause The Throwable that caused this point to be reached. */ private MobilityException(String errorCode, String errorText, Throwable cause) { super(errorText, cause); this.errorCode = errorCode; this.errorText = errorText; } /** * Returns the error code that was used to create this exception. * * @return The error code that was used to create this exception. */ public final String getErrorCode() { return errorCode; } /** * Returns the error text that was used to create this exception. * * @return The error text that was used to create this exception. */ public final String getErrorText() { return errorText; } } /** * Creates a MobilityInformation object that represents all of the * information in the parameterized Mobility data point. * * @param mobilityPoint A JSONObject that contains all of the required * information for a Mobility data point. * * @throws MobilityException Thrown if Mobility point is null, invalid, or * contains insufficient information to build * this object. */ public MobilityInformation(JSONObject mobilityPoint, MobilityPrivacyStateCache.PrivacyState privacyState) throws MobilityException { // Get the date. try { date = StringUtils.decodeDateTime(mobilityPoint.getString(JSON_KEY_DATE)); if(date == null) { throw new MobilityException(ErrorCodes.SERVER_INVALID_TIMESTAMP, "The date is invalid."); } } catch(JSONException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_TIMESTAMP, "The date is missing.", e); } // Get the time. try { time = mobilityPoint.getLong(JSON_KEY_TIME); } catch(JSONException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_TIME, "The time is missing.", e); } // Get the timezone. // FIXME: This doesn't validate the timezone and instead just defaults // to GMT. try { timezone = TimeZone.getTimeZone(mobilityPoint.getString(JSON_KEY_TIMEZONE)); } catch(JSONException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_TIMEZONE, "The timezone is missing.", e); } // Get the location status. try { locationStatus = LocationStatus.valueOf(mobilityPoint.getString(JSON_KEY_LOCATION_STATUS).toUpperCase()); } catch(JSONException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_LOCATION_STATUS, "The location status is missing.", e); } catch(IllegalArgumentException e) { throw new MobilityException(ErrorCodes.SERVER_INVALID_LOCATION_STATUS, "The location status is unknown.", e); } // Get the location. Location tLocation; try { tLocation = new Location(mobilityPoint.getJSONObject(JSON_KEY_LOCATION)); } catch(JSONException e) { // If there was no location information in the JSONObject, check to // ensure that the location status was unavailable as that is the // only time this is acceptable. if(LocationStatus.UNAVAILABLE.equals(locationStatus)) { tLocation = null; } else { throw new MobilityException(ErrorCodes.SERVER_INVALID_LOCATION, "The location is missing.", e); } } location = tLocation; // Get the subtype. try { subType = SubType.valueOf(mobilityPoint.getString(JSON_KEY_SUBTYPE).toUpperCase()); } catch(JSONException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_SUBTYPE, "The subtype is missing.", e); } catch(IllegalArgumentException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_SUBTYPE, "The subtype is an unknown type.", e); } // Based on the subtype, get the mode or sensor data. switch(subType) { case MODE_ONLY: try { mode = Mode.valueOf(mobilityPoint.getString(JSON_KEY_MODE).toUpperCase()); sensorData = null; } catch(JSONException e) { throw new MobilityException( ErrorCodes.MOBILITY_INVALID_MODE, "The subtype is '" + SubType.MODE_ONLY.toString().toLowerCase() + "', but the required key is missing: " + JSON_KEY_MODE, e); } catch(IllegalArgumentException e) { throw new MobilityException(ErrorCodes.MOBILITY_INVALID_MODE, "The mode is unknown.", e); } break; case SENSOR_DATA: try { sensorData = new SensorData(mobilityPoint.getJSONObject(JSON_KEY_DATA)); mode = sensorData.mode; } catch(JSONException e) { throw new MobilityException( ErrorCodes.SERVER_INVALID_JSON, "The subtype is '" + SubType.SENSOR_DATA.toString().toLowerCase() + "', but the required key is missing: " + JSON_KEY_DATA, e); } break; default: // If we accepted the subtype then we must know what it is, but we // may not need to look for any further data based on that subtype. mode = null; sensorData = null; } // Set the server's classification to null. classifierData = null; this.privacyState = privacyState; } public MobilityInformation(Date date, Long time, TimeZone timezone, LocationStatus locationStatus, JSONObject location, Mode mode, MobilityPrivacyStateCache.PrivacyState privacyState, JSONObject sensorData, JSONObject features, String classifierVersion) throws MobilityException{ if(date == null) { throw new IllegalArgumentException("The date cannot be null."); } else { this.date = date; } if(time == null) { throw new IllegalArgumentException("The time cannot be null."); } else { this.time = time; } if(timezone == null) { throw new IllegalArgumentException("The timezone cannot be null."); } else { this.timezone = timezone; } if(locationStatus == null) { throw new IllegalArgumentException("The location status cannot be null."); } else { this.locationStatus = locationStatus; } if(location == null) { this.location = null; } else { this.location = new Location(location); } if(mode == null) { throw new IllegalArgumentException("The mode cannot be null."); } else { this.mode = mode; } if(privacyState == null) { throw new IllegalArgumentException("The privacy state cannot be null."); } else { this.privacyState = privacyState; } if((sensorData == null) && (features == null) && (classifierVersion == null)) { subType = SubType.MODE_ONLY; this.sensorData = null; this.classifierData = null; } else { subType = SubType.SENSOR_DATA; this.sensorData = new SensorData(sensorData); this.classifierData = new ClassifierData(features); } } /** * Returns the date and time this Mobility point was created. * * @return The date and time this Mobility point was created. */ public final Date getDate() { return date; } /** * Returns the number of milliseconds since the epoch when this Mobility * point was created. * * @return The number of milliseconds since the epoch when this Mobility * point was created. */ public final long getTime() { return time; } /** * Returns the phone's timezone when this Mobility point was created. * * @return The phone's timezone when this Mobility point was created. */ public final TimeZone getTimezone() { return timezone; } /** * Returns the Mobility point's privacy state. * * @return The Mobility point's privacy state. */ public final MobilityPrivacyStateCache.PrivacyState getPrivacyState() { return privacyState; } /** * Returns the status of the location value obtained when this Mobility * point was created. * * @return The status of the location value obtained when this Mobility * point was created. * * @see #getLocation() */ public final LocationStatus getLocationStatus() { return locationStatus; } /** * Returns a Location object representing the information collected about * the phone's location when this Mobility point was created. * * @return A Location object representing the information collected about * the phone's location when this Mobility point was created. * * @see #getLocationStatus() */ public final Location getLocation() { return location; } /** * Returns the SubType of this Mobility reading which dictates whether the * mode or the sensor data is valid. * * @return The SubType of this Mobility reading which dictates whether the * mode or the sensor data is valid. * * @see SubType * @see #getMode() * @see #getSensorData() */ public final SubType getSubType() { return subType; } /** * This is the Mode that was calculated when this Mobility point was made. * * @return The Mode that was calculated when this Mobility point was made. */ public final Mode getMode() { return mode; } /** * Returns the additional sensor data that was recorded when this Mobility * point was made. This will be null if the {@link #getSubType()} is not * {@value SubType#SENSOR_DATA}. * * @return The additional sensor data that was recorded when this Mobility * point was made or null if {@link #getSubType()} does not return * {@value SubType#SENSOR_DATA}. */ public final SensorData getSensorData() { return sensorData; } /** * Returns the list of Samples from this Mobility point if it is of type * {@value SubType#SENSOR_DATA}; otherwise, null is returned. * * @return A list of Samples from this Mobility point if it is of type * {@value SubType#SENSOR_DATA}, which may be empty but will never * be null; otherwise, null is returned. */ public final List<Sample> getSamples() { if(! SubType.SENSOR_DATA.equals(subType)) { return null; } List<Sample> result = new ArrayList<Sample>(sensorData.accelData.size()); for(AccelData dataPoint : sensorData.accelData) { Sample sample = new Sample(); sample.setX(dataPoint.getX()); sample.setY(dataPoint.getY()); sample.setZ(dataPoint.getZ()); result.add(sample); } return result; } public final void setClassifierData(List<Double> fft, Double variance, Double n95Variance, Double average, Mode mode) { classifierData = new ClassifierData(fft, variance, n95Variance, average, mode); } /** * Sets this Mobility point's classifier data from the server's classifier, * but it only sets the mode. * * @param mode The mode that the classifier generated. */ public final void setClassifierModeOnly(Mode mode) { classifierData = new ClassifierData(mode); } /** * Returns the classifier data that was generated by the server's * classifier. * * @return The classifier data that was generated by the server's * classifier or null if nothing has been set yet. */ public final ClassifierData getClassifierData() { return classifierData; } /** * Outputs this Mobility point as a JSONObject. * * @param abbreviated Whether or not to use the abbreviated versions of the * JSON keys. * * @return A JSONObject that represents this Mobility point. */ public final JSONObject toJson(final boolean abbreviated) { try { JSONObject result = new JSONObject(); result.put(((abbreviated) ? JSON_KEY_MODE_SHORT : JSON_KEY_MODE), mode.toString().toLowerCase()); result.put(((abbreviated) ? JSON_KEY_DATE_SHORT : JSON_KEY_DATE), TimeUtils.getIso8601DateTimeString(date)); result.put(((abbreviated) ? JSON_KEY_TIMEZONE_SHORT : JSON_KEY_TIMEZONE), timezone.getID()); result.put(((abbreviated) ? JSON_KEY_LOCATION_STATUS_SHORT : JSON_KEY_LOCATION_STATUS), locationStatus.toString().toLowerCase()); if(location != null) { result.put(((abbreviated) ? JSON_KEY_LOCATION_SHORT : JSON_KEY_LOCATION), location.toJson(abbreviated)); } return result; } catch(JSONException e) { return null; } } }
package org.pentaho.di.job.entry; import java.util.List; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.Const; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.changed.ChangedFlagInterface; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepLoaderException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.gui.GUIPositionInterface; import org.pentaho.di.core.gui.Point; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.core.xml.XMLInterface; import org.pentaho.di.job.JobEntryLoader; import org.pentaho.di.job.JobEntryType; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.JobPlugin; import org.pentaho.di.repository.Repository; import org.w3c.dom.Node; /** * This class describes the fact that a single JobEntry can be used multiple * times in the same Job. Therefor it contains a link to a JobEntry, a position, * a number, etc. * * @author Matt * @since 01-10-2003 * */ public class JobEntryCopy implements Cloneable, XMLInterface, GUIPositionInterface, ChangedFlagInterface { private JobEntryInterface entry; private int nr; // Copy nr. 0 is the base copy... private boolean selected; private Point location; private boolean parallel; private boolean draw; private long id; public JobEntryCopy() { clear(); } /** * @deprecated Log is no longer required. * @param log */ public JobEntryCopy(LogWriter log) { clear(); } public JobEntryCopy(LogWriter log, JobEntryInterface entry) { setEntry(entry); } public String getXML() { StringBuffer retval = new StringBuffer(); retval.append(" <entry>").append(Const.CR); retval.append(entry.getXML()); retval.append(" ").append(XMLHandler.addTagValue("parallel", parallel)); retval.append(" ").append(XMLHandler.addTagValue("draw", draw)); retval.append(" ").append(XMLHandler.addTagValue("nr", nr)); retval.append(" ").append(XMLHandler.addTagValue("xloc", location.x)); retval.append(" ").append(XMLHandler.addTagValue("yloc", location.y)); retval.append(" </entry>").append(Const.CR); return retval.toString(); } public JobEntryCopy(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException { try { String stype = XMLHandler.getTagValue(entrynode, "type"); JobPlugin jobPlugin = JobEntryLoader.getInstance().findJobEntriesWithID(stype); if (jobPlugin == null) throw new KettleStepLoaderException("No valid step/plugin specified (jobPlugin=null) for " + stype); // Get an empty JobEntry of the appropriate class... entry = JobEntryLoader.getInstance().getJobEntryClass(jobPlugin); if (entry != null) { // System.out.println("New JobEntryInterface built of type: // "+entry.getTypeDesc()); entry.loadXML(entrynode, databases, slaveServers, rep); // Handle GUI information: nr & location? setNr(Const.toInt(XMLHandler.getTagValue(entrynode, "nr"), 0)); setParallel("Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "parallel"))); setDrawn("Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "draw"))); int x = Const.toInt(XMLHandler.getTagValue(entrynode, "xloc"), 0); int y = Const.toInt(XMLHandler.getTagValue(entrynode, "yloc"), 0); setLocation(x, y); } } catch (Throwable e) { String message = "Unable to read Job Entry copy info from XML node : " + e.toString(); LogWriter log = LogWriter.getInstance(); log.logError(toString(), message); log.logError(toString(), Const.getStackTracker(e)); throw new KettleXMLException(message, e); } } /** * Load the chef graphical entry from repository We load type, name & * description if no entry can be found. * * @param log * the logging channel * @param rep * the Repository * @param id_job * The job ID * @param id_jobentry_copy * The jobentry copy ID * @param jobentries * A list with all jobentries * @param databases * A list with all defined databases */ public JobEntryCopy(LogWriter log, Repository rep, long id_job, long id_jobentry_copy, List<JobEntryInterface> jobentries, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException { try { setID(id_jobentry_copy); // Handle GUI information: nr, location, ... RowMetaAndData r = rep.getJobEntryCopy(id_jobentry_copy); if (r != null) { // These are the jobentry_copy fields... // System.out.println("JobEntryCopy = "+r); long id_jobentry = r.getInteger("ID_JOBENTRY", 0); long id_jobentry_type = r.getInteger("ID_JOBENTRY_TYPE", 0); setNr((int) r.getInteger("NR", 0)); int locx = (int) r.getInteger("GUI_LOCATION_X", 0); int locy = (int) r.getInteger("GUI_LOCATION_Y", 0); boolean isdrawn = r.getBoolean("GUI_DRAW", false); boolean isparallel = r.getBoolean("PARALLEL", false); // Do we have the jobentry already? entry = JobMeta.findJobEntry(jobentries, id_jobentry); if (entry == null) { // What type of jobentry do we load now? // Get the jobentry type code RowMetaAndData rt = rep.getJobEntryType(id_jobentry_type); if (rt != null) { String jet_code = rt.getString("CODE", null); JobEntryLoader jobLoader = JobEntryLoader.getInstance(); JobPlugin jobPlugin = jobLoader.findJobEntriesWithID(jet_code); if (jobPlugin != null) { entry = jobLoader.getJobEntryClass(jobPlugin); // Load the attributes for that jobentry entry.loadRep(rep, id_jobentry, databases, slaveServers); entry.setID(id_jobentry); jobentries.add(entry); } else { throw new KettleException( "JobEntryLoader was unable to find Job Entry Plugin with description [" + jet_code + "]."); } } else { throw new KettleException("Unable to find Job Entry Type with id=" + id_jobentry_type + " in the repository"); } } setLocation(locx, locy); setDrawn(isdrawn); setParallel(isparallel); } } catch (KettleDatabaseException dbe) { throw new KettleException("Unable to load job entry copy from repository with id_jobentry_copy=" + id_jobentry_copy, dbe); } } public void saveRep(Repository rep, long id_job) throws KettleException { try { /* * --1-- Save the JobEntryCopy details... --2-- If we don't find a * id_jobentry, save the jobentry (meaning: only once) */ // See if an entry with the same name is already available... long id_jobentry = rep.getJobEntryID(getName(), id_job); if (id_jobentry <= 0) { entry.saveRep(rep, id_job); id_jobentry = entry.getID(); } // OK, the entry is saved. // Get the entry type... long id_jobentry_type = rep.getJobEntryTypeID(entry.getTypeCode()); // Oops, not found: update the repository! if (id_jobentry_type < 0) { rep.updateJobEntryTypes(); // Try again! id_jobentry_type = rep.getJobEntryTypeID(entry.getTypeCode()); } // Save the entry copy.. setID(rep.insertJobEntryCopy(id_job, id_jobentry, id_jobentry_type, getNr(), getLocation().x, getLocation().y, isDrawn(), isParallel())); } catch (KettleDatabaseException dbe) { throw new KettleException("Unable to save job entry copy to the repository, id_job=" + id_job, dbe); } } public void clear() { location = null; entry = null; nr = 0; parallel = false; setID(-1L); } public Object clone() { JobEntryCopy ge = new JobEntryCopy(); ge.replaceMeta(this); ge.setID(-1L); return ge; } public void replaceMeta(JobEntryCopy jobEntryCopy) { entry = jobEntryCopy.entry; nr = jobEntryCopy.nr; // Copy nr. 0 is the base copy... selected = jobEntryCopy.selected; if (jobEntryCopy.location != null) location = new Point(jobEntryCopy.location.x, jobEntryCopy.location.y); parallel = jobEntryCopy.parallel; draw = jobEntryCopy.draw; id = jobEntryCopy.id; } public Object clone_deep() { JobEntryCopy ge = (JobEntryCopy) clone(); // Copy underlying object as well... ge.entry = (JobEntryInterface) entry.clone(); return ge; } public void setID(long id) { this.id = id; } public boolean equals(Object o) { if (o == null) return false; JobEntryCopy je = (JobEntryCopy) o; return je.entry.getName().equalsIgnoreCase(entry.getName()) && je.getNr() == getNr(); } public long getID() { return id; } public void setEntry(JobEntryInterface je) { entry = je; if (entry!=null) { if (entry.getConfigId()==null) { entry.setConfigId( JobEntryLoader.getInstance().getJobEntryID(entry) ); } } } public JobEntryInterface getEntry() { return entry; } public JobEntryType getJobEntryType() { return entry.getJobEntryType(); } /** * @return entry in JobEntryInterface.typeCode[] for native jobs, * entry.getTypeCode() for plugins */ public String getTypeDesc() { if (getJobEntryType() == JobEntryType.NONE) return entry.getTypeCode(); return getTypeDesc(entry); } public void setLocation(int x, int y) { int nx = (x >= 0 ? x : 0); int ny = (y >= 0 ? y : 0); Point loc = new Point(nx, ny); if (!loc.equals(location)) setChanged(); location = loc; } public void setLocation(Point loc) { if (loc != null && !loc.equals(location)) setChanged(); location = loc; } public Point getLocation() { return location; } public void setChanged() { setChanged(true); } public void setChanged(boolean ch) { entry.setChanged(ch); } public boolean hasChanged() { return entry.hasChanged(); } public int getNr() { return nr; } public void setNr(int n) { nr = n; } public void setParallel() { setParallel(true); } public void setParallel(boolean p) { parallel = p; } public boolean isDrawn() { return draw; } public void setDrawn() { setDrawn(true); } public void setDrawn(boolean d) { draw = d; } public boolean isParallel() { return parallel; } public static final JobEntryType getType(String dsc) { if (dsc != null) { JobEntryType[] types = JobEntryType.values(); for (JobEntryType type : types) { if (type.getTypeCode().equalsIgnoreCase(dsc)) return type; } // Try the long description! for (JobEntryType type : types) { if (type.getDescription().equalsIgnoreCase(dsc)) return type; } } return JobEntryType.NONE; } public static final String getTypeDesc(int ty) { if (ty > 0 && ty < JobEntryType.values().length) return JobEntryType.values()[ty].toString(); return JobEntryType.NONE.toString(); } public static final String getTypeDesc(JobEntryInterface ty) { return ty.getJobEntryType().toString(); } public void setSelected(boolean sel) { selected = sel; } public void flipSelected() { selected = !selected; } public boolean isSelected() { return selected; } public void setDescription(String description) { entry.setDescription(description); } public String getDescription() { return entry.getDescription(); } public boolean isStart() { return entry.isStart(); } public boolean isDummy() { return entry.isDummy(); } public boolean isTransformation() { return getJobEntryType() == JobEntryType.TRANS; } public boolean isJob() { return getJobEntryType() == JobEntryType.JOB; } public boolean evaluates() { if (entry != null) return entry.evaluates(); return false; } public boolean isUnconditional() { if (entry != null) return entry.isUnconditional(); return true; } public boolean isEvaluation() { return getJobEntryType() == JobEntryType.EVAL; } public boolean isMail() { return getJobEntryType() == JobEntryType.MAIL; } public boolean isSQL() { return getJobEntryType() == JobEntryType.MAIL; } public boolean isSpecial() { return getJobEntryType() == JobEntryType.SPECIAL; } public String toString() { if( entry != null ) { return entry.getName() + "." + getNr(); } else { return "null."+getNr(); } } public String getName() { if( entry != null ) { return entry.getName(); } else { return "null"; } } public void setName(String name) { entry.setName(name); } public boolean resetErrorsBeforeExecution() { return entry.resetErrorsBeforeExecution(); } }
package org.subethamail.core.util; import java.util.logging.Level; import lombok.extern.java.Log; /** * Class which abstracts the handling of VERP bounces. This can * separate the VERP token from the original address. It can * also assemble an address from an email and a token. * * A VERP'd address looks like: * * announce-verp-THISISTHETOKEN-bounce@domain.com * * The extracted email will be announce@domain.com. * * Note that the token is a lowercase hex-encoded string. * This is because some evil MTAs (Postfix grrr) force * the mailbox part of an address to lowercase, screwing * up any attempt at base64 encoding. * * @author Jeff Schnitzer */ @Log public class VERPAddress { /** This is the suffix of all VERP'd addresses, plus the '@' */ public static final String SUFFIX = "-b@"; /** This preceeds the token in the address */ public static final String LEAD = "-verp-"; String email; String tokenEncoded; VERPAddress(String email, String tokenBase62) { this.email = email; this.tokenEncoded = tokenBase62; } /** * @return the "normal" email address, without the verp information. * This will be the mailing list address that the mail was from. */ public String getEmail() { return this.email; } /** * Lazily decodes the token. * * @return the token that was extracted from the VERP address. */ public byte[] getToken() { return Base62.decode(this.tokenEncoded); } /** * @return The Base62 encoded string. */ public String getRawToken() { return this.tokenEncoded; } /** * @return null if the address was not a VERP'ed address. */ public static VERPAddress getVERPBounce(String addy) { // Note the suffix includes the @ int suffixIndex = addy.indexOf(SUFFIX); if (suffixIndex < 0) return null; int leadIndex = addy.lastIndexOf(LEAD, suffixIndex); if (leadIndex < 0) return null; // Watch out for blah-verp-bounce@foo.bar if (leadIndex + LEAD.length() >= suffixIndex) return null; String email = addy.substring(0, leadIndex) + '@' + addy.substring(suffixIndex+SUFFIX.length()); String tokenBase62 = addy.substring(leadIndex+LEAD.length(), suffixIndex); if (log.isLoggable(Level.FINE)) log.log(Level.FINE,"{0} becomes {1}/{2}", new Object[]{addy,email,tokenBase62}); return new VERPAddress(email, tokenBase62); } /** * @return an email address encoded with the binary token. */ public static String encodeVERP(String email, byte[] token) { int atIndex = email.indexOf('@'); return email.substring(0, atIndex) + LEAD + new String(Base62.encode(token)) + SUFFIX + email.substring(atIndex+1); } }
package uk.ac.brighton.ci360.bigarrow; import java.util.List; import uk.ac.brighton.ci360.bigarrow.places.Place; import uk.ac.brighton.ci360.bigarrow.places.PlaceDetails; import uk.ac.brighton.ci360.bigarrow.places.PlacesList; import android.app.Activity; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapController; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; public class MyMapActivity extends PlaceSearchActivity implements LocationListener, PlaceSearchRequester { protected static final String TAG = null; MapFragment mapView; List<Overlay> mapOverlays; AddItemizedOverlay itemizedOverlay; GeoPoint geoPoint; MapController mc; double latitude; double longitude; OverlayItem overlayitem; private LocationManager locationManager; private Location myLocation; private LatLng myLatLng; private Marker myMarker; private GoogleMap map; private LatLngBounds.Builder llbBuilder; private PlaceSearch pSearch; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); myLocation = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (myLocation == null) { myLocation = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 50, this); /**IF GPS DISABLED myLocation is still null and app will crash**/ myLatLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude()); setUpMapIfNeeded(); map.moveCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, 15)); map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { Log.d(TAG, marker.getTitle()); } }); pSearch = new PlaceSearch(this); SearchEstab e = Prefs.getSearchType(this); pSearch.search(myLocation, new SearchEstab[] { e }, SearchType.MANY); } private void setUpMapIfNeeded() { if (map == null) { map = ((MapFragment) getFragmentManager() .findFragmentById(R.id.map)).getMap(); if (map != null) { // The Map is verified. It is now safe to manipulate the map. } } } @Override public void updateNearestPlace(Place place, Location location, float distance) { // TODO Auto-generated method stub } @Override public void updateNearestPlaces(PlacesList places) { map.clear(); LatLng ll; String marker_label = getResources().getString(R.string.my_marker_label); MarkerOptions mOpt = new MarkerOptions().position(myLatLng).title( marker_label); mOpt.icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_red)); myMarker = map.addMarker(mOpt); BitmapDescriptor bmd = BitmapDescriptorFactory .fromResource(R.drawable.mark_blue); if (places.results != null) { // loop through all the places llbBuilder = new LatLngBounds.Builder(); llbBuilder.include(myLatLng); for (Place place : places.results) { ll = new LatLng(place.geometry.location.lat, place.geometry.location.lng); // longitude Location pub = new Location(""); pub.setLatitude(ll.latitude); pub.setLongitude(ll.longitude); String dist = String.format(" (%.2f%s)", myLocation.distanceTo(pub), " m"); mOpt = new MarkerOptions().position(ll).title(place.name + dist) .icon(bmd); map.addMarker(mOpt); llbBuilder.include(ll); } map.animateCamera(CameraUpdateFactory.newLatLngBounds( llbBuilder.build(), 20)); } myMarker.showInfoWindow(); } @Override public void updatePlaceDetails(PlaceDetails details) { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location location) { myLatLng = new LatLng(location.getLatitude(), location.getLongitude()); SearchEstab e = Prefs.getSearchType(this); //This needs to be done relative to the bounds of the map pSearch.search(myLocation, new SearchEstab[] { e }, SearchType.MANY); } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onResume() { super.onResume(); setUpMapIfNeeded(); } }
package uk.me.graphe.client.dialogs; import uk.me.graphe.client.Graphemeui; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; public class GraphNameDialog extends PopupPanel { private static GraphNameDialog sInstance; private final Graphemeui parent; private final VerticalPanel pnlCont; private final Label lblTitle; private final TextBox txtParam; private boolean isValid; public GraphNameDialog (Graphemeui gui) { this.parent = gui; this.setAnimationEnabled(true); this.setGlassEnabled(true); this.setAutoHideEnabled(true); this.setTitle("Graph name"); this.setStyleName("paramDialog"); lblTitle = new Label("Graph name:"); txtParam = new TextBox(); pnlCont = new VerticalPanel(); pnlCont.add(lblTitle); pnlCont.add(txtParam); isValid = true; txtParam.addKeyDownHandler(new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent arg0) { //TODO: Text validation.....set isValid true or false } }); txtParam.addKeyUpHandler(new KeyUpHandler() { public void onKeyUp(KeyUpEvent e) { if (e.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) { cancel(); } else if (e.getNativeKeyCode() == KeyCodes.KEY_ENTER) { ok(); } else { if (txtParam.getText().trim().length() > 0) { isValid = true; } else { isValid = false; } } } }); super.add(pnlCont); } public static GraphNameDialog getInstance (Graphemeui gui) { if (sInstance == null) sInstance = new GraphNameDialog(gui); return sInstance; } public static GraphNameDialog getInstance () { return sInstance; } private void ok () { if (isValid) { parent.editGraphName(txtParam.getText()); parent.isHotkeysEnabled = true; super.hide(); } } private void cancel () { parent.isHotkeysEnabled = true; super.hide(); } public void show (String initialValue) { parent.isHotkeysEnabled = false; txtParam.setText(initialValue); super.center(); super.show(); txtParam.setFocus(true); } }
package uk.org.cinquin.mutinack.misc_util; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.lang.ref.SoftReference; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import org.nustaq.serialization.FSTConfiguration; import contrib.uk.org.lidalia.slf4jext.Logger; import contrib.uk.org.lidalia.slf4jext.LoggerFactory; public class FileCache<T extends Serializable> { private final static Logger logger = LoggerFactory.getLogger(FileCache.class); private static final FSTConfiguration conf = FSTConfiguration.createFastBinaryConfiguration(); private static final Map<String, SoftReference<Object>> cache = new ConcurrentHashMap<>(); @SuppressWarnings("unchecked") public static <T> T getCached(String path, String cacheExtension, Function<String, T> processor) { String canonicalPath; try { canonicalPath = new File(path + cacheExtension).getCanonicalPath(); } catch (IOException e) { throw new RuntimeException("Error getting canonical path for cache for " + path); } SoftReference<Object> sr = cache.get(canonicalPath); Object o = sr != null ? sr.get() : null; if (o != null) { return (T) o; } T result = getCached0(path, cacheExtension, processor); cache.put(canonicalPath, new SoftReference<Object> (result)); return result; } @SuppressWarnings("unchecked") public static <T> T getCached0(String path, String cacheExtension, Function<String, T> processor) { File cachedInfo; try { cachedInfo = new File(path + cacheExtension).getCanonicalFile(); } catch (IOException e1) { throw new RuntimeException("Error getting canonical path for cache for " + path); } @SuppressWarnings("null") T result = null; boolean recreate = true; if (cachedInfo.exists() && cachedInfo.lastModified() > new File(path).lastModified()) { try (DataInputStream dataIS = new DataInputStream(new FileInputStream(cachedInfo))) { byte [] bytes = new byte [(int) cachedInfo.length()]; dataIS.readFully(bytes); result = (T) conf.asObject(bytes); recreate = false; } catch (IOException e) { logger.debug("Problem reading cache from " + cachedInfo.getAbsolutePath(), e); } } if (recreate) { logger.info("Could not read from cache for " + path); result = processor.apply(path); try (FileOutputStream os = new FileOutputStream(cachedInfo)) { try (FileLock lock = os.getChannel().tryLock()) { if (lock != null) { os.write(conf.asByteArray(result)); } } } catch (OverlappingFileLockException e) { logger.debug("Ignoring concurrent write attempt to cache file"); } catch (IOException e) { logger.debug("Could not save cached data to " + cachedInfo.getAbsolutePath() + "; continuing anyway", e); } } return result; } }
package com.precog.util; import javolution.util.*; import java.lang.UnsupportedOperationException; import java.util.Set; import javax.realtime.MemoryArea; import javolution.context.ObjectFactory; import javolution.lang.MathLib; import javolution.lang.Reusable; /** * <p> This class represents either a table of bits or a set of non-negative * numbers.</p> * * <p> This class is integrated with the collection framework (as * a set of {@link Index indices} and obeys the collection semantic * for methods such as {@link #size} (cardinality) or {@link #equals} * (same set of indices).</p> * * @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a> * @version 5.3, February 24, 2008 */ public class BitSet extends FastCollection <Index> implements Set <Index> , Reusable { /** * Holds the set factory. */ private static final ObjectFactory FACTORY = new ObjectFactory() { public Object create() { return new BitSet(); } }; /** * Holds the bits (64 bits per long). */ private long[] bits; public long[] getBits() { return bits; } public void setBits(long[] arr) { bits = arr; _length = arr.length; } /** * Holds the length in words (long) of this bit set. * Any word at or above the current length should be ignored (assumed * to be zero). */ private int _length; public int getBitsLength() { return _length; } /** * Creates a bit set of small initial capacity. All bits are initially * {@code false}. */ public BitSet() { this(64); } /** * Creates a bit set of specified initial capacity (in bits). * All bits are initially {@code false}. This * constructor reserves enough space to represent the integers * from {@code 0} to {@code bitSize-1}. * * @param bitSize the initial capacity in bits. */ public BitSet(int bitSize) { _length = ((bitSize - 1) >> 6) + 1; bits = new long[_length]; } /** * Creates a bitset given the bits array and length. * * Used internally by copy. */ private BitSet(long[] _bits, int _len) { bits = _bits; _length = _len; } /** * Returns a new, preallocated or {@link #recycle recycled} set instance * (on the stack when executing in a {@link javolution.context.StackContext * StackContext}). * * @return a new, preallocated or recycled set instance. */ public static BitSet newInstance() { BitSet bitSet = (BitSet) FACTORY.object(); bitSet._length = 0; return bitSet; } /** * Recycles a set {@link #newInstance() instance} immediately * (on the stack when executing in a {@link javolution.context.StackContext * StackContext}). */ public static void recycle(BitSet instance) { FACTORY.recycle(instance); } /** * Adds the specified index to this set. This method is equivalent * to <code>set(index.intValue())</code>. * * @param index the integer value to be appended to this set. * @return {@code true} if this set did not contains the specified * index; {@code false} otherwise. */ public boolean add( Index index) { int bitIndex = ((Index) index).intValue(); if (this.get(bitIndex)) return false; // Already there. set(bitIndex); return true; } /** * Performs the logical AND operation on this bit set and the * given bit set. This means it builds the intersection * of the two sets. The result is stored into this bit set. * * @param that the second bit set. */ public void and(BitSet that) { final int n = MathLib.min(this._length, that._length); for (int i = 0; i < n; ++i) { this.bits[i] &= that.bits[i]; } this._length = n; } /** * Performs the logical AND operation on this bit set and the * complement of the given bit set. This means it * selects every element in the first set, that isn't in the * second set. The result is stored into this bit set. * * @param that the second bit set */ public void andNot(BitSet that) { int i = Math.min(this._length, that._length); while (--i >= 0) { this.bits[i] &= ~that.bits[i]; } } /** * Returns the number of bits set to {@code true} (or the size of this * set). * * @return the number of bits being set. */ public int cardinality() { int sum = 0; for (int i = 0; i < _length; i++) { sum += MathLib.bitCount(bits[i]); } return sum; } /** * Sets all bits in the set to {@code false} (empty the set). */ public void clear() { _length = 0; } /** * Removes the specified integer value from this set. That is * the corresponding bit is cleared. * * @param bitIndex a non-negative integer. * @throws IndexOutOfBoundsException if {@code index < 0} */ public void clear(int bitIndex) { int longIndex = bitIndex >> 6; if (longIndex >= _length) return; bits[longIndex] &= ~(1L << bitIndex); } /** * Sets the bits from the specified {@code fromIndex} (inclusive) to the * specified {@code toIndex} (exclusive) to {@code false}. * * @param fromIndex index of the first bit to be cleared. * @param toIndex index after the last bit to be cleared. * @throws IndexOutOfBoundsException if * {@code (fromIndex < 0) | (toIndex < fromIndex)} */ public void clear(int fromIndex, int toIndex) { if ((fromIndex < 0) || (toIndex < fromIndex)) throw new IndexOutOfBoundsException(); int i = fromIndex >>> 6; if (i >= _length) return; // Ensures that i < _length int j = toIndex >>> 6; if (i == j) { bits[i] &= ((1L << fromIndex) - 1) | (-1L << toIndex); return; } bits[i] &= (1L << fromIndex) - 1; if (j < _length) { bits[j] &= -1L << toIndex; } for (int k = i + 1; (k < j) && (k < _length); k++) { bits[k] = 0; } } public BitSet copy() { long[] _bits = new long[_length]; System.arraycopy(bits, 0, _bits, 0, _length); return new BitSet(_bits, _length); } /** * Sets the bit at the index to the opposite value. * * @param bitIndex the index of the bit. * @throws IndexOutOfBoundsException if {@code bitIndex < 0} */ public void flip(int bitIndex) { int i = bitIndex >> 6; setLength(i + 1); bits[i] ^= 1L << bitIndex; } /** * Sets a range of bits to the opposite value. * * @param fromIndex the low index (inclusive). * @param toIndex the high index (exclusive). * @throws IndexOutOfBoundsException if * {@code (fromIndex < 0) | (toIndex < fromIndex)} */ public void flip(int fromIndex, int toIndex) { if ((fromIndex < 0) || (toIndex < fromIndex)) throw new IndexOutOfBoundsException(); int i = fromIndex >>> 6; int j = toIndex >>> 6; setLength(j + 1); if (i == j) { bits[i] ^= (-1L << fromIndex) & ((1L << toIndex) - 1); return; } bits[i] ^= -1L << fromIndex; bits[j] ^= (1L << toIndex) - 1; for (int k = i + 1; k < j; k++) { bits[k] ^= -1; } } /** * Returns {@code true}> if the specified integer is in * this bit set; {@code false } otherwise. * * @param bitIndex a non-negative integer. * @return the value of the bit at the specified index. * @throws IndexOutOfBoundsException if {@code bitIndex < 0} */ public boolean get(int bitIndex) { int i = bitIndex >> 6; return (i >= _length) ? false : (bits[i] & (1L << bitIndex)) != 0; } // added for scala compatibility public boolean apply(int bitIndex) { if (bitIndex < 0) return false; int i = bitIndex >> 6; return (i >= _length) ? false : (bits[i] & (1L << bitIndex)) != 0; } public boolean contains(int bitIndex) { if (bitIndex < 0) return false; int i = bitIndex >> 6; return (i >= _length) ? false : (bits[i] & (1L << bitIndex)) != 0; } /** * Returns a new bit set composed of a range of bits from this one. * * @param fromIndex the low index (inclusive). * @param toIndex the high index (exclusive). * @return a context allocated bit set instance. * @throws IndexOutOfBoundsException if * {@code (fromIndex < 0) | (toIndex < fromIndex)} */ public BitSet get(int fromIndex, int toIndex) { if (fromIndex < 0 || fromIndex > toIndex) throw new IndexOutOfBoundsException(); BitSet bitSet = BitSet.newInstance(); int length = MathLib.min(_length, (toIndex >>> 6) + 1); bitSet.setLength(length); System.arraycopy(bits, 0, bitSet.bits, 0, length); bitSet.clear(0, fromIndex); bitSet.clear(toIndex, length << 6); return bitSet; } /** * Returns {@code true} if this bit set shares at least one * common bit with the specified bit set. * * @param that the bit set to check for intersection * @return {@code true} if the sets intersect; {@code false} otherwise. */ public boolean intersects(BitSet that) { int i = MathLib.min(this._length, that._length); while (--i >= 0) { if ((bits[i] & that.bits[i]) != 0) { return true; } } return false; } // provided by super class //public boolean isEmpty() { // return nextSetBit(0) == -1; /** * Returns the logical number of bits actually used by this bit * set. It returns the index of the highest set bit plus one. * * <p> Note: This method does not return the number of set bits * which is returned by {@link #size} </p> * * @return the index of the highest set bit plus one. */ public int length() { for (int i = _length; --i >= 0;) { long l = bits[i]; if (l != 0) { return i << 6 + 64 - MathLib.numberOfTrailingZeros(l); } } return 0; } /** * Returns the index of the next {@code false} bit, from the specified bit * (inclusive). * * @param fromIndex the start location. * @return the first {@code false} bit. * @throws IndexOutOfBoundsException if {@code fromIndex < 0} */ public int nextClearBit(int fromIndex) { int offset = fromIndex >> 6; long mask = 1L << fromIndex; while (offset < _length) { long h = bits[offset]; do { if ((h & mask) == 0) { return fromIndex; } mask <<= 1; fromIndex++; } while (mask != 0); mask = 1; offset++; } return fromIndex; } /** * Returns the index of the next {@code true} bit, from the specified bit * (inclusive). If there is none, {@code -1} is returned. * The following code will iterates through the bit set:[code] * for (int i=nextSetBit(0); i >= 0; i = nextSetBit(i)) { * ... * }[/code] * * @param fromIndex the start location. * @return the first {@code false} bit. * @throws IndexOutOfBoundsException if {@code fromIndex < 0} */ public int nextSetBit(int fromIndex) { int offset = fromIndex >> 6; long mask = 1L << fromIndex; while (offset < _length) { long h = bits[offset]; do { if ((h & mask) != 0) return fromIndex; mask <<= 1; fromIndex++; } while (mask != 0); mask = 1; offset++; } return -1; } public boolean nonEmpty() { return nextSetBit(0) != -1; } /** * Performs the logical OR operation on this bit set and the one specified. * In other words, builds the union of the two sets. * The result is stored into this bit set. * * @param that the second bit set. */ public void or(BitSet that) { if (that._length > this._length) { setLength(that._length); } for (int i = that._length; --i >= 0;) { bits[i] |= that.bits[i]; } } /** * Adds the specified integer to this set (corresponding bit is set to * {@code true}. * * @param bitIndex a non-negative integer. * @throws IndexOutOfBoundsException if {@code bitIndex < 0} */ public void set(int bitIndex) { int i = bitIndex >> 6; if (i >= _length) { setLength(i + 1); } bits[i] |= 1L << bitIndex; } /** * Sets the bit at the given index to the specified value. * * @param bitIndex the position to set. * @param value the value to set it to. * @throws IndexOutOfBoundsException if {@code bitIndex < 0} */ public void set(int bitIndex, boolean value) { if (value) { set(bitIndex); } else { clear(bitIndex); } } // added for scala compatibility public void update(int bitIndex, boolean value) { if (value) { set(bitIndex); } else { clear(bitIndex); } } /** * Sets the bits from the specified {@code fromIndex} (inclusive) to the * specified {@code toIndex} (exclusive) to {@code true}. * * @param fromIndex index of the first bit to be set. * @param toIndex index after the last bit to be set. * @throws IndexOutOfBoundsException if * {@code (fromIndex < 0) | (toIndex < fromIndex)} */ public void set(int fromIndex, int toIndex) { if ((fromIndex < 0) || (toIndex < fromIndex)) throw new IndexOutOfBoundsException(); int i = fromIndex >>> 6; int j = toIndex >>> 6; setLength(j + 1); if (i == j) { bits[i] |= (-1L << fromIndex) & ((1L << toIndex) - 1); return; } bits[i] |= -1L << fromIndex; bits[j] |= (1L << toIndex) - 1; for (int k = i + 1; k < j; k++) { bits[k] = -1; } } /** * Sets the bits between from (inclusive) and to (exclusive) to the * specified value. * * @param fromIndex the start range (inclusive). * @param toIndex the end range (exclusive). * @param value the value to set it to. * @throws IndexOutOfBoundsException if {@code bitIndex < 0} */ public void set(int fromIndex, int toIndex, boolean value) { if (value) { set(fromIndex, toIndex); } else { clear(fromIndex, toIndex); } } /** * Returns the cardinality of this bit set (number of bits set). * * <P>Note: Unlike {@code java.util.BitSet} this method does not * returns an approximation of the number of bits of space * actually in use. This method is compliant with * java.util.Collection meaning for size().</p> * * @return the cardinality of this bit set. */ public int size() { return cardinality(); } /** * Performs the logical XOR operation on this bit set and the one specified. * In other words, builds the symmetric remainder of the two sets * (the elements that are in one set, but not in the other). * The result is stored into this bit set. * * @param that the second bit set. */ public void xor(BitSet that) { if (that._length > this._length) { setLength(that._length); } for (int i = that._length; --i >= 0;) { bits[i] ^= that.bits[i]; } } // Optimization. public boolean equals(Object obj) { if (!(obj instanceof BitSet)) return super.equals(obj); BitSet that = (BitSet) obj; int n = MathLib.min(this._length, that._length); for (int i = 0; i < n; ++i) { if (bits[i] != that.bits[i]) return false; } for (int i = n; i < this._length; i++) { if (this.bits[i] != 0) return false; } for (int i = n; i < that._length; i++) { if (that.bits[i] != 0) return false; } return true; } // Optimization. public int hashCode() { int h = 0; for (int i=nextSetBit(0); i >= 0; i = nextSetBit(i)) { h += i; } return h; } // Implements Reusable. public void reset() { _length = 0; } // Implements abstract methods. // Records holds the ordering position of the bit sets. // (e.g. first bit set has a position of zero). public Record head() { return Index.valueOf(-1); } public Record tail() { return Index.valueOf(cardinality()); } public Index valueOf(Record record) { int i = ((Index)record).intValue(); int count= 0; for (int j = 0; j < _length;) { long l = bits[j++]; count += MathLib.bitCount(l); if (count > i) { // Found word for record. int bitIndex = j << 6; while (count != i) { int shiftRight = MathLib.numberOfLeadingZeros(l) + 1; l <<= shiftRight; bitIndex -= shiftRight; count } return Index.valueOf(bitIndex); } } return null; } public void delete(Record record) { Index bitIndex = (Index) valueOf(record); if (bitIndex != null) throw new UnsupportedOperationException("Not supported yet."); } /** * Sets the new length of the table (all new bits are <code>false</code>). * * @param newLength the new length of the table. */ private final void setLength(final int newLength) { if (bits.length < newLength) { // Resizes array. MemoryArea.getMemoryArea(this).executeInArea(new Runnable() { public void run() { int arrayLength = bits.length; while (arrayLength < newLength) { arrayLength <<= 1; } long[] tmp = new long[arrayLength]; System.arraycopy(bits, 0, tmp, 0, _length); bits = tmp; } }); } for (int i = _length; i < newLength; i++) { bits[i] = 0; } _length = newLength; } private static final long serialVersionUID = 1L; }
package soot.dex; import static soot.dex.instructions.InstructionFactory.fromInstruction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.jf.dexlib.CodeItem; import org.jf.dexlib.CodeItem.EncodedCatchHandler; import org.jf.dexlib.CodeItem.EncodedTypeAddrPair; import org.jf.dexlib.CodeItem.TryItem; import org.jf.dexlib.DebugInfoItem; import org.jf.dexlib.DexFile; import org.jf.dexlib.ProtoIdItem; import org.jf.dexlib.TypeIdItem; import org.jf.dexlib.TypeListItem; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.InstructionIterator; import org.jf.dexlib.Debug.DebugInstructionIterator; import soot.Body; import soot.BooleanType; import soot.IntType; import soot.Local; import soot.Modifier; import soot.PackManager; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.SootResolver; import soot.Trap; import soot.Type; import soot.Unit; import soot.UnknownType; import soot.Value; import soot.ValueBox; import soot.dex.instructions.DanglingInstruction; import soot.dex.instructions.DeferableInstruction; import soot.dex.instructions.DexlibAbstractInstruction; import soot.dex.instructions.MoveExceptionInstruction; import soot.dex.instructions.PseudoInstruction; import soot.dex.instructions.RetypeableInstruction; import soot.javaToJimple.LocalGenerator; import soot.jimple.Jimple; import soot.jimple.JimpleBody; import soot.jimple.Stmt; import soot.jimple.internal.JArrayRef; import soot.jimple.internal.JAssignStmt; import soot.jimple.internal.JCastExpr; import soot.jimple.internal.JIdentityStmt; import soot.jimple.internal.JInstanceFieldRef; import soot.jimple.internal.JInstanceOfExpr; import soot.jimple.toolkits.scalar.LocalNameStandardizer; import soot.jimple.toolkits.scalar.UnreachableCodeEliminator; import soot.jimple.toolkits.typing.TypeAssigner; import soot.toolkits.scalar.LocalPacker; import soot.toolkits.scalar.LocalSplitter; import soot.toolkits.scalar.UnusedLocalEliminator; /** * A DexBody contains the code of a DexMethod and is used as a wrapper around * JimpleBody in the jimplification process. * * @author Michael Markert * @author Frank Hartmann */ public class DexBody { private List<DexlibAbstractInstruction> instructions; // keeps track about the jimple locals that are associated with the dex registers private Local[] registerLocals; private Local storeResultLocal; private Map<Integer, DexlibAbstractInstruction> instructionAtAddress; private LocalGenerator localGenerator; private List<DeferableInstruction> deferredInstructions; private Set<RetypeableInstruction> instructionsToRetype; private DanglingInstruction dangling; private int numRegisters; private int numParameterRegisters; private List<Type> parameterTypes; private boolean isStatic; private String methodString = ""; private JimpleBody jBody; private TryItem[] tries; private RefType declaringClassType; private static LocalSplitter splitter; // detect array/instructions overlapping obfuscation private ArrayList<PseudoInstruction> pseudoInstructionData = new ArrayList<PseudoInstruction>(); private DexFile dexFile = null; PseudoInstruction isAddressInData (int a) { for (PseudoInstruction pi: pseudoInstructionData) { int fb = pi.getDataFirstByte(); int lb = pi.getDataLastByte(); if (fb <= a && a <= lb) return pi; } return null; } /** * @param code the codeitem that is contained in this body * @param method the method that is associated with this body */ public DexBody(DexFile dexFile, CodeItem code, RefType declaringClassType) { this.dexFile = dexFile; this.declaringClassType = declaringClassType; tries = code.getTries(); methodString = code.getParent().method.toString(); ProtoIdItem prototype = code.getParent().method.getPrototype(); List<TypeIdItem> paramTypes = TypeListItem.getTypes(prototype.getParameters()); if (paramTypes != null) { parameterTypes = new ArrayList<Type>(); for (TypeIdItem type : paramTypes) parameterTypes.add(DexType.toSoot(type)); } else { parameterTypes = Collections.emptyList(); } numRegisters = code.getRegisterCount(); numParameterRegisters = prototype.getParameterRegisterCount(); isStatic = Modifier.isStatic(code.getParent().accessFlags); instructions = new ArrayList<DexlibAbstractInstruction>(); instructionAtAddress = new HashMap<Integer, DexlibAbstractInstruction>(); registerLocals = new Local[numRegisters]; int address = 0; for (Instruction instruction : code.getInstructions()) { DexlibAbstractInstruction dexInstruction = fromInstruction(instruction, address); instructions.add(dexInstruction); instructionAtAddress.put(address, dexInstruction); Debug.printDbg(" put instruction '"+ dexInstruction +"' at 0x"+ Integer.toHexString(address)); address += instruction.getSize(address); } // get addresses of pseudo-instruction data blocks for(DexlibAbstractInstruction instruction : instructions) { if (instruction instanceof PseudoInstruction) { PseudoInstruction pi = (PseudoInstruction)instruction; try { pi.computeDataOffsets(this); } catch (Exception e) { throw new RuntimeException("exception while computing data offsets: ", e); } pseudoInstructionData.add (pi); Debug.printDbg("add pseudo instruction: 0x"+ Integer.toHexString(pi.getDataFirstByte()) +" - 0x"+ Integer.toHexString(pi.getDataLastByte()) +" : "+ pi.getDataSize()); } } DebugInfoItem debugInfoItem = code.getDebugInfo(); if(debugInfoItem!=null) { DebugInstructionIterator.DecodeInstructions(debugInfoItem, numRegisters, new DebugInstructionIterator.ProcessDecodedDebugInstructionDelegate() { @Override public void ProcessLineEmit(int codeAddress, final int line) { instructionAtAddress(codeAddress).setLineNumber(line); } }); } } /** * Return the types that are used in this body. */ public Set<DexType> usedTypes() { Set<DexType> types = new HashSet<DexType>(); for (DexlibAbstractInstruction i : instructions) types.addAll(i.introducedTypes()); if(tries!=null) { for (TryItem tryItem : tries) { EncodedCatchHandler h = tryItem.encodedCatchHandler; for (EncodedTypeAddrPair handler: h.handlers) { types.add(new DexType(handler.exceptionType)); } } } return types; } /** * Add unit to this body. * * @param u Unit to add. */ public void add(Unit u) { getBody().getUnits().add(u); } /** * Add a deferred instruction to this body. * * @param i the deferred instruction. */ public void addDeferredJimplification(DeferableInstruction i) { deferredInstructions.add(i); } /** * Add a retypeable instruction to this body. * * @param i the retypeable instruction. */ public void addRetype(RetypeableInstruction i) { instructionsToRetype.add(i); } /** * Generate a new local variable. * * @param t the type of the new variable. * @return the generated local. */ public Local generateLocal(Type t) { return localGenerator.generateLocal(t); } /** * Return the associated JimpleBody. * * @throws RuntimeException if no jimplification happened yet. */ public Body getBody() { if (jBody == null) throw new RuntimeException("No jimplification happened yet, no body available."); return jBody; } /** * Return the Locals that are associated with the current register state. * */ public Local[] getRegisterLocals() { return registerLocals; } /** * Return the Local that are associated with the number in the current * register state. * * Handles if the register number actually points to a method parameter. * * @param num the register number */ public Local getRegisterLocal(int num) { return registerLocals[num]; } public Local getStoreResultLocal () { return storeResultLocal; } /** * Return the instruction that is present at the byte code address. * * @param address the byte code address. * @throws RuntimeException if address is not part of this body. */ public DexlibAbstractInstruction instructionAtAddress(int address) { // for (int j=address - 10; j< address+10; j++ ){ // Debug.printDbg(" dump2: 0x"+ Integer.toHexString(j) +" : "+instructionAtAddress.get (j) ); // check if it is a jump to pseudo-instructions data (=obfuscation) PseudoInstruction pi = isAddressInData(address); if (pi != null && !pi.isLoaded()) { System.out.println("warning: attempting to jump to pseudo-instruction data at address 0x"+ Integer.toHexString(address)); System.out.println("pseudo instruction: "+ pi); pi.setLoaded(true); instructions.addAll(decodeInstructions(pi)); // TODO: should add a throw instruction here just to be sure... Exception e = new Exception(); e.printStackTrace(); System.out.println(); } DexlibAbstractInstruction i = instructionAtAddress.get(address); if (i == null) { // catch addresses can be in the middlde of last instruction. Ex. in com.letang.ldzja.en.apk: // 042c46: 7020 2a15 0100 |008f: invoke-direct {v1, v0}, Ljavax/mi... // 042c4c: 2701 |0092: throw v1 // catches : 4 // <any> -> 0x0065 // 0x0069 - 0x0093 if ((i = instructionAtAddress.get(address - 1)) == null) { if ((i = instructionAtAddress.get(address - 2)) == null) { throw new RuntimeException("Address 0x" + Integer.toHexString(address) + "(& -1 -2) not part of method '"+ this.methodString +"'"); } } } return i; } private ArrayList<DexlibAbstractInstruction> decodeInstructions(PseudoInstruction pi) { final ArrayList<Instruction> instructionList = new ArrayList<Instruction>(); ArrayList<DexlibAbstractInstruction> dexInstructions = new ArrayList<DexlibAbstractInstruction>(); byte[] encodedInstructions = pi.getData(); InstructionIterator.IterateInstructions(this.dexFile, encodedInstructions, new InstructionIterator.ProcessInstructionDelegate() { public void ProcessInstruction(int codeAddress, Instruction instruction) { instructionList.add(instruction); } }); Instruction[] instructions = new Instruction[instructionList.size()]; instructionList.toArray(instructions); System.out.println("instructionList: "); int address = pi.getDataFirstByte(); for (Instruction i: instructions) { DexlibAbstractInstruction dexInstruction = fromInstruction(i, address); instructionAtAddress.put(address, dexInstruction); dexInstructions.add(dexInstruction); System.out.println("i = "+ dexInstruction +" @ 0x"+ Integer.toHexString(address)); address += i.getSize(address); } return dexInstructions; } public DvkTyperBase dvkTyper = null; /** * Return the jimple equivalent of this body. * * @param m the SootMethod that contains this body */ public Body jimplify(SootMethod m) { jBody = Jimple.v().newBody(m); localGenerator = new LocalGenerator(jBody); deferredInstructions = new ArrayList<DeferableInstruction>(); instructionsToRetype = new HashSet<RetypeableInstruction>(); if (DvkTyperBase.ENABLE_DVKTYPER) { dvkTyper = null; //new DvkTyper(); } Debug.printDbg("\n[jimplify] start for: "+ methodString); // process method parameters and generate Jimple locals from Dalvik registers List<Local> paramLocals = new LinkedList<Local>(); if (!isStatic) { int thisRegister = numRegisters - numParameterRegisters - 1; Local thisLocal = Jimple.v().newLocal("$u"+ thisRegister, UnknownType.v()); //generateLocal(UnknownType.v()); jBody.getLocals().add(thisLocal); registerLocals[thisRegister] = thisLocal; JIdentityStmt idStmt = (JIdentityStmt) Jimple.v().newIdentityStmt(thisLocal, Jimple.v().newThisRef(declaringClassType)); add(idStmt); paramLocals.add(thisLocal); if (DvkTyperBase.ENABLE_DVKTYPER) { this.dvkTyper.setType(idStmt.leftBox, jBody.getMethod().getDeclaringClass().getType()); } } { int i = 0; // index of parameter type int parameterRegister = numRegisters - numParameterRegisters; // index of parameter register for (Type t: parameterTypes) { Local gen = Jimple.v().newLocal("$u"+ parameterRegister, UnknownType.v()); //may only use UnknownType here because the local may be reused with a different type later (before splitting) jBody.getLocals().add(gen); Debug.printDbg ("add local for parameter register number: "+ parameterRegister); registerLocals[parameterRegister] = gen; JIdentityStmt idStmt = (JIdentityStmt) Jimple.v().newIdentityStmt(gen, Jimple.v().newParameterRef(t, i++)); add(idStmt); paramLocals.add(gen); if (DvkTyperBase.ENABLE_DVKTYPER) { this.dvkTyper.setType(idStmt.leftBox, t); } // some parameters may be encoded on two registers. // in Jimple only the first Dalvik register name is used // as the corresponding Jimple Local name. However, we also add // the second register to the registerLocals array since it could be // used later in the Dalvik bytecode if (t.toString().equals("long") || t.toString().equals("double")) { parameterRegister++; Local g = Jimple.v().newLocal("$u"+ parameterRegister, UnknownType.v()); //may only use UnknownType here because the local may be reused with a different type later (before splitting) jBody.getLocals().add (g); registerLocals[parameterRegister] = g; } parameterRegister++; } } for (int i = 0; i < (numRegisters - numParameterRegisters - (isStatic?0:1)); i++) { Debug.printDbg ("add local for register number: "+ i); registerLocals[i] = Jimple.v().newLocal("$u"+ i, UnknownType.v()); jBody.getLocals().add(registerLocals[i]); } // add local to store intermediate results storeResultLocal = Jimple.v().newLocal("$u-1", UnknownType.v()); jBody.getLocals().add (storeResultLocal); // process bytecode instructions for(DexlibAbstractInstruction instruction : instructions) { if (dangling != null) { dangling.finalize(this, instruction); dangling = null; } //Debug.printDbg(" current op to jimplify: 0x"+ Integer.toHexString(instruction.getInstruction().opcode.value) +" instruction: "+ instruction ); instruction.jimplify(this); //System.out.println("jimple: "+ jBody.getUnits().getLast()); } for(DeferableInstruction instruction : deferredInstructions) { instruction.deferredJimplify(this); } if (tries != null) addTraps(); /* We eliminate dead code. Dead code has been shown to occur under the following * circumstances. * * 0006ec: 0d00 |00a2: move-exception v0 0006f2: 0d00 |00a5: move-exception v0 0x0041 - 0x008a Ljava/lang/Throwable; -> 0x00a5 <any> -> 0x00a2 Here there are two traps both over the same region. But the same always fires, hence rendering the code at a2 unreachable. Dead code yields problems during local splitting because locals within dead code will not be split. Hence we remove all dead code here. */ UnreachableCodeEliminator.v().transform(jBody); Debug.printDbg("\nbefore splitting"); Debug.printDbg(""+(Body)jBody); splitLocals(); Debug.printDbg("\nafter splitting"); Debug.printDbg(""+(Body)jBody); for (RetypeableInstruction i : instructionsToRetype) i.retype(); if (DvkTyperBase.ENABLE_DVKTYPER) { dvkTyper.assignType(); } else { DexNumTransformer.v().transform (jBody); DexNullTransformer.v().transform(jBody); DexIfTransformer.v().transform(jBody); //DexRefsChecker.v().transform(jBody); //DexNullArrayRefTransformer.v().transform(jBody); } Debug.printDbg("\nafter Num and Null transformers"); Debug.printDbg(""+(Body)jBody); TypeAssigner.v().transform(jBody); LocalPacker.v().transform(jBody); UnusedLocalEliminator.v().transform(jBody); LocalNameStandardizer.v().transform(jBody); Debug.printDbg("\nafter type assigner localpacker and name standardizer"); Debug.printDbg(""+(Body)jBody); PackManager.v().getPack("jb").apply(jBody); return jBody; } private void splitLocals() { if(splitter==null) splitter = new LocalSplitter(new DalvikThrowAnalysis()); splitter.transform(jBody); } /** * Set a dangling instruction for this body. * */ public void setDanglingInstruction(DanglingInstruction i) { dangling = i; } /** * Return the instructions that appear (lexically) after the given instruction. * * @param instruction the instruction which successors will be returned. */ public List<DexlibAbstractInstruction> instructionsAfter(DexlibAbstractInstruction instruction) { int i = instructions.indexOf(instruction); if (i == -1) throw new IllegalArgumentException("Instruction" + instruction + "not part of this body."); return instructions.subList(i + 1, instructions.size()); } /** * Return the instructions that appear (lexically) before the given instruction. * * The instruction immediately before the given is the first instruction and so on. * * @param instruction the instruction which successors will be returned. */ public List<DexlibAbstractInstruction> instructionsBefore(DexlibAbstractInstruction instruction) { int i = instructions.indexOf(instruction); if (i == -1) throw new IllegalArgumentException("Instruction " + instruction + " not part of this body."); List<DexlibAbstractInstruction> l = new ArrayList<DexlibAbstractInstruction>(); l.addAll(instructions.subList(0 , i)); Collections.reverse(l); return l; } /** * Add the traps of this body. * * Should only be called at the end jimplify. */ private void addTraps() { for (TryItem tryItem : tries) { int startAddress = tryItem.getStartCodeAddress(); Debug.printDbg(" start : 0x"+ Integer.toHexString(startAddress)); int length = tryItem.getTryLength(); Debug.printDbg(" length: 0x"+ Integer.toHexString(length)); Debug.printDbg(" end : 0x"+ Integer.toHexString(startAddress + length)); int endAddress = startAddress + length; Unit beginStmt = instructionAtAddress(startAddress).getUnit(); // (startAddress + length) typically points to the first byte of the first instruction after the try block // except if there is no instruction after the try block in which case it points to the last byte of the last // instruction of the try block. Removing 1 from (startAddress + length) always points to "somewhere" in // the last instruction of the try block since the smallest instruction is on two bytes (nop = 0x0000). Unit endStmt = instructionAtAddress (endAddress).getUnit(); Debug.printDbg("begin instruction (0x"+ Integer.toHexString(startAddress) +"): "+ instructionAtAddress(startAddress).getUnit() +" --- "+ instructionAtAddress(startAddress).getUnit()); Debug.printDbg("end instruction (0x"+ Integer.toHexString(endAddress) +"): "+ instructionAtAddress (endAddress).getUnit() +" --- "+ instructionAtAddress (endAddress).getUnit()); // for (int i=0x00; i<0x20; i++) { EncodedCatchHandler h = tryItem.encodedCatchHandler; for (EncodedTypeAddrPair handler: h.handlers) { int handlerAddress = handler.getHandlerAddress(); Debug.printDbg("handler (0x"+ Integer.toHexString(handlerAddress) +"): "+ instructionAtAddress (handlerAddress).getUnit() +" --- "+ instructionAtAddress (handlerAddress-1).getUnit()); Type t = DexType.toSoot(handler.exceptionType); // exceptions can only be of RefType if (t instanceof RefType) { SootClass exception = ((RefType) t).getSootClass(); DexlibAbstractInstruction instruction = instructionAtAddress(handler.getHandlerAddress()); if (! (instruction instanceof MoveExceptionInstruction)) Debug.printDbg("First instruction of trap handler unit not MoveException but " + instruction.getClass()); else ((MoveExceptionInstruction) instruction).setRealType(this, exception.getType()); Trap trap = Jimple.v().newTrap(exception, beginStmt, endStmt, instruction.getUnit()); jBody.getTraps().add(trap); } } int catchAllHandlerAddress = h.getCatchAllHandlerAddress(); if (catchAllHandlerAddress != -1) { DexlibAbstractInstruction i = instructionAtAddress(catchAllHandlerAddress); Unit catchAllHandler = i.getUnit(); SootClass exc = SootResolver.v().makeClassRef("java.lang.Throwable"); Trap trap = Jimple.v().newTrap(exc, beginStmt, endStmt, catchAllHandler); ((RetypeableInstruction) i).setRealType(this, exc.getType()); jBody.getTraps().add(trap); } } } //from FT public Stmt captureAssign(JAssignStmt stmt, int current) { ValueBox left = stmt.leftBox; ValueBox right = stmt.rightBox; Debug.printDbg("current captureAssign: 0x"+ Integer.toHexString(current)); switch(current) { case 0x01: case 0x02: case 0x03: dvkTyper.setConstraint(left, right); break; case 0x04: case 0x05: case 0x06: dvkTyper.setConstraint(left, right); break; case 0x07: case 0x08: case 0x09: dvkTyper.setObjectType(right); dvkTyper.setConstraint(left, right); break; case 0xa: case 0xb: dvkTyper.setConstraint(left, right); //dvkTyper.setType(left, right.getValue().getType()); break; case 0xc: dvkTyper.setObjectType(right); dvkTyper.setConstraint(left, right); // 0xc move result object // 0xd move exception // 0xe return void // 0xf return vx // 0x10 return vx // 0x11 return object vx case 0x12: case 0x13: case 0x14: dvkTyper.setConstraint(left,right); break; case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: dvkTyper.setConstraint(left,right); break; case 0x1a: case 0x1b: dvkTyper.setType(left, Scene.v().getRefType("java.lang.String")); break; case 0x1c: dvkTyper.setType(left, Scene.v().getRefType("java.lang.Class")); break; // 0x1d monitor-enter vx // 0x1e monitor-exit vx case 0x1f: dvkTyper.setType(left, right.getValue().getType()); dvkTyper.setType(((JCastExpr) right.getValue()).getOpBox(), right.getValue().getType()); break; case 0x20: dvkTyper.setType(left, BooleanType.v()); dvkTyper.setObjectType(((JInstanceOfExpr) right.getValue()).getOpBox()); break; case 0x21: dvkTyper.setType(left, IntType.v()); break; case 0x22: case 0x23: case 0x24: case 0x25: dvkTyper.setType(left, right.getValue().getType()); break; // 0x25 filled-new-array-range {vx..vy},type_id // 0x26 fill-array-data vx,array_data_offset // 0x27 throw vx // 0x28 goto // 0x29 goto // 0x2a goto // 0x2b switch // 0x2c switch // 0x2d cmp // 0x2e cmp // 0x2f cmp // 0x30 cmp // 0x31 cmp // 0x32 if // 0x33 if // 0x34 if // 0x35 if // 0x36 if // 0x37 if // 0x38 if // 0x39 if // 0x3a if // 0x3b if // 0x3c if // 0x3d if // 0x3e - // 0x3f - // 0x40 - // 0x41 - // 0x42 - // 0x43 - case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: Value arrayGetValue = right.getValue(); if (arrayGetValue instanceof JArrayRef) { dvkTyper.setObjectType(((JArrayRef) arrayGetValue).getBaseBox()); } dvkTyper.setConstraint(right,left); break; case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: case 0x50: case 0x51: dvkTyper.setConstraint(left, right); break; case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: Value fieldGetValue = right.getValue(); if (fieldGetValue instanceof JInstanceFieldRef) { dvkTyper.setObjectType(((JInstanceFieldRef) fieldGetValue).getBaseBox()); } dvkTyper.setType(left, right.getValue().getType()); break; // 0x59 iput see below // 0x5a iput see below // 0x5b iput see below // 0x5c iput see below // 0x5d iput see below // 0x5e iput see below // 0x5f iput see below case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: dvkTyper.setType(left, right.getValue().getType()); break; case 0x59: case 0x5a: case 0x5b: case 0x5c: case 0x5d: case 0x5e: case 0x5f: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: dvkTyper.setType(right, left.getValue().getType()); break; // 0x6e invoke method // 0x6f invoke method // 0x70 invoke method // 0x71 invoke method // 0x72 invoke method // 0x73 - // 0x74 invoke method // 0x75 invoke method // 0x76 invoke method // 0x77 invoke method // 0x78 invoke method // 0x79 to 0xED unused or arithmetic operations // 0xEE to 0xFF unused or odex instructions default: Debug.printDbg("[D2J] warning: No constraint registered for opcode 0x" + Integer.toHexString(current)); } return stmt; } }
package aQute.junit; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.regex.Pattern; import org.junit.runner.Description; import org.junit.runner.manipulation.NoTestsRemainException; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.Constants; import org.osgi.framework.SynchronousBundleListener; import org.osgi.framework.Version; import org.osgi.framework.namespace.HostNamespace; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import aQute.junit.constants.TesterConstants; import junit.framework.JUnit4TestAdapter; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; public class Activator implements BundleActivator, TesterConstants, Runnable { BundleContext context; volatile boolean active; int port = -1; boolean continuous = false; boolean trace = false; PrintStream out = System.err; JUnitEclipseReport jUnitEclipseReport; volatile Thread thread; public Activator() {} @Override public void start(BundleContext context) throws Exception { this.context = context; active = true; if (!Boolean.valueOf(context.getProperty(TESTER_SEPARATETHREAD)) && Boolean.valueOf(context.getProperty("launch.services"))) { // can't // register // services // mini // framework Hashtable<String, String> ht = new Hashtable<>(); ht.put("main.thread", "true"); ht.put(Constants.SERVICE_DESCRIPTION, "JUnit tester"); context.registerService(Runnable.class.getName(), this, ht); } else { thread = new Thread(this, "bnd Runtime Test Bundle"); thread.start(); } } @Override public void stop(BundleContext context) throws Exception { active = false; if (jUnitEclipseReport != null) jUnitEclipseReport.close(); if (thread != null) { thread.interrupt(); thread.join(10000); } } public boolean active() { return active; } @Override public void run() { continuous = Boolean.valueOf(context.getProperty(TESTER_CONTINUOUS)); trace = context.getProperty(TESTER_TRACE) != null; if (thread == null) trace("running in main thread"); // We can be started on our own thread or from the main code thread = Thread.currentThread(); String testcases = context.getProperty(TESTER_NAMES); trace("test cases %s", testcases); if (context.getProperty(TESTER_PORT) != null) { port = Integer.parseInt(context.getProperty(TESTER_PORT)); try { trace("using port %s", port); jUnitEclipseReport = new JUnitEclipseReport(port); } catch (Exception e) { System.err.println("Cannot create link Eclipse JUnit on port " + port); System.exit(254); } } String testerDir = context.getProperty(TESTER_DIR); if (testerDir == null) testerDir = "testdir"; final File reportDir = new File(testerDir); // Jenkins does not detect test failures unless reported // by JUnit XML output. If we have an unresolved failure // we timeout. The following will test if there are any // unresolveds and report this as a JUnit failure. It can // be disabled with -testunresolved=false String unresolved = context.getProperty(TESTER_UNRESOLVED); trace("run unresolved %s", unresolved); if (unresolved == null || unresolved.equalsIgnoreCase("true")) { // Check if there are any unresolved bundles. // If yes, we run a test case to get a proper JUnit report Bundle testBundle = null; for (Bundle b : context.getBundles()) { if (b.getState() == Bundle.INSTALLED) { testBundle = b; break; } } if (testBundle != null) { for (Bundle b : context.getBundles()) { String testcasesheader = b.getHeaders() .get(aQute.bnd.osgi.Constants.TESTCASES); if (testcasesheader != null) { testBundle = b; break; } } int err = 0; try { err = test(context.getBundle(), "aQute.junit.UnresolvedTester", getReportWriter(reportDir, bundleReportName(testBundle))); } catch (IOException e) { // ignore } if (err != 0) { System.exit(err); } } } if (!reportDir.exists() && !reportDir.mkdirs()) { System.err.printf("Could not create directory %s%n", reportDir); } trace("using %s", reportDir); if (testcases == null) { trace("automatic testing of all bundles with " + aQute.bnd.osgi.Constants.TESTCASES + " header"); try { automatic(reportDir); } catch (IOException e) { // ignore } } else { trace("receivednames of classes to test %s", testcases); try { int errors; try (Writer report = getReportWriter(reportDir, reportDir.getName())) { errors = test(null, testcases, report); } System.exit(errors); } catch (Exception e) { e.printStackTrace(); System.exit(254); } } } void automatic(File reportDir) throws IOException { BlockingDeque<Bundle> queue = new LinkedBlockingDeque<>(); trace("adding Bundle Listener for getting test bundle events"); context.addBundleListener((SynchronousBundleListener) event -> { switch (event.getType()) { case BundleEvent.STARTED : case BundleEvent.RESOLVED : checkBundle(queue, event.getBundle()); break; } }); for (Bundle b : context.getBundles()) { checkBundle(queue, b); } trace("starting queue"); int result = 0; while (active()) { try { Bundle bundle = queue.takeFirst(); trace("received bundle to test: %s", bundle.getLocation()); try (Writer report = getReportWriter(reportDir, bundleReportName(bundle))) { trace("test will run"); result += test(bundle, bundle.getHeaders() .get(aQute.bnd.osgi.Constants.TESTCASES), report); trace("test ran"); } if (queue.isEmpty() && !continuous) { trace("queue " + queue); System.exit(result); } } catch (InterruptedException e) { trace("tests bundle queue interrupted"); thread.interrupt(); break; } catch (Exception e) { error("Not sure what happened anymore %s", e); System.exit(254); } } } void checkBundle(BlockingDeque<Bundle> queue, Bundle bundle) { Bundle host = findHost(bundle); if (host != null && (host.getState() == Bundle.ACTIVE || host.getState() == Bundle.STARTING)) { String testcases = bundle.getHeaders() .get(aQute.bnd.osgi.Constants.TESTCASES); if (testcases != null) { trace("found active bundle with test cases %s : %s", bundle, testcases); queue.offerLast(bundle); } } } private Writer getReportWriter(File reportDir, String name) throws IOException { if (reportDir.isDirectory()) { File f = new File(reportDir, "TEST-" + name + ".xml"); Writer writer = new OutputStreamWriter(Files.newOutputStream(f.toPath()), UTF_8); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); return writer; } return null; } private String bundleReportName(Bundle bundle) { Version v = bundle.getVersion(); return bundle.getSymbolicName() + "-" + v.getMajor() + "." + v.getMinor() + "." + v.getMicro(); } /** * The main test routine. * * @param bundle The bundle under test or null * @param testnames The names to test * @param report The report writer or null * @return # of errors */ int test(Bundle bundle, String testnames, Writer report) { trace("testing bundle %s with %s", bundle, testnames); Bundle fw = context.getBundle(0); try { bundle = findHost(bundle); List<String> names = Arrays.asList(testnames.trim() .split(",\\s*")); List<TestReporter> reporters = new ArrayList<>(); final TestResult result = new TestResult(); Tee systemOut = new Tee(System.err); Tee systemErr = new Tee(System.err); systemOut.capture(isTrace()) .echo(true); systemErr.capture(isTrace()) .echo(true); final PrintStream originalOut = System.out; final PrintStream originalErr = System.err; System.setOut(systemOut.getStream()); System.setErr(systemErr.getStream()); trace("changed streams"); try { BasicTestReport basic = new BasicTestReport(this, systemOut, systemErr, result); add(reporters, result, basic); if (port > 0) { add(reporters, result, jUnitEclipseReport); } if (report != null) { add(reporters, result, new JunitXmlReport(report, bundle, basic)); } for (TestReporter tr : reporters) { tr.setup(fw, bundle); } TestSuite suite = createSuite(bundle, names, result); try { trace("created suite %s #%s", suite.getName(), suite.countTestCases()); List<Test> flattened = new ArrayList<>(); int realcount = flatten(flattened, suite); for (TestReporter tr : reporters) { tr.begin(flattened, realcount); } trace("running suite %s", suite); suite.run(result); } catch (Throwable t) { trace("%s", t); result.addError(suite, t); } finally { for (TestReporter tr : reporters) { tr.end(); } } } catch (Throwable t) { System.err.println("exiting " + t); t.printStackTrace(System.err); } finally { System.setOut(originalOut); System.setErr(originalErr); trace("unset streams"); } System.err.println("Tests run : " + result.runCount()); System.err.println("Passed : " + (result.runCount() - result.errorCount() - result.failureCount())); System.err.println("Errors : " + result.errorCount()); System.err.println("Failures : " + result.failureCount()); return result.errorCount() + result.failureCount(); } catch (Exception e) { e.printStackTrace(); } return -1; } /* * Find the host for a fragment. We just iterate over all other bundles and * ask for the fragments. We returns the first one found. */ private Bundle findHost(Bundle bundle) { if (bundle == null) return null; List<Bundle> hosts = new ArrayList<>(); BundleWiring wiring = bundle.adapt(BundleWiring.class); // Bundle isn't resolved. if (wiring == null) { System.err.println("unresolved bundle: " + bundle); return null; } List<BundleWire> wires = wiring.getRequiredWires(HostNamespace.HOST_NAMESPACE); System.err.println("required wires for " + bundle + " " + wires); for (BundleWire wire : wires) { hosts.add(wire.getProviderWiring() .getRevision() .getBundle()); } if (hosts.isEmpty()) { return bundle; } if (hosts.size() > 1) { trace("Found multiple hosts for fragment %s: %s", bundle, hosts); } return hosts.get(0); } private TestSuite createSuite(Bundle tfw, List<String> testNames, TestResult result) { TestSuite suite = new TestSuite(); for (String fqn : testNames) { addTest(tfw, suite, fqn, result); } return suite; } private void addTest(Bundle tfw, TestSuite suite, String fqn, TestResult testResult) { try { int n = fqn.indexOf(':'); if (n > -1) { String method = fqn.substring(n + 1); fqn = fqn.substring(0, n); Class<?> clazz = loadClass(tfw, fqn); if (clazz != null) addTest(suite, clazz, method); else { diagnoseNoClass(tfw, fqn); testResult.addError(suite, new Exception("Cannot load class " + fqn + ", was it included in the test bundle?")); } } else { Class<?> clazz = loadClass(tfw, fqn); if (clazz != null) addTest(suite, clazz, null); else { diagnoseNoClass(tfw, fqn); testResult.addError(suite, new Exception("Cannot load class " + fqn + ", was it included in the test bundle?")); } } } catch (Throwable e) { System.err.println("Can not create test case for: " + fqn + " : " + e); testResult.addError(suite, e); } } private void diagnoseNoClass(Bundle tfw, String fqn) { if (tfw == null) { error("No class found: %s, target bundle: %s", fqn, tfw); trace("Installed bundles:"); for (Bundle bundle : context.getBundles()) { Class<?> c = loadClass(bundle, fqn); String state; switch (bundle.getState()) { case Bundle.UNINSTALLED : state = "UNINSTALLED"; break; case Bundle.INSTALLED : state = "INSTALLED"; break; case Bundle.RESOLVED : state = "RESOLVED"; break; case Bundle.STARTING : state = "STARTING"; break; case Bundle.STOPPING : state = "STOPPING"; break; case Bundle.ACTIVE : state = "ACTIVE"; break; default : state = "UNKNOWN"; } trace("%s %s %s", bundle.getLocation(), state, c != null); } } } @SuppressWarnings("unchecked") private void addTest(TestSuite suite, Class<?> clazz, final String method) { if (TestCase.class.isAssignableFrom(clazz)) { if (hasJunit4Annotations(clazz)) { error( "The test class %s extends %s and it uses JUnit 4 annotations. This means that the annotations will be ignored.", clazz.getName(), TestCase.class.getName()); } trace("using JUnit 3"); if (method != null) { suite.addTest(TestSuite.createTest(clazz, method)); return; } suite.addTestSuite((Class<? extends TestCase>) clazz); return; } trace("using JUnit 4"); JUnit4TestAdapter adapter = new JUnit4TestAdapter(clazz); if (method != null) { trace("method specified " + clazz + ":" + method); final Pattern glob = Pattern.compile(method.replaceAll("\\*", ".*") .replaceAll("\\?", ".?")); try { adapter.filter(new org.junit.runner.manipulation.Filter() { @Override public String describe() { return "Method filter for " + method; } @Override public boolean shouldRun(Description description) { if (glob.matcher(description.getMethodName()) .lookingAt()) { trace("accepted " + description.getMethodName()); return true; } trace("rejected " + description.getMethodName()); return false; } }); } catch (NoTestsRemainException e) { return; } } suite.addTest(adapter); } private boolean hasJunit4Annotations(Class<?> clazz) { if (hasAnnotations("org.junit.", clazz.getAnnotations())) return true; for (Method m : clazz.getMethods()) { if (hasAnnotations("org.junit.", m.getAnnotations())) return true; } return false; } private boolean hasAnnotations(String prefix, Annotation[] annotations) { if (annotations != null) for (Annotation a : annotations) if (a.getClass() .getName() .startsWith(prefix)) return true; return false; } private Class<?> loadClass(Bundle tfw, String fqn) { try { if (tfw != null) { checkResolved(tfw); try { return tfw.loadClass(fqn); } catch (ClassNotFoundException e1) { return null; } } trace("finding %s", fqn); Bundle bundles[] = context.getBundles(); for (int i = bundles.length - 1; i >= 0; i try { checkResolved(bundles[i]); trace("found in %s", bundles[i]); return bundles[i].loadClass(fqn); } catch (ClassNotFoundException e1) { trace("not in %s", bundles[i]); // try next } } } catch (Exception e) { error("Exception during loading of class: %s. Exception %s and cause %s. This sometimes " + "happens when there is an error in the static initialization, the class has " + "no public constructor, it is an inner class, or it has no public access", fqn, e, e.getCause()); } return null; } private void checkResolved(Bundle bundle) { int state = bundle.getState(); if (state == Bundle.INSTALLED || state == Bundle.UNINSTALLED) { trace("unresolved bundle %s", bundle.getLocation()); } } public int flatten(List<Test> list, TestSuite suite) { int realCount = 0; for (Enumeration<?> e = suite.tests(); e.hasMoreElements();) { Test test = (Test) e.nextElement(); if (test instanceof JUnit4TestAdapter) { list.add(test); for (Test t : ((JUnit4TestAdapter) test).getTests()) { if (t instanceof TestSuite) { realCount += flatten(list, (TestSuite) t); } else { list.add(t); realCount++; } } continue; } list.add(test); if (test instanceof TestSuite) { realCount += flatten(list, (TestSuite) test); } else { realCount++; } } return realCount; } private void add(List<TestReporter> reporters, TestResult result, TestReporter rp) { reporters.add(rp); result.addListener(rp); } static public String replace(String source, String symbol, String replace) { StringBuilder sb = new StringBuilder(source); int n = sb.indexOf(symbol, 0); while (n > 0) { sb.replace(n, n + symbol.length(), replace); n = n - symbol.length() + replace.length(); n = sb.indexOf(replace, n); } return sb.toString(); } boolean isTrace() { return trace; } public void trace(String msg, Object... objects) { if (isTrace()) { message("# ", msg, objects); } } void message(String prefix, String string, Object... objects) { Throwable e = null; StringBuilder sb = new StringBuilder(); int n = 0; sb.append(prefix); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '%') { c = string.charAt(++i); switch (c) { case 's' : if (n < objects.length) { Object o = objects[n++]; if (o instanceof Throwable) { Throwable t = e = (Throwable) o; for (Throwable cause; (t instanceof InvocationTargetException) && ((cause = t.getCause()) != null);) { t = cause; } sb.append(t.getMessage()); } else { sb.append(o); } } else sb.append("<no more arguments>"); break; default : sb.append(c); } } else { sb.append(c); } } out.println(sb); if (e != null) e.printStackTrace(out); } public void error(String msg, Object... objects) { message("! ", msg, objects); } /** * Running a test from the command line * * @param args */ public static void main(String args[]) { System.out.println("args " + Arrays.toString(args)); } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * A class to check the Lotto Max bets * * @author Ping Zhang */ public class LottoMaxChecker { public static void main(String[] args) { lotoCheck(); } private static final List<ArrayList<String>> betList = new ArrayList<>(); public static void lotoCheck() { File lotoNumbers = new File("lotoNumbers.txt"); try { BufferedReader bufferedReader; try (FileReader reader = new FileReader(lotoNumbers)) { bufferedReader = new BufferedReader(reader); String s; while ((s = bufferedReader.readLine()) != null) { String[] params = s.split(","); betList.add(new ArrayList<>(Arrays.asList(params))); } } bufferedReader.close(); } catch (IOException ex) { Logger.getLogger(LottoMaxChecker.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(" printArray(betList.get(0), "_"); System.out.println(" for (int j = 1; j < betList.size(); j++) { for (int i = 0; i < betList.get(0).size(); i++) { if (betList.get(j).contains(betList.get(0).get(i))) { System.out.print(betList.get(0).get(i)); System.out.print("_"); betList.get(j).remove(betList.get(0).get(i)); } else { System.out.print("___"); } //new marks if (i == betList.get(0).size() - 2) { System.out.print("***"); } } System.out.print("__"); for (int i = 0; i < betList.get(j).size(); i++) { System.out.print(betList.get(j).get(i)); System.out.print("_"); } System.out.println(); } } /** * * @param list The List to be printed * @param mySeparator The String to separate the list elements */ public static void printArray(ArrayList<String> list, String mySeparator) { for (int index = 0; index < list.size(); index++) { System.out.print(list.get(index)); if (index != list.size() - 1) { System.out.print(mySeparator); } if (index == list.size() - 2) { System.out.print("***"); } } System.out.println(); } }
package mpi.imglib.algorithm.fft; import java.util.concurrent.atomic.AtomicInteger; import edu.mines.jtk.dsp.FftComplex; import edu.mines.jtk.dsp.FftReal; import mpi.imglib.algorithm.Benchmark; import mpi.imglib.algorithm.CanvasImage; import mpi.imglib.algorithm.MultiThreadedOutputAlgorithm; import mpi.imglib.algorithm.math.MathLib; import mpi.imglib.container.array.FakeArray; import mpi.imglib.cursor.LocalizableByDimCursor; import mpi.imglib.cursor.array.ArrayLocalizableByDimCursor; import mpi.imglib.cursor.array.ArrayLocalizableCursor; import mpi.imglib.image.Image; import mpi.imglib.image.ImageFactory; import mpi.imglib.multithreading.SimpleMultiThreading; import mpi.imglib.outside.OutsideStrategyFactory; import mpi.imglib.outside.OutsideStrategyMirrorExpWindowingFactory; import mpi.imglib.outside.OutsideStrategyMirrorFactory; import mpi.imglib.outside.OutsideStrategyValueFactory; import mpi.imglib.type.label.FakeType; import mpi.imglib.type.numeric.ComplexFloatType; import mpi.imglib.type.numeric.FloatType; public class FourierTransform implements MultiThreadedOutputAlgorithm<ComplexFloatType>, Benchmark { public static enum PreProcessing { None, ExtendMirror, ExtendMirrorFading, UseGivenOutsideStrategy } public static enum Rearrangement { RearrangeQuadrants, Unchanged } public static enum FFTOptimization { OptimizeSpeed, OptimizeMemory } final Image<FloatType> img; final int numDimensions; Image<ComplexFloatType> fft; PreProcessing preProcessing; Rearrangement rearrangement; FFTOptimization fftOptimization; float relativeImageExtension; float relativeFadeOutDistance; OutsideStrategyFactory<FloatType> strategy; String errorMessage = ""; int numThreads; long processingTime; public FourierTransform( final Image<FloatType> image, final PreProcessing preProcessing, final Rearrangement rearrangement, final FFTOptimization fftOptimization, final float relativeImageExtension, final float relativeFadeOutDistance ) { this.img = image; this.numDimensions = img.getNumDimensions(); this.preProcessing = preProcessing; this.rearrangement = rearrangement; this.fftOptimization = fftOptimization; this.relativeImageExtension = relativeImageExtension; this.relativeFadeOutDistance = relativeFadeOutDistance; this.strategy = null; this.processingTime = -1; setNumThreads(); } public void setPreProcessing( final PreProcessing preProcessing ) { this.preProcessing = preProcessing; } public void setRearrangement( final Rearrangement rearrangement ) { this.rearrangement = rearrangement; } public void setFFTOptimization( final FFTOptimization fftOptimization ) { this.fftOptimization = fftOptimization; } public void setRelativeImageExtension( final float extensionRatio ) { this.relativeImageExtension = extensionRatio; } public void setRelativeFadeOutDistance( final float relativeFadeOutDistance ) { this.relativeFadeOutDistance = relativeFadeOutDistance; } public void setCustomOutsideStrategy( final OutsideStrategyFactory<FloatType> strategy ) { this.strategy = strategy; } public PreProcessing getPreProcessing() { return preProcessing; } public Rearrangement getRearrangement() { return rearrangement; } public FFTOptimization getFFOptimization() { return fftOptimization; } public float getRelativeImageExtension() { return relativeImageExtension; } public float getRelativeFadeOutDistance() { return relativeFadeOutDistance; } public OutsideStrategyFactory<FloatType> getCustomOutsideStrategy() { return strategy; } public FourierTransform( final Image<FloatType> image ) { this ( image, PreProcessing.ExtendMirrorFading, Rearrangement.RearrangeQuadrants, FFTOptimization.OptimizeSpeed, 0.25f, 0.25f ); } @Override public boolean process() { final CanvasImage<FloatType> canvas; switch ( preProcessing ) { case UseGivenOutsideStrategy: { if ( strategy == null ) { errorMessage = "Custom OutsideStrategyFactory is null, cannot use custom strategy"; return false; } canvas = new CanvasImage<FloatType>( img, getZeroPaddingSize( getExtendedImageSize( img, relativeImageExtension ), fftOptimization), strategy ); break; } case ExtendMirror: { canvas = new CanvasImage<FloatType>( img, getZeroPaddingSize( getExtendedImageSize( img, relativeImageExtension ), fftOptimization), new OutsideStrategyMirrorFactory<FloatType>() ); break; } case ExtendMirrorFading: { canvas = new CanvasImage<FloatType>( img, getZeroPaddingSize( getExtendedImageSize( img, relativeImageExtension ), fftOptimization), new OutsideStrategyMirrorExpWindowingFactory<FloatType>( relativeFadeOutDistance ) ); break; } default: // or NONE { canvas = new CanvasImage<FloatType>( img, getZeroPaddingSize( img.getDimensions(), fftOptimization), new OutsideStrategyValueFactory<FloatType>( new FloatType( 0 ) ) ); break; } } // zero pad and maybe extend the image using the given strategy if ( !canvas.checkInput() && canvas.process() ) { errorMessage = canvas.getErrorMessage(); return false; } // get the result final Image<FloatType> tmp = canvas.getResult(); // perform FFT on the temporary image fft = computeFFT( tmp, getNumThreads(), false ); if ( fft == null ) return false; // close temporary image tmp.close(); return true; } protected Image<ComplexFloatType> computeFFT( final Image<FloatType> img, final int numThreads, final boolean scale ) { final int complexSize[] = new int[ numDimensions ]; // the size of the first dimension is changed complexSize[ 0 ] = ( img.getDimension( 0 ) / 2 + 1); for ( int d = 0; d < numDimensions; ++d ) complexSize[ d ] = img.getDimension( d ) / 2; final ImageFactory<ComplexFloatType> imgFactory = new ImageFactory<ComplexFloatType>( new ComplexFloatType(), img.getStorageFactory() ); final Image<ComplexFloatType> fftImage = imgFactory.createImage( complexSize ); // not enough memory if ( fft == null ) return null; final AtomicInteger ai = new AtomicInteger(0); Thread[] threads = SimpleMultiThreading.newThreads( numThreads ); for (int ithread = 0; ithread < threads.length; ++ithread) threads[ithread] = new Thread(new Runnable() { public void run() { final int myNumber = ai.getAndIncrement(); final int complexSize = fft.getDimension( 0 ); final int size = fft.getDimension( 0 ) * 2; final float[] tempIn = new float[ size ]; float[] tempOut; final FftReal fft = new FftReal( size ); final LocalizableByDimCursor<FloatType> cursor = img.createLocalizableByDimCursor(); final LocalizableByDimCursor<ComplexFloatType> cursorOut = fftImage.createLocalizableByDimCursor(); if ( img.getNumDimensions() > 1 ) { /** * Here we "misuse" a ArrayLocalizableCursor to iterate through all dimensions except the one we are computing the fft in */ final int[] fakeSize = new int[ numDimensions - 1 ]; final int[] tmp = new int[ numDimensions ]; for ( int d = 1; d < numDimensions; ++d ) fakeSize[ d - 1 ] = img.getDimension( d ); final ArrayLocalizableCursor<FakeType> cursorDim = new ArrayLocalizableCursor<FakeType>( new FakeArray<FakeType>( fakeSize ), null, new FakeType() ); // iterate over all dimensions except the one we are computing the fft in, which is dim=0 here while( cursorDim.hasNext() ) { cursorDim.fwd(); if ( cursorDim.getPosition( 0 ) % numThreads == myNumber ) { cursorDim.getPosition( fakeSize ); tmp[ 0 ] = 0; for ( int d = 1; d < numDimensions; ++d ) tmp[ d ] = fakeSize[ d - 1 ]; cursor.setPosition( tmp ); for ( int x = 0; x < size; ++x ) { tempIn[ x ] = cursor.getType().get(); cursor.fwd( 0 ); } fft.realToComplex( -1, tempIn, tempOut ); if (scale) fft.scale( size, tempOut ); cursorOut.setPosition( tmp ); for ( int x = 0; x < complexSize; x++ ) { cursorOut.getType().set( tempOut[x] * 2, tempOut[x] * 2 + 1 ); cursorOut.fwd( 0 ); } } } cursorOut.close(); cursor.close(); cursorDim.close(); } else { // multithreading makes no sense here if ( myNumber == 0) { cursor.setPosition( 0, 0 ); for ( int x = 0; x < size; ++x ) { tempIn[ x ] = cursor.getType().get(); cursor.fwd( 0 ); } fft.realToComplex( -1, tempIn, tempOut ); if (scale) fft.scale( size, tempOut ); cursorOut.setPosition( 0, 0 ); for ( int x = 0; x < complexSize; x++ ) { cursorOut.getType().set( tempOut[x] * 2, tempOut[x] * 2 + 1 ); cursorOut.fwd( 0 ); } } } } }); SimpleMultiThreading.startAndJoin(threads); /* final int height = values.height; final int width = values.width; final int depth = values.depth; final int complexWidth = (width / 2 + 1) * 2; final FloatArray3D result = new FloatArray3D(complexWidth, height, depth); //do fft's in x direction final AtomicInteger ai = new AtomicInteger(0); Thread[] threads = newThreads(); final int numThreads = threads.length; for (int ithread = 0; ithread < threads.length; ++ithread) threads[ithread] = new Thread(new Runnable() { public void run() { int myNumber = ai.getAndIncrement(); float[] tempIn = new float[width]; float[] tempOut; FftReal fft = new FftReal(width); for (int z = 0; z < depth; z++) if (z % numThreads == myNumber) for (int y = 0; y < height; y++) { tempOut = new float[complexWidth]; for (int x = 0; x < width; x++) tempIn[x] = values.get(x, y, z); fft.realToComplex( -1, tempIn, tempOut); if (scale) fft.scale(width, tempOut); for (int x = 0; x < complexWidth; x++) result.set(tempOut[x], x, y, z); } } }); startAndJoin(threads); //do fft's in y direction ai.set(0); threads = newThreads(); for (int ithread = 0; ithread < threads.length; ++ithread) threads[ithread] = new Thread(new Runnable() { public void run() { float[] tempIn = new float[height * 2]; float[] tempOut; FftComplex fftc = new FftComplex(height); int myNumber = ai.getAndIncrement(); for (int z = 0; z < depth; z++) if (z % numThreads == myNumber) for (int x = 0; x < complexWidth / 2; x++) { tempOut = new float[height * 2]; for (int y = 0; y < height; y++) { tempIn[y * 2] = result.get(x * 2, y, z); tempIn[y * 2 + 1] = result.get(x * 2 + 1, y, z); } fftc.complexToComplex( -1, tempIn, tempOut); for (int y = 0; y < height; y++) { result.set(tempOut[y * 2], x * 2, y, z); result.set(tempOut[y * 2 + 1], x * 2 + 1, y, z); } } } }); startAndJoin(threads); */ return null; } protected int[] getExtendedImageSize( final Image<?> img, final float extensionRatio ) { final int[] extendedSize = new int[ img.getNumDimensions() ]; for ( int d = 0; d < img.getNumDimensions(); ++d ) { extendedSize[ d ] = MathLib.round( img.getDimension( d ) * extensionRatio ); // add an even number so that both sides extend equally if ( extendedSize[ d ] % 2 != 0) extendedSize[ d ]++; } return extendedSize; } protected int[] getZeroPaddingSize( final int[] imageSize, final FFTOptimization fftOptimization ) { final int[] fftSize = new int[ imageSize.length ]; // the first dimension is real to complex fftSize[ 0 ] = FftReal.nfftFast( imageSize[ 0 ] ); // all the other dimensions complex to complex for ( int d = 1; d < fftSize.length; ++d ) { if ( fftOptimization == FFTOptimization.OptimizeSpeed ) fftSize[ d ] = FftComplex.nfftSmall( imageSize[ d ] ); else fftSize[ d ] = FftComplex.nfftFast( imageSize[ d ] ); } return fftSize; } @Override public long getProcessingTime() { return processingTime; } @Override public void setNumThreads() { this.numThreads = Runtime.getRuntime().availableProcessors(); } @Override public void setNumThreads( final int numThreads ) { this.numThreads = numThreads; } @Override public int getNumThreads() { return numThreads; } @Override public Image<ComplexFloatType> getResult() { return fft; } @Override public boolean checkInput() { if ( errorMessage.length() > 0 ) { return false; } else if ( img == null ) { errorMessage = "Input image is null"; return false; } else { return true; } } @Override public String getErrorMessage() { return errorMessage; } }
package jlibs.nblr.rules; import java.util.*; /** * @author Santhosh Kumar T */ public class Paths extends ArrayList<Path>{ public final Path owner; public final int depth; public Paths(Path owner){ this.owner = owner; if(owner!=null){ owner.children = this; depth = owner.depth+1; }else depth = 1; } public boolean add(Path path){ if(owner==null) path.branch = size(); else path.branch = owner.branch; path.parent = owner; path.depth = depth; return super.add(path); } @SuppressWarnings({"SimplifiableIfStatement"}) private static boolean clashes(Path p1, Path p2){ if(p1.matcher()==null && p2.matcher()==null) throw new IllegalStateException("Ambiguous Routes"); if(p1.matcher()!=null && p2.matcher()!=null){ if(p1.matcherEdge().fallback || p2.matcherEdge().fallback) return false; else return p1.clashesWith(p2); } return false; } public static Paths travel(Node fromNode){ Paths rootPaths = new Paths(null); List<Path> list = new ArrayList<Path>(); while(true){ if(list.size()==0){ rootPaths.populate(fromNode, new ArrayDeque<Object>()); list.addAll(rootPaths); }else{ List<Path> newList = new ArrayList<Path>(); for(Path path: list){ if(path.matcher()!=null){ Paths paths = new Paths(path); paths.populate((Node)path.get(path.size()-1)); newList.addAll(paths); } } list = newList; } TreeSet<Integer> clashingIndexes = new TreeSet<Integer>(); for(int ibranch=0; ibranch<rootPaths.size()-1; ibranch++){ for(int jbranch=ibranch+1; jbranch<rootPaths.size(); jbranch++){ int i = 0; for(Path ipath: list){ if(ipath.branch==ibranch){ int j = 0; for(Path jpath: list){ if(jpath.branch==jbranch){ if(clashes(ipath, jpath)){ if(ipath.hasLoop() && jpath.hasLoop()) throw new IllegalStateException("Infinite lookAhead needed"); clashingIndexes.add(i); clashingIndexes.add(j); } } j++; } } i++; } } } if(clashingIndexes.size()==0) return rootPaths; List<Path> clashingPaths = new ArrayList<Path>(clashingIndexes.size()); for(int id: clashingIndexes) clashingPaths.add(list.get(id)); list = clashingPaths; } } private void populate(Node fromNode){ populate(fromNode, new ArrayDeque<Object>()); } private void populate(Node fromNode, Deque<Object> stack){ if(stack.contains(fromNode)) throw new IllegalStateException("infinite loop detected"); stack.push(fromNode); if(fromNode.outgoing.size()>0){ for(Edge edge: fromNode.outgoing){ stack.push(edge); if(edge.matcher!=null){ stack.push(edge.target); add(new Path(stack)); stack.pop(); }else if(edge.rule!=null) populate(edge.rule.node, stack); else populate(edge.target, stack); stack.pop(); } }else{ int rulesPopped = 0; boolean wasNode = false; Node target = null; for(Object obj: stack){ if(obj instanceof Node){ if(wasNode) rulesPopped++; wasNode = true; }else if(obj instanceof Edge){ wasNode = false; Edge edge = (Edge)obj; if(edge.rule!=null){ if(rulesPopped==0){ target = edge.target; break; }else rulesPopped } } } Path p = this.owner; while(p!=null && target==null){ wasNode = false; for(int i=p.size()-1; i>=0; i Object obj = p.get(i); if(obj instanceof Node){ if(wasNode) rulesPopped++; wasNode = true; }else if(obj instanceof Edge){ wasNode = false; Edge edge = (Edge)obj; if(edge.rule!=null){ if(rulesPopped==0){ target = edge.target; break; }else rulesPopped } } } p = p.parent; } if(target==null){ add(new Path(stack)); }else populate(target, stack); } stack.pop(); } }
package ch.elexis.data; import static ch.elexis.core.model.PatientConstants.FLD_EXTINFO_LEGAL_GUARDIAN; import static ch.elexis.core.model.PatientConstants.FLD_EXTINFO_STAMMARZT; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import ch.elexis.admin.AccessControlDefaults; import ch.elexis.core.constants.Preferences; import ch.elexis.core.constants.StringConstants; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.data.interfaces.events.MessageEvent; import ch.elexis.core.jdt.Nullable; import ch.elexis.core.model.prescription.EntryType; import ch.rgw.tools.ExHandler; import ch.rgw.tools.JdbcLink; import ch.rgw.tools.JdbcLink.Stm; import ch.rgw.tools.Money; import ch.rgw.tools.StringTool; import ch.rgw.tools.TimeTool; import ch.rgw.tools.TimeTool.TimeFormatException; public class Patient extends Person { public static final String FLD_ALLERGIES = "Allergien"; public static final String FLD_RISKS = "Risiken"; public static final String FLD_GROUP = "Gruppe"; public static final String FLD_DIAGNOSES = "Diagnosen"; public static final String FLD_PATID = "PatientNr"; public final static String FLD_NAME = "Name"; public static final String FLD_FIRSTNAME = "Vorname"; public static final String FLD_SEX = "Geschlecht"; public static final String FLD_DOB = "Geburtsdatum"; public static final String FLD_STREET = "Strasse"; public static final String FLD_ZIP = "Plz"; public static final String FLD_PLACE = "Ort"; public static final String FLD_PHONE1 = "Telefon1"; public static final String FLD_FAX = "Fax"; public static final String FLD_BALANCE = "Konto"; public static final String FLD_PERS_ANAMNESE = "PersAnamnese"; public static final String FLD_SYS_ANAMNESE = "SysAnamnese"; public static final String FLD_FAM_ANAMNESE = "FamilienAnamnese"; public static final String[] DEFAULT_SORT = { FLD_NAME, FLD_FIRSTNAME, FLD_DOB }; static { addMapping(Kontakt.TABLENAME, FLD_DIAGNOSES + " =S:C:Diagnosen", FLD_PERS_ANAMNESE + " =S:C:PersAnamnese", "SystemAnamnese =S:C:SysAnamnese", "FamilienAnamnese =S:C:FamAnamnese", FLD_RISKS, FLD_ALLERGIES, "Faelle =LIST:PatientID:FAELLE:DatumVon", "Garanten =JOINT:GarantID:PatientID:PATIENT_GARANT_JOINT:" + Kontakt.class.getCanonicalName(), "Dauermedikation =JOINT:ArtikelID:PatientID:PATIENT_ARTIKEL_JOINT:" + Artikel.class.getCanonicalName(), FLD_BALANCE + " =LIST:PatientID:KONTO", FLD_GROUP, FLD_PATID, Kontakt.FLD_IS_PATIENT); } public String getDiagnosen(){ return get(FLD_DIAGNOSES); } public String getPersAnamnese(){ return get("PersAnamnese"); } public String getSystemAnamnese(){ return get("Systemanamnese"); } protected Patient(){/* leer */ } @Override public boolean isValid(){ if (!super.isValid()) { return false; } String geb = (get(Person.BIRTHDATE)); if (geb.equals("WERT?")) { return false; } String g = get(Person.SEX); if (g.equals(Person.MALE) || g.equals(Person.FEMALE)) { return true; } return false; } /** * Dieser oder der folgende Konstruktor sollte normalerweise verwendet werden, um einen neuen, * bisher noch nicht in der Datenbank vorhandenen Patienten anzulegen. * * @param Name * @param Vorname * @param Geburtsdatum * Als String in Notation dd.mm.jj * @param s * Geschlecht m oder w */ public Patient(final String Name, final String Vorname, final String Geburtsdatum, final String s){ super(Name, Vorname, Geburtsdatum, s); getPatCode(); } /** * This constructor is more critical than the previous one * * @param name * will be checked for non-alphabetic characters * @param vorname * will be checked for non alphabetiic characters * @param gebDat * will be checked for unplausible values * @param s * will be checked for undefined values * @throws TimeFormatException */ public Patient(final String name, final String vorname, final TimeTool gebDat, final String s) throws PersonDataException{ super(name, vorname, gebDat, s); getPatCode(); } public Fall[] getFaelle(){ List<String> cas = getList("Faelle", true); Fall[] ret = new Fall[cas.size()]; int i = 0; for (String id : cas) { Fall fall = Fall.load(id); fall.setDBConnection(getDBConnection()); ret[i++] = fall; } return ret; } /** * Get the patients active medication filtered by {@link EntryType}. * * @param filterType * or null * @return */ public List<Prescription> getMedication(@Nullable EntryType filterType){ Query<Prescription> qbe = new Query<Prescription>(Prescription.class); qbe.add(Prescription.FLD_PATIENT_ID, Query.EQUALS, getId()); qbe.add(Prescription.FLD_REZEPT_ID, StringTool.leer, null); String today = new TimeTool().toString(TimeTool.DATE_COMPACT); qbe.startGroup(); qbe.add(Prescription.FLD_DATE_UNTIL, Query.GREATER_OR_EQUAL, today); qbe.or(); qbe.add(Prescription.FLD_DATE_UNTIL, StringTool.leer, null); qbe.endGroup(); List<Prescription> prescriptions = qbe.execute(); if (filterType != null) { return prescriptions.parallelStream().filter(p -> p.getEntryType() == filterType) .collect(Collectors.toList()); } else { return prescriptions; } } /** * Get the patients medication filtered by {@link EntryType} as text. * * @param filterType * or null * @return */ public String getMedicationText(@Nullable EntryType filterType){ List<Prescription> prescriptions = getMedication(filterType); StringBuilder sb = new StringBuilder(); prescriptions.stream().forEach(p -> sb.append(p.getLabel()).append(StringTool.lf)); return sb.toString(); } /** * Fixmedikation dieses Patienten einlesen * * @return ein Array aus {@link Prescription} * @deprecated does not filter by EntryType, use {@link Patient#getMedication(EntryType)} * instead. */ public Prescription[] getFixmedikation(){ Query<Prescription> qbe = new Query<Prescription>(Prescription.class); qbe.add(Prescription.FLD_PATIENT_ID, Query.EQUALS, getId()); qbe.add(Prescription.FLD_REZEPT_ID, StringTool.leer, null); String today = new TimeTool().toString(TimeTool.DATE_COMPACT); qbe.startGroup(); qbe.add(Prescription.FLD_DATE_UNTIL, Query.GREATER_OR_EQUAL, today); qbe.or(); qbe.add(Prescription.FLD_DATE_UNTIL, StringTool.leer, null); qbe.endGroup(); List<Prescription> l = qbe.execute(); return l.toArray(new Prescription[0]); } /** * Fixmedikation als Text * * @return * @deprecated does not filter by EntryType, use {@link Patient#getMedication(EntryType)} * instead. */ public String getMedikation(){ Prescription[] pre = getFixmedikation(); StringBuilder sb = new StringBuilder(); for (Prescription p : pre) { sb.append(p.getLabel()).append(StringTool.lf); } return sb.toString(); } /** * Die neueste Konsultation dieses Patienten holen, soweit eruierbar * * @param create * : eine Kons erstellen, falls keine existiert * @return die letzte Konsultation oder null */ public Konsultation getLetzteKons(final boolean create){ if (ElexisEventDispatcher.getSelectedMandator() == null) { MessageEvent.fireError("Kein Mandant angemeldet", "Es ist kein Mandant angemeldet."); return null; } Query<Konsultation> qbe = new Query<Konsultation>(Konsultation.class); // if not configured otherwise load only consultations of active mandant if (!CoreHub.userCfg.get(Preferences.USR_DEFLOADCONSALL, false)) { Mandant mandator = ElexisEventDispatcher.getSelectedMandator(); if (mandator != null) { qbe.add(Konsultation.FLD_MANDATOR_ID, Query.EQUALS, mandator.getId()); } } // qbe.add("Datum", "=", new // TimeTool().toString(TimeTool.DATE_COMPACT)); Fall[] faelle = getFaelle(); if ((faelle == null) || (faelle.length == 0)) { return create ? createFallUndKons() : null; } qbe.startGroup(); boolean termInserted = false; for (Fall fall : faelle) { if (fall.isOpen()) { qbe.add(Konsultation.FLD_CASE_ID, Query.EQUALS, fall.getId()); qbe.or(); termInserted = true; } } if (!termInserted) { return create ? createFallUndKons() : null; } qbe.endGroup(); qbe.orderBy(true, Konsultation.DATE); List<Konsultation> list = qbe.execute(); if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); } } public Konsultation createFallUndKons(){ Fall fall = neuerFall(Fall.getDefaultCaseLabel(), Fall.getDefaultCaseReason(), Fall.getDefaultCaseLaw()); Konsultation k = fall.neueKonsultation(); k.setMandant(ElexisEventDispatcher.getSelectedMandator()); return k; } /** * Einen neuen Fall erstellen und an den Patienten binden * * @return der eben erstellte Fall oder null bei Fehler */ public Fall neuerFall(final String Bezeichnung, final String grund, final String Abrechnungsmethode){ Fall fall = new Fall(getId(), Bezeichnung, grund, Abrechnungsmethode); ElexisEventDispatcher.reload(Fall.class); return fall; } public String getPatCode(){ String rc = get(FLD_PATID); if (!StringTool.isNothing(rc)) { return rc; } while (true) { String lockid = PersistentObject.lock("PatNummer", true); String pid = getDBConnection() .queryString("SELECT WERT FROM CONFIG WHERE PARAM='PatientNummer'"); if (StringTool.isNothing(pid)) { pid = "0"; getDBConnection() .exec("INSERT INTO CONFIG (PARAM,WERT) VALUES ('PatientNummer','0')"); } int lastNum = Integer.parseInt(pid) + 1; rc = Integer.toString(lastNum); getDBConnection() .exec("UPDATE CONFIG set wert='" + rc + "' where param='PatientNummer'"); PersistentObject.unlock("PatNummer", lockid); String exists = getDBConnection() .queryString("SELECT ID FROM KONTAKT WHERE PatientNr=" + JdbcLink.wrap(rc)); if (exists == null) { break; } } set(FLD_PATID, rc); return rc; } public Money getKontostand(){ StringBuilder sql = new StringBuilder(); sql.append("SELECT betrag FROM KONTO WHERE PatientID=").append(getWrappedId()); Stm stm = getDBConnection().getStatement(); Money konto = new Money(); try { ResultSet res = stm.query(sql.toString()); while (res.next()) { int buchung = res.getInt(1); konto.addCent(buchung); } return konto; } catch (Exception ex) { ExHandler.handle(ex); return null; } finally { getDBConnection().releaseStatement(stm); } } /** * to be used by the platzhalter system, allows for presentation of the current balance of this * patient by using [Patient.Konto] * * @return the current balance of the patient */ public String getBalance(){ return getKontostand().getAmountAsString(); } /** * Calculates a possibly available account excess. (This value may be added to a bill as * prepayment.) * <p> * Considers all overpaid bills and account transactions not bound to a bill. The garant of the * bill must be the patient itself. (Bills not yet paid or partly paid are not considered.) * <p> * This value is not the same as the current account balance, since we ignore outstanding debts * of not yet paid bills. * * @return the account excess (may be zero or positive) */ public Money getAccountExcess(){ Money prepayment = new Money(); // overpaid bills of this patient // TODO do an optimized query over KONTAKT/FALL/RECHNUNG Query<Rechnung> rQuery = new Query<Rechnung>(Rechnung.class); // normally do not display other mandator's balance if (CoreHub.acl.request(AccessControlDefaults.ACCOUNTING_GLOBAL) == false) { Mandant mandator = ElexisEventDispatcher.getSelectedMandator(); if (mandator != null) { rQuery.add(Rechnung.MANDATOR_ID, Query.EQUALS, mandator.getId()); } } // let the database engine do the filtering Fall[] faelle = getFaelle(); if ((faelle != null) && (faelle.length > 0)) { rQuery.startGroup(); for (Fall fall : faelle) { rQuery.add(Rechnung.CASE_ID, Query.EQUALS, fall.getId()); rQuery.or(); } rQuery.endGroup(); } List<Rechnung> rechnungen = rQuery.execute(); if (rechnungen != null) { for (Rechnung rechnung : rechnungen) { Fall fall = rechnung.getFall(); if (fall != null) { // of course this should never happen Query<AccountTransaction> atQuery = new Query<AccountTransaction>(AccountTransaction.class); atQuery.add(AccountTransaction.FLD_PATIENT_ID, Query.EQUALS, getId()); atQuery.add(AccountTransaction.FLD_BILL_ID, Query.EQUALS, rechnung.getId()); List<AccountTransaction> transactions = atQuery.execute(); if (transactions != null) { Money sum = new Money(); for (AccountTransaction transaction : transactions) { sum.addMoney(transaction.getAmount()); } if (sum.getCents() > 0) { prepayment.addMoney(sum); } } } } } // account (sum over all account transactions not assigned to a bill) Query<AccountTransaction> atQuery = new Query<AccountTransaction>(AccountTransaction.class); atQuery.add(AccountTransaction.FLD_PATIENT_ID, Query.EQUALS, getId()); List<AccountTransaction> transactions = atQuery.execute(); if (transactions != null) { Money sum = new Money(); for (AccountTransaction transaction : transactions) { Rechnung rechnung = transaction.getRechnung(); if ((rechnung == null) || !rechnung.exists()) { sum.addMoney(transaction.getAmount()); } } prepayment.addMoney(sum); } return prepayment; } /** Einen Patienten mit gegebener ID aus der Datenbank einlesen */ public static Patient load(final String id){ Patient ret = new Patient(id); return ret; } /** * Einen Patienten aufgrund seiner PatientenNr laden * * @param patientNr * @return Patient falls gefunden, <code>null</code> wenn nicht gefunden */ public static Patient loadByPatientID(String patientNr){ String patID = new Query<Patient>(Patient.class).findSingle(Patient.FLD_PATID, Query.EQUALS, patientNr); return Patient.load(patID); } private Patient(final String id){ super(id); } @Override protected String getConstraint(){ return new StringBuilder(Kontakt.FLD_IS_PATIENT).append(Query.EQUALS) .append(JdbcLink.wrap(StringConstants.ONE)).toString(); } @Override protected void setConstraint(){ set(new String[] { Kontakt.FLD_IS_PATIENT, Kontakt.FLD_IS_PERSON }, StringConstants.ONE, StringConstants.ONE); } @Override /* * * Return a short or long label for this Patient * * This implementation returns "<Vorname> <Name>" for the sort label, and calls getPersonalia() * for the long label. * * @return a label describing this Patient */ public String getLabel(final boolean shortLabel){ if (shortLabel) { return super.getLabel(true); } else { return getPersonalia(); } } /** * We do not allow direct deletion -> use remove instead */ @Override public boolean delete(){ return delete(false); } public boolean delete(final boolean force){ Fall[] fl = getFaelle(); if ((fl.length == 0) || ((force == true) && (CoreHub.acl.request(AccessControlDefaults.DELETE_FORCED) == true))) { for (Fall f : fl) { f.delete(true); } delete_dependent(); return super.delete(); } return false; } private boolean delete_dependent(){ for (LabResult lr : new Query<LabResult>(LabResult.class, LabResult.PATIENT_ID, getId()) .execute()) { lr.delete(); } for (Rezept rp : new Query<Rezept>(Rezept.class, Rezept.PATIENT_ID, getId()).execute()) { rp.delete(); } for (Brief br : new Query<Brief>(Brief.class, Brief.FLD_PATIENT_ID, getId()).execute()) { br.delete(); } for (AccountTransaction at : new Query<AccountTransaction>(AccountTransaction.class, AccountTransaction.FLD_PATIENT_ID, getId()).execute()) { at.delete(); } return true; } @Override public boolean isDragOK(){ return true; } public String getAuftragsnummer(){ String pid = StringTool.addModulo10(getPatCode()) + "-" //$NON-NLS-1$ + new TimeTool().toString(TimeTool.TIME_COMPACT); return pid; } /** * Das Alter des Patienten in Jahren errechnen * * @return Das Alter in ganzen Jahren als String */ public String getAlter(){ TimeTool now = new TimeTool(); TimeTool bd = new TimeTool(getGeburtsdatum()); int jahre = now.get(TimeTool.YEAR) - bd.get(TimeTool.YEAR); bd.set(TimeTool.YEAR, now.get(TimeTool.YEAR)); if (bd.isAfter(now)) { jahre -= 1; } return Integer.toString(jahre); } /** * Return all bills of this patient * * @return a list of bills of this patient */ public List<Rechnung> getRechnungen(){ List<Rechnung> rechnungen = new ArrayList<Rechnung>(); Fall[] faelle = getFaelle(); if ((faelle != null) && (faelle.length > 0)) { Query<Rechnung> query = new Query<Rechnung>(Rechnung.class); query.insertTrue(); query.startGroup(); for (Fall fall : faelle) { query.add(Rechnung.CASE_ID, Query.EQUALS, fall.getId()); query.or(); } query.endGroup(); List<Rechnung> rnList = query.execute(); if (rnList != null) { rechnungen.addAll(rnList); } } return rechnungen; } // PatientDetailView backport from 2.2 - databinding bean compatibility public String getAllergies(){ return get(FLD_ALLERGIES); } public void setAllergies(String allergien){ set(FLD_ALLERGIES, allergien); } public String getPersonalAnamnese(){ return get(FLD_PERS_ANAMNESE); } public void setPersonalAnamnese(String anamnese){ set(FLD_PERS_ANAMNESE, anamnese); } public String getComment(){ return get(FLD_REMARK); } public void setComment(String bemerkungen){ set(FLD_REMARK, bemerkungen); } public String getFamilyAnamnese(){ return get(FLD_FAM_ANAMNESE); } public void setFamilyAnamnese(String anamnese){ set(FLD_FAM_ANAMNESE, anamnese); } public void setDiagnosen(String diagnosen){ set(FLD_DIAGNOSES, diagnosen); } public String getRisk(){ return get(FLD_RISKS); } public void setRisk(String risk){ set(FLD_RISKS, risk); } public void removeStammarzt(){ removeFromExtInfo(FLD_EXTINFO_STAMMARZT); } public void setStammarzt(Kontakt stammarzt){ if (stammarzt == null) return; // we override the name to force PersistentObject#get(String) to revert // to the method getStammarzt to fetch the entry setExtInfoStoredObjectByKey(FLD_EXTINFO_STAMMARZT, stammarzt.getId()); } /** * @return Stammarzt for the patient if defined, else <code>null</code> */ public Kontakt getStammarzt(){ // we override the name to force PersistentObject#get(String) to revert // to the method getStammarzt to fetch the entry // unfortunately lots of PersistentObject: field is not mapped Stammarzt // will be thrown .. return (getExtInfoStoredObjectByKey(FLD_EXTINFO_STAMMARZT) != null) ? Kontakt.load((String) getExtInfoStoredObjectByKey(FLD_EXTINFO_STAMMARZT)) : null; } public void setLegalGuardian(Kontakt legalGuardian){ if (legalGuardian == null) { removeFromExtInfo(FLD_EXTINFO_LEGAL_GUARDIAN); return; } setExtInfoStoredObjectByKey(FLD_EXTINFO_LEGAL_GUARDIAN, legalGuardian.getId()); } public Kontakt getLegalGuardian(){ Object guardianId = getExtInfoStoredObjectByKey(FLD_EXTINFO_LEGAL_GUARDIAN); if (guardianId != null && !((String) guardianId).isEmpty()) { return Kontakt.load((String) guardianId); } return null; } @SuppressWarnings("unchecked") private void removeFromExtInfo(String key){ Map h = getMap(FLD_EXTINFO); h.remove(key); setMap(FLD_EXTINFO, h); } }
package peergos.server.storage; import com.amazonaws.*; import com.amazonaws.auth.*; import com.amazonaws.client.builder.*; import com.amazonaws.services.s3.*; import com.amazonaws.services.s3.model.*; import peergos.server.*; import peergos.server.corenode.*; import peergos.server.sql.*; import peergos.server.util.*; import peergos.shared.*; import peergos.shared.cbor.*; import peergos.shared.crypto.asymmetric.*; import peergos.shared.crypto.hash.*; import peergos.shared.io.ipfs.cid.*; import peergos.shared.io.ipfs.multibase.binary.*; import peergos.shared.mutable.*; import peergos.shared.storage.*; import peergos.shared.io.ipfs.multihash.*; import io.prometheus.client.Histogram; import peergos.shared.util.*; import java.io.*; import java.nio.file.*; import java.sql.*; import java.time.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.*; public class S3BlockStorage implements ContentAddressedStorage { private static final Logger LOG = Logger.getGlobal(); private static final Histogram readTimerLog = Histogram.build() .labelNames("filesize") .name("block_read_seconds") .help("Time to read a block from immutable storage") .exponentialBuckets(0.01, 2, 16) .register(); private static final Histogram writeTimerLog = Histogram.build() .labelNames("filesize") .name("s3_block_write_seconds") .help("Time to write a block to immutable storage") .exponentialBuckets(0.01, 2, 16) .register(); private final Multihash id; private final AmazonS3 s3Client; private final String bucket, folder; private final TransactionStore transactions; private final ContentAddressedStorage p2pFallback; public S3BlockStorage(S3Config config, Multihash id, TransactionStore transactions, ContentAddressedStorage p2pFallback) { this.id = id; this.bucket = config.bucket; this.folder = config.path.isEmpty() || config.path.endsWith("/") ? config.path : config.path + "/"; AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard() .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(config.regionEndpoint, config.region)) .withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(config.accessKey, config.secretKey))); s3Client = builder.build(); LOG.info("Using S3 Block Storage at " + config.regionEndpoint + ", bucket " + config.bucket + ", path: " + config.path); this.transactions = transactions; this.p2pFallback = p2pFallback; } private static String hashToKey(Multihash hash) { // To be compatible with IPFS we use the same scheme here, the cid bytes encoded as uppercase base32 String padded = new Base32().encodeAsString(hash.toBytes()); int padStart = padded.indexOf("="); return padStart > 0 ? padded.substring(0, padStart) : padded; } private Multihash keyToHash(String key) { // To be compatible with IPFS we use the ame scheme here, the cid bytes encoded as uppercase base32 byte[] decoded = new Base32().decode(key.substring(folder.length())); return Cid.cast(decoded); } @Override public CompletableFuture<Optional<CborObject>> get(Multihash hash) { if (hash instanceof Cid && ((Cid) hash).codec == Cid.Codec.Raw) throw new IllegalStateException("Need to call getRaw if cid is not cbor!"); return getRaw(hash).thenApply(opt -> opt.map(CborObject::fromByteArray)); } @Override public CompletableFuture<Optional<byte[]>> getRaw(Multihash hash) { Optional<byte[]> fromS3 = map(hash, h -> { GetObjectRequest get = new GetObjectRequest(bucket, folder + hashToKey(hash)); Histogram.Timer readTimer = readTimerLog.labels("read").startTimer(); try (S3Object res = s3Client.getObject(get); DataInputStream din = new DataInputStream(new BufferedInputStream(res.getObjectContent()))) { return Optional.of(Serialize.readFully(din)); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { readTimer.observeDuration(); } }, e -> Optional.empty()); if (fromS3.isPresent()) return Futures.of(fromS3); return p2pFallback.getRaw(hash); } @Override public CompletableFuture<List<Multihash>> pinUpdate(PublicKeyHash owner, Multihash existing, Multihash updated) { return Futures.of(Collections.singletonList(updated)); } @Override public CompletableFuture<List<Multihash>> recursivePin(PublicKeyHash owner, Multihash hash) { return Futures.of(Collections.singletonList(hash)); } @Override public CompletableFuture<List<Multihash>> recursiveUnpin(PublicKeyHash owner, Multihash hash) { return Futures.of(Collections.singletonList(hash)); } @Override public CompletableFuture<Boolean> gc() { return Futures.errored(new IllegalStateException("S3 doesn't implement GC!")); } /** The result of this method is a snapshot of the mutable pointers that is consistent with the blocks store * after GC has completed (saved to a file which can be independently backed up). * * @param pointers * @return */ private void collectGarbage(JdbcIpnsAndSocial pointers) throws IOException { // TODO: do this more efficiently with a bloom filter, and streaming List<Multihash> present = getFiles(Integer.MAX_VALUE); List<Multihash> pending = transactions.getOpenTransactionBlocks(); // This pointers call must happen AFTER the previous two for correctness Map<PublicKeyHash, byte[]> allPointers = pointers.getAllEntries(); BitSet reachable = new BitSet(present.size()); for (PublicKeyHash writerHash : allPointers.keySet()) { byte[] signedRawCas = allPointers.get(writerHash); PublicSigningKey writer = getSigningKey(writerHash).join().get(); byte[] bothHashes = writer.unsignMessage(signedRawCas); HashCasPair cas = HashCasPair.fromCbor(CborObject.fromByteArray(bothHashes)); MaybeMultihash updated = cas.updated; if (updated.isPresent()) markReachable(updated.get(), present, reachable); } for (Multihash additional : pending) { int index = present.indexOf(additional); if (index >= 0) reachable.set(index); } // Save pointers snapshot to file Path pointerSnapshotFile = Paths.get("pointers-snapshot-" + LocalDateTime.now() + ".txt"); for (Map.Entry<PublicKeyHash, byte[]> entry : allPointers.entrySet()) { Files.write(pointerSnapshotFile, (entry.getKey() + ":" + ArrayOps.bytesToHex(entry.getValue()) + "\n").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); } long deletedBlocks = 0; long deletedSize = 0; for (int i=0; i < present.size(); i++) if (! reachable.get(i)) { Multihash hash = present.get(i); int size = getSize(hash).join().get(); deletedBlocks++; deletedSize += size; delete(hash); } System.out.println("GC complete. Freed " + deletedBlocks + " blocks totalling " + deletedSize + " bytes"); } private void markReachable(Multihash root, List<Multihash> present, BitSet reachable) { int index = present.indexOf(root); if (index >= 0) reachable.set(index); List<Multihash> links = getLinks(root).join(); for (Multihash link : links) { markReachable(link, present, reachable); } } @Override public CompletableFuture<Optional<Integer>> getSize(Multihash hash) { return Futures.of(map(hash, h -> { if (hash.isIdentity()) // Identity hashes are not actually stored explicitly return Optional.of(0); Histogram.Timer readTimer = readTimerLog.labels("size").startTimer(); try { ObjectMetadata res = s3Client.getObjectMetadata(bucket, folder + hashToKey(hash)); return Optional.of((int)res.getContentLength()); } finally { readTimer.observeDuration(); } }, e -> Optional.empty())); } public boolean contains(Multihash key) { return map(key, h -> s3Client.doesObjectExist(bucket, folder + hashToKey(h)), e -> false); } public <T> T map(Multihash hash, Function<Multihash, T> success, Function<Throwable, T> absent) { try { return success.apply(hash); } catch (AmazonServiceException e) { /* Caught an AmazonServiceException, which means our request made it to Amazon S3, but was rejected with an error response for some reason. */ if ("NoSuchKey".equals(e.getErrorCode())) { Histogram.Timer readTimer = readTimerLog.labels("absent").startTimer(); readTimer.observeDuration(); return absent.apply(e); } LOG.warning("AmazonServiceException: " + e.getMessage()); LOG.warning("AWS Error Code: " + e.getErrorCode()); throw new RuntimeException(e.getMessage(), e); } catch (AmazonClientException e) { /* Caught an AmazonClientException, which means the client encountered an internal error while trying to communicate with S3, such as not being able to access the network. */ LOG.severe("AmazonClientException: " + e.getMessage()); LOG.severe("Thrown at:" + e.getCause().toString()); throw new RuntimeException(e.getMessage(), e); } } @Override public CompletableFuture<Multihash> id() { return Futures.of(id); } @Override public CompletableFuture<TransactionId> startTransaction(PublicKeyHash owner) { return CompletableFuture.completedFuture(transactions.startTransaction(owner)); } @Override public CompletableFuture<Boolean> closeTransaction(PublicKeyHash owner, TransactionId tid) { transactions.closeTransaction(owner, tid); return CompletableFuture.completedFuture(true); } @Override public CompletableFuture<List<Multihash>> put(PublicKeyHash owner, PublicKeyHash writer, List<byte[]> signatures, List<byte[]> blocks, TransactionId tid) { return put(owner, writer, signatures, blocks, false, tid); } @Override public CompletableFuture<List<Multihash>> putRaw(PublicKeyHash owner, PublicKeyHash writer, List<byte[]> signatures, List<byte[]> blocks, TransactionId tid) { return put(owner, writer, signatures, blocks, true, tid); } private CompletableFuture<List<Multihash>> put(PublicKeyHash owner, PublicKeyHash writer, List<byte[]> signatures, List<byte[]> blocks, boolean isRaw, TransactionId tid) { return CompletableFuture.completedFuture(blocks.stream() .map(b -> put(b, isRaw, tid, owner)) .collect(Collectors.toList())); } /** Must be atomic relative to reads of the same key * * @param data */ public Multihash put(byte[] data, boolean isRaw, TransactionId tid, PublicKeyHash owner) { Histogram.Timer writeTimer = writeTimerLog.labels("write").startTimer(); Multihash hash = new Multihash(Multihash.Type.sha2_256, Hash.sha256(data)); Cid cid = new Cid(1, isRaw ? Cid.Codec.Raw : Cid.Codec.DagCbor, hash.type, hash.getHash()); String key = hashToKey(cid); try { ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(data.length); PutObjectRequest put = new PutObjectRequest(bucket, folder + key, new ByteArrayInputStream(data), metadata); transactions.addBlock(cid, tid, owner); PutObjectResult putResult = s3Client.putObject(put); return cid; } catch (AmazonServiceException e) { /* Caught an AmazonServiceException, which means our request made it to Amazon S3, but was rejected with an error response for some reason. */ LOG.severe("AmazonServiceException: " + e.getMessage() + " for " + key); LOG.severe("AWS Error Code: " + e.getErrorCode()); throw new RuntimeException(e.getMessage(), e); } catch (AmazonClientException e) { /* Caught an AmazonClientException, which means the client encountered an internal error while trying to communicate with S3, such as not being able to access the network. */ LOG.severe("AmazonClientException: " + e.getMessage()); LOG.severe("Thrown at:" + e.getCause().toString()); throw new RuntimeException(e.getMessage(), e); } finally { writeTimer.observeDuration(); } } private List<Multihash> getFiles(long maxReturned) { List<Multihash> results = new ArrayList<>(); applyToAll(obj -> { try { results.add(keyToHash(obj.getKey())); } catch (Exception e) { LOG.warning("Couldn't parse S3 key to Cid: " + obj.getKey()); } }, maxReturned); return results; } private List<String> getFilenames(long maxReturned) { List<String> results = new ArrayList<>(); applyToAll(obj -> results.add(obj.getKey()), maxReturned); return results; } private void applyToAll(Consumer<S3ObjectSummary> processor, long maxObjects) { try { LOG.log(Level.FINE, "Listing blobs"); final ListObjectsV2Request req = new ListObjectsV2Request() .withBucketName(bucket) .withPrefix(folder) .withMaxKeys(10_000); ListObjectsV2Result result; long processedObjects = 0; do { result = s3Client.listObjectsV2(req); for (S3ObjectSummary objectSummary : result.getObjectSummaries()) { if (objectSummary.getKey().endsWith("/")) { LOG.fine(" - " + objectSummary.getKey() + " " + "(directory)"); continue; } LOG.fine(" - " + objectSummary.getKey() + " " + "(size = " + objectSummary.getSize() + "; modified: " + objectSummary.getLastModified() + ")"); processor.accept(objectSummary); processedObjects++; if (processedObjects >= maxObjects) return; } LOG.log(Level.FINE, "Next Continuation Token : " + result.getNextContinuationToken()); req.setContinuationToken(result.getNextContinuationToken()); } while (result.isTruncated()); } catch (AmazonServiceException ase) { /* Caught an AmazonServiceException, which means our request made it to Amazon S3, but was rejected with an error response for some reason. */ LOG.severe("AmazonServiceException: " + ase.getMessage()); LOG.severe("AWS Error Code: " + ase.getErrorCode()); } catch (AmazonClientException ace) { /* Caught an AmazonClientException, which means the client encountered an internal error while trying to communicate with S3, such as not being able to access the network. */ LOG.severe("AmazonClientException: " + ace.getMessage()); LOG.severe("Thrown at:" + ace.getCause().toString()); } } public void delete(Multihash hash) { DeleteObjectRequest del = new DeleteObjectRequest(bucket, folder + hashToKey(hash)); s3Client.deleteObject(del); } public static void main(String[] args) throws Exception { System.out.println("Performing GC on block store..."); Args a = Args.parse(args); S3Config config = S3Config.build(a); boolean usePostgres = a.getBoolean("use-postgres", false); SqlSupplier sqlCommands = usePostgres ? new PostgresCommands() : new SqliteCommands(); Supplier<Connection> database = Main.getDBConnector(a, "mutable-pointers-file"); Supplier<Connection> transactionsDb = Main.getDBConnector(a, "transactions-sql-file"); TransactionStore transactions = JdbcTransactionStore.build(transactionsDb, sqlCommands); S3BlockStorage s3 = new S3BlockStorage(config, Cid.decode(a.getArg("ipfs.id")), transactions, new RAMStorage()); JdbcIpnsAndSocial rawPointers = new JdbcIpnsAndSocial(database, sqlCommands); s3.collectGarbage(rawPointers); } public static void test(String[] args) throws Exception { // Use this method to test access to a bucket S3Config config = S3Config.build(Args.parse(args)); System.out.println("Testing S3 bucket: " + config.bucket + " in region " + config.region + " with base dir: " + config.path); Multihash id = new Multihash(Multihash.Type.sha2_256, RAMStorage.hash("S3Storage".getBytes())); TransactionStore transactions = JdbcTransactionStore.build(Main.buildEphemeralSqlite(), new SqliteCommands()); S3BlockStorage s3 = new S3BlockStorage(config, id, transactions, new RAMStorage()); System.out.println("***** Testing ls and read"); System.out.println("Testing ls..."); List<Multihash> files = s3.getFiles(1000); System.out.println("Success! found " + files.size()); System.out.println("Testing read..."); byte[] data = s3.getRaw(files.get(0)).join().get(); System.out.println("Success: read blob of size " + data.length); System.out.println("Testing write..."); byte[] uploadData = new byte[10 * 1024]; new Random().nextBytes(uploadData); PublicKeyHash owner = PublicKeyHash.NULL; TransactionId tid = s3.startTransaction(owner).join(); Multihash put = s3.put(uploadData, true, tid, owner); System.out.println("Success!"); System.out.println("Testing delete..."); s3.delete(put); System.out.println("Success!"); } @Override public String toString() { return "S3BlockStore[" + bucket + ":" + folder + "]"; } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Random; import javax.swing.*; import javax.swing.plaf.basic.BasicProgressBarUI; public final class MainPanel extends JPanel implements HierarchyListener { private transient SwingWorker<String, Void> worker; private MainPanel() { super(new BorderLayout()); UIManager.put("ProgressBar.cycleTime", 1000); UIManager.put("ProgressBar.repaintInterval", 10); BoundedRangeModel model = new DefaultBoundedRangeModel(); JProgressBar progress1 = new JProgressBar(model); progress1.setUI(new StripedProgressBarUI(true, true)); JProgressBar progress2 = new JProgressBar(model); progress2.setUI(new StripedProgressBarUI(true, false)); JProgressBar progress3 = new JProgressBar(model); progress3.setUI(new StripedProgressBarUI(false, true)); JProgressBar progress4 = new JProgressBar(model); progress4.setUI(new StripedProgressBarUI(false, false)); List<JProgressBar> list = Arrays.asList(new JProgressBar(model), progress1, progress2, progress3, progress4); JPanel p = new JPanel(new GridLayout(5, 1)); list.forEach(bar -> p.add(makePanel(bar))); JButton button = new JButton("Test start"); button.addActionListener(e -> { if (Objects.nonNull(worker) && !worker.isDone()) { worker.cancel(true); } worker = new BackgroundTask(); list.forEach(bar -> { bar.setIndeterminate(true); worker.addPropertyChangeListener(new ProgressListener(bar)); }); worker.execute(); }); Box box = Box.createHorizontalBox(); box.add(Box.createHorizontalGlue()); box.add(button); box.add(Box.createHorizontalStrut(5)); addHierarchyListener(this); add(p); add(box, BorderLayout.SOUTH); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setPreferredSize(new Dimension(320, 240)); } @Override public void hierarchyChanged(HierarchyEvent e) { boolean displayability = (e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0; if (displayability && !e.getComponent().isDisplayable() && Objects.nonNull(worker)) { System.out.println("DISPOSE_ON_CLOSE"); worker.cancel(true); // worker = null; } } private static Component makePanel(Component cmp) { GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(5, 5, 5, 5); c.weightx = 1d; JPanel p = new JPanel(new GridBagLayout()); p.add(cmp, c); return p; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class StripedProgressBarUI extends BasicProgressBarUI { private final boolean dir; private final boolean slope; protected StripedProgressBarUI(boolean dir, boolean slope) { super(); this.dir = dir; this.slope = slope; } @Override protected int getBoxLength(int availableLength, int otherDimension) { return availableLength; // (int) Math.round(availableLength / 6d); } @Override public void paintIndeterminate(Graphics g, JComponent c) { // if (!(g instanceof Graphics2D)) { // return; Insets b = progressBar.getInsets(); // area for border int barRectWidth = progressBar.getWidth() - b.right - b.left; int barRectHeight = progressBar.getHeight() - b.top - b.bottom; if (barRectWidth <= 0 || barRectHeight <= 0) { return; } // Paint the striped box. boxRect = getBox(boxRect); if (Objects.nonNull(boxRect)) { int w = 10; int x = getAnimationIndex(); Shape p = makeIndeterminateBox(w); Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(progressBar.getForeground()); if (slope) { for (int i = boxRect.width + x; i > -w; i -= w) { g2.fill(AffineTransform.getTranslateInstance(i, 0).createTransformedShape(p)); } } else { for (int i = -x; i < boxRect.width; i += w) { g2.fill(AffineTransform.getTranslateInstance(i, 0).createTransformedShape(p)); } } g2.dispose(); } } private Shape makeIndeterminateBox(int w) { GeneralPath p = new GeneralPath(); if (dir) { p.moveTo(boxRect.x, boxRect.y); p.lineTo(boxRect.x + w * .5f, boxRect.getMaxY()); p.lineTo(boxRect.x + (float) w, boxRect.getMaxY()); } else { p.moveTo(boxRect.x, boxRect.getMaxY()); p.lineTo(boxRect.x + w * .5f, boxRect.getMaxY()); p.lineTo(boxRect.x + (float) w, boxRect.y); } p.lineTo(boxRect.x + w * .5f, boxRect.y); p.closePath(); return p; } } class BackgroundTask extends SwingWorker<String, Void> { private final Random rnd = new Random(); @Override protected String doInBackground() throws InterruptedException { Thread.sleep(5000); int current = 0; int lengthOfTask = 100; int total = 0; while (current <= lengthOfTask && !isCancelled()) { total += doSomething(); setProgress(100 * current++ / lengthOfTask); } return String.format("Done(%dms)", total); } protected int doSomething() throws InterruptedException { int iv = rnd.nextInt(50) + 1; Thread.sleep(iv); return iv; } } class ProgressListener implements PropertyChangeListener { private final JProgressBar progressBar; protected ProgressListener(JProgressBar progressBar) { this.progressBar = progressBar; this.progressBar.setValue(0); } @Override public void propertyChange(PropertyChangeEvent e) { String strPropertyName = e.getPropertyName(); if ("progress".equals(strPropertyName)) { progressBar.setIndeterminate(false); int progress = (Integer) e.getNewValue(); progressBar.setValue(progress); } } }
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Compiler { private final static Pattern relation_pattern = Pattern.compile("(.+)(>|<|>=|<=|==|!=)+(.+)"); private final static String operators = "+-*/()"; private final static Pattern expression_pattern = Pattern.compile("([a-zA-Z0-9" + operators + "]+)"); Scanner scanner; int[] memory; ArrayList<Integer> constants; HashMap<Integer, Integer> line_numbers; HashMap<String, Integer> variables; int last_line_number, pointer, data_pointer; public Compiler(File file) throws FileNotFoundException { scanner = new Scanner(file); memory = new int[100]; constants = new ArrayList<Integer>(); line_numbers = new HashMap<Integer, Integer>(); variables = new HashMap<String, Integer>(); last_line_number = 0; pointer = 0; data_pointer = 99; } public int[] compile() throws OutOfMemoryException, LineNumberException, InvalidVariableException, UndefinedVaribleException, IllegalArgumentException { while(scanner.hasNextLine()) { if(pointer >= data_pointer) throw new OutOfMemoryException(); String[] command = scanner.nextLine().split(" "); //Everything is separated by spaces //Double check line numbers and save each one as a symbol int line_number = Integer.parseInt(command[0]); if(line_number <= last_line_number) throw new LineNumberException(); line_numbers.put(line_number, pointer); last_line_number = line_number; if(command[1].equalsIgnoreCase("rem")) //Ignore comment lines continue; else if(command[1].equalsIgnoreCase("input")) { //Make a new variable and remember it if(!Character.isLetter(command[2].charAt(0))) throw new InvalidVariableException(); variables.put(command[2], data_pointer); memory[pointer] = 1000 + data_pointer; data_pointer } else if(command[1].equalsIgnoreCase("print")) { //Simply print variable if(!variables.containsKey(command[2])) throw new UndefinedVariableException(); memory[pointer] = 1100 + variables.get(command[2]); } else if(command[1].equalsIgnoreCase("let")) { //If a variable doesn't exist, create it then parse the expression String[] params = command[2].split("=", 1); if(params.length < 2) throw new SyntaxException(); if(!Character.isLetter(params[0].charAt(0))) throw new InvalidVariableException(); if(!variables.containsKey(params[0])) { variables.put(params[0], data_pointer); data_pointer } parseExpression(params[1], variables.get(params[0])); } else if(command[1].equalsIgnoreCase("goto")) { //Put a new goto memory[pointer] = 4000 + Integer.parseInt(command[2]); } else if(command[1].equalsIgnoreCase("if")) { //Yay for if's if(!command[3].equalsIgnoreCase("goto")) throw new IllegalArgumentException(); parseRelation(command[2], Integer.parseInt(command[4])); //Call parse relation } else if(command[1].equalsIgnoreCase("end")) //Put a halt memory[pointer] = 4300; pointer++; } } private void parseRelation(String relation, int goto_symbol) throws SyntaxException { //Check relations based on regexes Matcher matcher = relation_pattern.matcher(relation); if(!matcher.matches()) throw new SyntaxException(); parseExpression(matcher.group(1), data_pointer); data_pointer parseExpression(matcher.group(3), data_pointer); memory[pointer] = 2000 + data_pointer; pointer++; if(matcher.group(2).charAt(0) == '>') { memory[pointer] = 3100 + data_pointer + 1; //First number pointer++; memory[pointer] = 4200 + goto_symbol; //Branch negative to "goto" if(matcher.group(2).charAt(1) == '=') { pointer++; memory[pointer] = 4100 + goto_symbol; //Also branch zero if equal to } } else if(matcher.group(2).charAt(0) == '<') { memory[pointer - 1] = 2000 + data_pointer + 1; memory[pointer] = 3100 + data_pointer; pointer++; memory[pointer] = 4200 + goto_symbol; if(matcher.group(2).charAt(1) == '=') { pointer++; memory[pointer] = 4100 + goto_symbol; } } else if(matcher.group(2).equals("==")) { memory[pointer] = 3100 + data_pointer + 1; pointer++; memory[pointer] = 4100 + goto_symbol; } else if(matcher.group(2).equals("!=")) { if(!constants.contains(-1)) constants.add(-1); memory[pointer] = 3100 + data_pointer + 1; pointer++; memory[pointer] = 4200 + goto_symbol; pointer++; memory[pointer] = 3300 + constants.indexOf(-1); pointer++; memory[pointer] = 4200 + goto_symbol; } pointer++; data_pointer } private void parseExpression(String expression, int value_pointer) throws SyntaxException, NumberFormatException { //Check expressions based on regexes Matcher matcher = expression_pattern.matcher(expression); if(!matcher.matches()) throw new SyntaxException(); ArrayList<String> postfix = convertToPostfix(expression); int temp_data_pointer = data_pointer; for(int i = 0; i < postfix.size(); i++) { int operator = operators.indexOf(postfix[i].charAt(0)); if(operator != -1) { if(temp_data_pointer < pointer) { //You dun goofed! } int operand; if(Character.isLetter(postfix[i - 1].charAt(0))) { if(!variables.containsKey(postfix[i - 1])) { variables.put(postfix[i - 1], data_pointer); data_pointer } operand = variables.get(postfix[i - 1]); } else { int number = Integer.parseInt(postfix[i - 1]); if(!constants.contains(number)) constants.add(number); operand = constants.indexOf(number); } int load; if(operators.indexOf(postfix[i - 1].charAt(0)) != -1) { operand = temp_data_pointer; temp_data_pointer++; } else if(Character.isLetter(postfix[i - 2].charAt(0))) { if(!variables.containsKey(postfix[i - 2])) { variables.put(postfix[i - 2], data_pointer); data_pointer } load = variables.get(postfix[i - 2]); } else { int number = Integer.parseInt(postfix[i - 2]); if(!constants.contains(number)) constants.add(number); load = constants.indexOf(number); } memory[pointer] = 2000 + load; pointer++; switch(operator) { case 0: memory[pointer] = 3000 + operand; break; case 1: memory[pointer] = 3100 + operand; break; case 2: memory[pointer] = 3200 + operand; break; case 3: memory[pointer] = 3300 + operand; break; default: //You dun goofed! } pointer++; memory[pointer] = 2100 + temp_data_pointer; pointer++; temp_data_pointer } } } private ArrayList<String> convertToPostfix(String infix) { ArrayList<String> postfix = new ArrayList<String>(); Stack<Character> processStack = new Stack<Character>(); char[] chars = infix.toCharArray(); for(int i = 0; i < chars.length; i++) { String term = new String(); while(operators.indexOf(chars[i]) == -1) { term += chars[i]; i++; } postfix.add(term); if(processStack.empty()) { processStack.push(chars[i]); } else { while(operators.indexOf(chars[i]) <= operators.indexOf(processStack.peek())) { postfix.add(Character.toString(processStack.pop())); } processStack.push(chars[i]); } } return postfix; } }
package testing; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import enums.Color; import enums.Number; import enums.Shading; import enums.Shape; import setGame.Board; import setGame.Card; import setGame.Deck; import setGame.Game; public class GameTest { @Before public void setUp() throws Exception { } @Test public void initGameTest() { Game game = new Game(); assertFalse(game.getDeck().isEmpty()); assertTrue(game.getBoard().isEmpty()); } @Test public void initGameWithDeckTest() { Card card1 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.ONE); Card card2 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.TWO); Card card3 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.THREE); Card card4 = new Card(Color.RED, Shape.SQUIGGLE, Shading.EMPTY, Number.ONE); Card card5 = new Card(Color.RED, Shape.SQUIGGLE, Shading.STRIPED, Number.ONE); Card card6 = new Card(Color.RED, Shape.DIAMOND, Shading.SOLID, Number.ONE); Card card7 = new Card(Color.RED, Shape.OVAL, Shading.SOLID, Number.ONE); Card[] cards = new Card[] { card1, card2, card3, card4, card5, card6, card7 }; Game game = new Game(new Deck(cards), new Board()); assertArrayEquals((Object[]) cards, game.getBoard().toArray()); assertFalse(game.getDeck().isEmpty()); } @Test public void initGameWithBoardTest() { Card card1 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.ONE); Card card2 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.TWO); Card card3 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.THREE); Card card4 = new Card(Color.RED, Shape.SQUIGGLE, Shading.EMPTY, Number.ONE); Card card5 = new Card(Color.RED, Shape.SQUIGGLE, Shading.STRIPED, Number.ONE); Card card6 = new Card(Color.RED, Shape.DIAMOND, Shading.SOLID, Number.ONE); Card card7 = new Card(Color.RED, Shape.OVAL, Shading.SOLID, Number.ONE); Card[] cards = new Card[] { card1, card2, card3, card4, card5, card6, card7 }; Game game = new Game(new Deck(), new Board(cards)); assertArrayEquals((Object[]) cards, game.getBoard().toArray()); assertFalse(game.getDeck().isEmpty()); } @Test public void PlaythroughTest1() { fail("Not yet implemented"); } @Test public void PlaythroughTest2() { fail("Not yet implemented"); } @Test public void PlaythroughTest3() { fail("Not yet implemented"); } }
package edu.duke.cabig.c3pr.dao; import java.util.List; import edu.duke.cabig.c3pr.domain.DiseaseTerm; /** * @author Krikor Krumlian */ public class DiseaseTermDao extends GridIdentifiableDao<DiseaseTerm> { public Class<DiseaseTerm> domainClass() { return DiseaseTerm.class; } @SuppressWarnings("unchecked") public List<DiseaseTerm> getByCategoryId(Integer parentId) { return getHibernateTemplate().find("from DiseaseTerm dt where dt.category.id =?", new Object[] { parentId }); } /* * Primarily created for Generating test reports. */ @SuppressWarnings("unchecked") public List<DiseaseTerm> getByCtepTerm(String ctepTerm) { return getHibernateTemplate().find("from DiseaseTerm dt where dt.ctepTerm =?", ctepTerm); } }
package org.openforis.collect.manager; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openforis.collect.Collect; import org.openforis.collect.datacleansing.manager.SurveyDataCleansingManager; import org.openforis.collect.event.EventQueue; import org.openforis.collect.event.SurveyUpdatedEvent; import org.openforis.collect.io.exception.CodeListImportException; import org.openforis.collect.manager.exception.SurveyValidationException; import org.openforis.collect.manager.process.ProcessStatus; import org.openforis.collect.manager.validation.RecordValidationProcess; import org.openforis.collect.manager.validation.SurveyValidator; import org.openforis.collect.model.CollectSurvey; import org.openforis.collect.model.CollectSurveyContext; import org.openforis.collect.model.SurveyFile; import org.openforis.collect.model.SurveySummary; import org.openforis.collect.model.User; import org.openforis.collect.persistence.RecordDao; import org.openforis.collect.persistence.SurveyDao; import org.openforis.collect.persistence.SurveyFileDao; import org.openforis.collect.persistence.SurveyImportException; import org.openforis.collect.persistence.SurveyStoreException; import org.openforis.collect.persistence.xml.CollectSurveyIdmlBinder; import org.openforis.collect.utils.ExecutorServiceUtil; import org.openforis.commons.collection.CollectionUtils; import org.openforis.commons.io.OpenForisIOUtils; import org.openforis.idm.metamodel.CodeList; import org.openforis.idm.metamodel.ModelVersion; import org.openforis.idm.metamodel.Survey; import org.openforis.idm.metamodel.xml.IdmlParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * @author M. Togna * @author S. Ricci * */ @Transactional(readOnly=true, propagation=Propagation.SUPPORTS) public class SurveyManager { private static Log LOG = LogFactory.getLog(SurveyManager.class); private static final String URI_PREFIX = "http: @Autowired private CodeListManager codeListManager; @Autowired private SamplingDesignManager samplingDesignManager; @Autowired private SpeciesManager speciesManager; @Autowired private SurveyFileDao surveyFileDao; @Autowired private SurveyDao surveyDao; @Autowired private RecordDao recordDao; @Autowired private CollectSurveyContext collectSurveyContext; @Autowired private SurveyValidator surveyValidator; @Autowired private ApplicationContext applicationContext; @Autowired private CollectSurveyIdmlBinder surveySerializer; @Autowired(required=false) private EventQueue eventQueue; @Autowired(required=false) private SurveyDataCleansingManager dataCleansingManager; private List<CollectSurvey> surveys; private Map<Integer, CollectSurvey> surveysById; private Map<String, CollectSurvey> surveysByName; private Map<String, CollectSurvey> surveysByUri; private Map<Integer, ProcessStatus> recordValidationStatusBySurvey; public SurveyManager() { surveys = new ArrayList<CollectSurvey>(); surveysById = new HashMap<Integer, CollectSurvey>(); surveysByName = new HashMap<String, CollectSurvey>(); surveysByUri = new HashMap<String, CollectSurvey>(); recordValidationStatusBySurvey = Collections.synchronizedMap(new HashMap<Integer, ProcessStatus>()); } public void init() { initPublishedSurveysCache(); } protected void initPublishedSurveysCache() { surveysById.clear(); surveysByName.clear(); surveysByUri.clear(); surveys = surveyDao.loadAllPublished(); for (CollectSurvey survey : surveys) { addToCache(survey); } } private void addToCache(CollectSurvey survey) { if ( ! surveys.contains(survey) ) { surveys.add(survey); } surveysById.put(survey.getId(), survey); surveysByName.put(survey.getName(), survey); surveysByUri.put(survey.getUri(), survey); } protected void removeFromCache(CollectSurvey survey) { surveys.remove(survey); surveysById.remove(survey.getId()); surveysByName.remove(survey.getName()); surveysByUri.remove(survey.getUri()); } public List<CollectSurvey> getAll() { return CollectionUtils.unmodifiableList(surveys); } public CollectSurvey get(String name) { CollectSurvey survey = surveysByName.get(name); return survey; } public CollectSurvey getById(int id) { CollectSurvey survey = surveysById.get(id); return survey; } public CollectSurvey getByUri(String uri) { CollectSurvey survey = surveysByUri.get(uri); return survey; } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey importTemporaryModel(InputStream is, String name, boolean validate) throws SurveyImportException, SurveyValidationException { File tempFile = null; try { tempFile = OpenForisIOUtils.copyToTempFile(is); return importTemporaryModel(tempFile, name, validate); } finally { if ( tempFile != null && tempFile.exists() ) { tempFile.delete(); } } } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey importTemporaryModel(File surveyFile, String name, boolean validate) throws SurveyImportException, SurveyValidationException { try { CollectSurvey survey = unmarshalSurvey(surveyFile, validate, false); survey.setName(name); survey.setTemporary(true); surveyDao.insert(survey); codeListManager.importCodeLists(survey, surveyFile); return survey; } catch ( CodeListImportException e ) { throw new SurveyImportException(e); } catch (IdmlParseException e) { throw new SurveyImportException(e); } } /** * Duplicates a published survey into a temporary survey and import the survey file into this new temporary survey */ @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey importInPublishedTemporaryModel(String uri, File surveyFile, boolean validate) throws SurveyStoreException, SurveyValidationException { createTemporarySurveyFromPublished(uri); CollectSurvey newTemporarySurvey = updateTemporaryModel(surveyFile, validate); return newTemporarySurvey; } /** * Imports a survey from a XML file input stream and publishes it. */ @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey importModel(InputStream is, String name, boolean validate) throws SurveyImportException, SurveyValidationException { File tempFile = null; try { tempFile = OpenForisIOUtils.copyToTempFile(is); return importModel(tempFile, name, validate); } finally { if ( tempFile != null && tempFile.exists() ) { tempFile.delete(); } } } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey importModel(File surveyFile, String name, boolean validate) throws SurveyImportException, SurveyValidationException { return importModel(surveyFile, name, validate, false); } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey importModel(File surveyFile, String name, boolean validate, boolean includeCodeLists) throws SurveyImportException, SurveyValidationException { try { CollectSurvey survey = unmarshalSurvey(surveyFile, validate, includeCodeLists); survey.setName(name); survey.setPublished(true); surveyDao.insert(survey); addToCache(survey); codeListManager.importCodeLists(survey, surveyFile); return survey; } catch ( CodeListImportException e ) { throw new SurveyImportException(e); } catch (IdmlParseException e) { throw new SurveyImportException(e); } } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey updateModel(InputStream is, boolean validate) throws IdmlParseException, SurveyValidationException, SurveyImportException { File tempFile = OpenForisIOUtils.copyToTempFile(is); try { return updateModel(tempFile, validate); } finally { tempFile.delete(); } } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey updateModel(File surveyFile, boolean validate) throws SurveyValidationException, SurveyImportException { return updateModel(surveyFile, validate, false); } /** * Updates a published or a temporary survey and overwrites it with the specified one. * The existing survey will be searched by his URI. * If a temporary survey with the same URI as the survey in the surveyFile exists, * than it will be overwritten with the passed one, otherwise the published survey will be overwritten. */ @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey updateModel(File surveyFile, boolean validate, boolean includeCodeLists) throws SurveyValidationException, SurveyImportException { CollectSurvey parsedSurvey; try { parsedSurvey = unmarshalSurvey(surveyFile, validate, includeCodeLists); } catch (IdmlParseException e) { throw new SurveyImportException(e); } updateModel(surveyFile, parsedSurvey); return parsedSurvey; } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey updateModel(File surveyFile, CollectSurvey packagedSurvey) throws SurveyValidationException, SurveyImportException { String uri = packagedSurvey.getUri(); CollectSurvey oldPublishedSurvey = getByUri(uri); if ( oldPublishedSurvey == null ) { throw new IllegalArgumentException("Survey to update not found: " + uri); } Integer id = oldPublishedSurvey.getId(); packagedSurvey.setId(id); packagedSurvey.setName(oldPublishedSurvey.getName()); // if ( validate ) { // surveyValidator.checkCompatibility(oldPublishedSurvey1, packagedSurvey); codeListManager.deleteAllItemsBySurvey(id, false); removeFromCache(oldPublishedSurvey); surveyDao.update(packagedSurvey); addToCache(packagedSurvey); try { codeListManager.importCodeLists(packagedSurvey, surveyFile); } catch (CodeListImportException e) { throw new SurveyImportException(e); } return packagedSurvey; } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey updateTemporaryModel(File surveyFile, boolean validate) throws SurveyValidationException, SurveyStoreException { CollectSurvey parsedSurvey; try { parsedSurvey = unmarshalSurvey(surveyFile, validate, false); } catch (IdmlParseException e) { throw new SurveyImportException(e); } String uri = parsedSurvey.getUri(); SurveySummary oldTemporarySurvey = loadTemporarySummaryByUri(uri); if ( oldTemporarySurvey == null ) { throw new IllegalArgumentException("Survey to update not found: " + uri); } else { int oldSurveyId = oldTemporarySurvey.getId(); parsedSurvey.setId(oldSurveyId); parsedSurvey.setName(oldTemporarySurvey.getName()); parsedSurvey.setPublishedId(oldTemporarySurvey.getPublishedId()); parsedSurvey.setTemporary(true); //clean code list items for (CodeList codeList : parsedSurvey.getCodeLists()) { codeList.removeAllItems(); } codeListManager.deleteAllItemsBySurvey(oldSurveyId, true); save(parsedSurvey); //import code list items try { codeListManager.importCodeLists(parsedSurvey, surveyFile); } catch (CodeListImportException e) { throw new SurveyImportException(e); } } return parsedSurvey; } /** * Import a survey and consider it as published. * * @param survey * @throws SurveyImportException * @deprecated use {@link #importModel(File, String, boolean)} instead. */ @Transactional(readOnly=false, propagation=Propagation.SUPPORTS) @Deprecated public void importModel(CollectSurvey survey) throws SurveyImportException { surveyDao.insert(survey); addToCache(survey); } /** * Updates a published survey and overwrites it with the specified one. * The existing published survey will be searched by his URI. * * @param survey * @throws SurveyImportException * @deprecated Use {@link #updateModel(File, boolean)} instead. */ @Deprecated @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public void updateModel(CollectSurvey survey) throws SurveyImportException { //remove old survey from surveys cache CollectSurvey oldSurvey = get(survey.getName()); if ( oldSurvey != null ) { removeFromCache(oldSurvey); } else { throw new SurveyImportException("Could not find survey to update"); } surveyDao.update(survey); addToCache(survey); } public List<SurveySummary> getSurveySummaries(String lang) { List<SurveySummary> summaries = new ArrayList<SurveySummary>(); for (CollectSurvey survey : surveys) { SurveySummary summary = SurveySummary.createFromSurvey(survey, lang); if ( summary.isPublished() ) { int publishedSurveyId = summary.isTemporary() ? summary.getPublishedId(): summary.getId(); summary.setRecordValidationProcessStatus(getRecordValidationProcessStatus(publishedSurveyId)); } summaries.add(summary); } sortByName(summaries); return summaries; } public SurveySummary getPublishedSummaryByUri(String uri) { CollectSurvey survey = getByUri(uri); if ( survey == null ) { return null; } else { return SurveySummary.createFromSurvey(survey); } } public SurveySummary getPublishedSummaryByName(String name) { CollectSurvey survey = get(name); if ( survey == null ) { return null; } else { return SurveySummary.createFromSurvey(survey); } } protected void sortByName(List<SurveySummary> summaries) { Collections.sort(summaries, new Comparator<SurveySummary>() { @Override public int compare(SurveySummary s1, SurveySummary s2) { return s1.getName().compareTo(s2.getName()); } }); } public String marshalSurvey(Survey survey) { try { String result = surveyDao.marshalSurvey(survey); return result; } catch (SurveyImportException e) { throw new RuntimeException(e.getMessage(), e); } } public void marshalSurvey(Survey survey, OutputStream os) { marshalSurvey(survey, os, true, false, false); } public void marshalSurvey(Survey survey, OutputStream os, boolean marshalCodeLists, boolean marshalPersistedCodeLists, boolean marshalExternalCodeLists) { try { surveySerializer.marshal(survey, os, marshalCodeLists, marshalPersistedCodeLists, marshalExternalCodeLists); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } public CollectSurvey unmarshalSurvey(InputStream is) throws IdmlParseException, SurveyValidationException { return unmarshalSurvey(is, false, true); } public CollectSurvey unmarshalSurvey(File surveyFile, boolean validate, boolean includeCodeListItems) throws IdmlParseException, SurveyValidationException { try { return unmarshalSurvey(new FileInputStream(surveyFile), validate, includeCodeListItems); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public CollectSurvey unmarshalSurvey(InputStream is, boolean validate, boolean includeCodeListItems) throws IdmlParseException, SurveyValidationException { return unmarshalSurvey(OpenForisIOUtils.toReader(is), validate, includeCodeListItems); } public CollectSurvey unmarshalSurvey(Reader reader) throws IdmlParseException, SurveyValidationException { return unmarshalSurvey(reader, false, true); } public CollectSurvey unmarshalSurvey(Reader reader, boolean validate, boolean includeCodeListItems) throws IdmlParseException, SurveyValidationException { CollectSurvey survey; File tempFile = OpenForisIOUtils.copyToTempFile(reader); if ( validate ) { //validate against schema validateSurveyXMLAgainstSchema(tempFile); } survey = unmarshalSurvey(tempFile, includeCodeListItems); if ( validate ) { surveyValidator.validate(survey); } tempFile.delete(); return survey; } protected CollectSurvey unmarshalSurvey(File file, boolean includeCodeListItems) throws IdmlParseException { FileInputStream tempIs = null; try { tempIs = new FileInputStream(file); return surveyDao.unmarshalIdml(tempIs, includeCodeListItems); } catch (Exception e) { //should never enter here throw new RuntimeException(e); } finally { IOUtils.closeQuietly(tempIs); } } protected void validateSurveyXMLAgainstSchema(File file) throws SurveyValidationException { surveyValidator.validateAgainstSchema(file); } /** * Loads published and temporary survey summaries into a single list. * Survey details like project name will be read using survey default language. * * @return */ public List<SurveySummary> loadCombinedSummaries() { return loadCombinedSummaries(null, false); } /** * Loads published and temporary survey summaries into a single list. * * @param labelLang language code used to * @param includeDetails if true, survey info like project name will be included in the summary (it makes the loading process slower). * @return list of published and temporary surveys. */ public List<SurveySummary> loadCombinedSummaries(String labelLang, boolean includeDetails) { List<SurveySummary> publishedSurveySummaries = getSurveySummaries(labelLang); List<SurveySummary> temporarySurveySummaries = loadTemporarySummaries(labelLang, includeDetails); List<SurveySummary> result = new ArrayList<SurveySummary>(); Map<String, SurveySummary> summariesByUri = new HashMap<String, SurveySummary>(); for (SurveySummary summary : temporarySurveySummaries) { summary.setPublished(false); summary.setTemporary(true); result.add(summary); summariesByUri.put(summary.getUri(), summary); } for (SurveySummary publishedSurveySummary : publishedSurveySummaries) { SurveySummary temporarySurveySummary = summariesByUri.get(publishedSurveySummary.getUri()); if ( temporarySurveySummary == null ) { result.add(publishedSurveySummary); } else { temporarySurveySummary.setPublished(true); temporarySurveySummary.setRecordValidationProcessStatus(publishedSurveySummary.getRecordValidationProcessStatus()); } } sortByName(result); return result; } public SurveySummary loadSummaryByUri(String uri) { SurveySummary temporarySummary = loadTemporarySummaryByUri(uri); SurveySummary publishedSummary = getPublishedSummaryByUri(uri); SurveySummary result = combineSummaries(temporarySummary, publishedSummary); return result; } public SurveySummary loadSummaryByName(String name) { SurveySummary temporarySummary = loadTemporarySummaryByName(name); SurveySummary publishedSummary = getPublishedSummaryByName(name); SurveySummary result = combineSummaries(temporarySummary, publishedSummary); return result; } private SurveySummary combineSummaries(SurveySummary temporarySummary, SurveySummary publishedSummary) { SurveySummary result; if ( temporarySummary != null ) { result = temporarySummary; if ( publishedSummary != null ) { result.setPublished(true); result.setPublishedId(publishedSummary.getId()); } } else { result = publishedSummary; } return result; } public CollectSurvey loadSurvey(int id) { CollectSurvey survey = surveyDao.loadById(id); if ( survey != null ) { codeListManager.deleteInvalidCodeListReferenceItems(survey); survey.getUIOptions().removeUnassignedTabs(); if ( survey.getSamplingDesignCodeList() == null ) { survey.addSamplingDesignCodeList(); } } return survey; } public CollectSurvey getOrLoadSurveyById(int id) { CollectSurvey survey = getById(id); if (survey == null) { survey = loadSurvey(id); } return survey; } public List<SurveySummary> loadTemporarySummaries(String labelLang, boolean includeDetails) { List<SurveySummary> summaries = surveyDao.loadTemporarySummaries(); if ( includeDetails ) { for (SurveySummary summary : summaries) { CollectSurvey survey = surveyDao.loadById(summary.getId()); String projectName = survey.getProjectName(labelLang); if ( projectName == null && labelLang != null && ! labelLang.equals(survey.getDefaultLanguage()) ) { projectName = survey.getProjectName(); } summary.setProjectName(projectName); summary.setDefaultLanguage(survey.getDefaultLanguage()); summary.setLanguages(survey.getLanguages()); } } return summaries; } public SurveySummary loadTemporarySummaryByUri(String uri) { return surveyDao.loadSurveySummaryByUri(uri, true); } public SurveySummary loadTemporarySummaryByName(String name) { return surveyDao.loadSurveySummaryByName(name, true); } public boolean isSurveyTemporary(CollectSurvey survey) { Integer id = survey.getId(); String uri = survey.getUri(); SurveySummary temporarySurveySummary = loadTemporarySummaryByUri(uri); if (temporarySurveySummary == null || ! temporarySurveySummary.getId().equals(id) ) { CollectSurvey publishedSurvey = getByUri(uri); if (publishedSurvey == null || ! publishedSurvey.getId().equals(id) ) { throw new IllegalStateException("Survey with uri '" + uri + "' not found"); } else { return false; } } else { return true; } } public CollectSurvey createTemporarySurvey(String name, String language) { CollectSurvey survey = (CollectSurvey) collectSurveyContext.createSurvey(); survey.setName(name); survey.setUri(generateSurveyUri(name)); survey.addLanguage(language); survey.setTemporary(true); return survey; } public String generateSurveyUri(String name) { return URI_PREFIX + name; } public String generateRandomSurveyUri() { return generateSurveyUri(UUID.randomUUID().toString()); } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public void save(CollectSurvey survey) throws SurveyStoreException { survey.setModifiedDate(new Date()); survey.setCollectVersion(Collect.VERSION); Integer id = survey.getId(); if ( id == null ) { surveyDao.insert(survey); } else { surveyDao.update(survey); } } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey createTemporarySurveyFromPublished(String uri) { return createTemporarySurveyFromPublished(uri, true, true); } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey createTemporarySurveyFromPublished(String uri, boolean markCopyAsPublished, boolean preserveReferenceToPublishedSurvey) { try { SurveySummary existingTemporarySurvey = surveyDao.loadSurveySummaryByUri(uri, true); if ( existingTemporarySurvey != null ) { throw new IllegalArgumentException("Temporary survey with uri " + uri + " already existing"); } CollectSurvey publishedSurvey = surveyDao.loadByUri(uri, false); int publishedSurveyId = publishedSurvey.getId(); CollectSurvey temporarySurvey = publishedSurvey; //the published survey object should be cloned... temporarySurvey.setId(null); temporarySurvey.setPublished(markCopyAsPublished); temporarySurvey.setTemporary(true); temporarySurvey.setPublishedId(preserveReferenceToPublishedSurvey ? publishedSurveyId : null); if ( temporarySurvey.getSamplingDesignCodeList() == null ) { temporarySurvey.addSamplingDesignCodeList(); } surveyDao.insert(temporarySurvey); publishedSurvey = getByUri(uri); copyReferencedMetadata(publishedSurvey, temporarySurvey); return temporarySurvey; } catch (SurveyImportException e) { //it should never enter here, we are duplicating an already existing survey throw new RuntimeException(e); } } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey duplicateSurveyIntoTemporary(String originalSurveyName, boolean originalSurveyIsTemporary, String newName) { try { CollectSurvey oldSurvey = loadSurvey(originalSurveyName, originalSurveyIsTemporary); //TODO : clone it CollectSurvey newSurvey = oldSurvey; newSurvey.setId(null); newSurvey.setPublished(false); newSurvey.setTemporary(true); newSurvey.setPublishedId(null); newSurvey.setName(newName); newSurvey.setUri(generateSurveyUri(newName)); newSurvey.setCreationDate(new Date()); newSurvey.setModifiedDate(new Date()); if ( newSurvey.getSamplingDesignCodeList() == null ) { newSurvey.addSamplingDesignCodeList(); } surveyDao.insert(newSurvey); //reload old survey, it has been modified previously oldSurvey = loadSurvey(originalSurveyName, originalSurveyIsTemporary); copyReferencedMetadata(oldSurvey, newSurvey); return newSurvey; } catch (SurveyImportException e) { //it should never enter here, we are duplicating an already existing survey throw new RuntimeException(e); } } private void copyReferencedMetadata(CollectSurvey fromSurvey, CollectSurvey toSurvey) { int toSurveyId = toSurvey.getId(); int fromSurveyId = fromSurvey.getId(); samplingDesignManager.copySamplingDesign(fromSurveyId, toSurveyId); speciesManager.copyTaxonomy(fromSurveyId, toSurveyId); codeListManager.copyCodeLists(fromSurvey, toSurvey); surveyFileDao.copyItems(fromSurvey.getId(), toSurvey.getId()); if (dataCleansingManager != null) { dataCleansingManager.duplicateMetadata(fromSurvey, toSurvey); } } private CollectSurvey loadSurvey(String name, boolean temporary) { return surveyDao.loadByName(name, temporary); } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public void publish(CollectSurvey survey) throws SurveyImportException { codeListManager.deleteInvalidCodeListReferenceItems(survey); Integer temporarySurveyId = survey.getId(); Integer oldPublishedSurveyId = survey.getPublishedId(); boolean existsPublishedSurvey = oldPublishedSurveyId != null; if (existsPublishedSurvey) { cancelRecordValidation(oldPublishedSurveyId); survey.setId(oldPublishedSurveyId); } survey.setTemporary(false); survey.setPublished(true); survey.setPublishedId(null); survey.setModifiedDate(new Date()); survey.setCollectVersion(Collect.VERSION); surveyDao.update(survey); int newSurveyId = survey.getId(); if (newSurveyId != temporarySurveyId) { if (dataCleansingManager != null) { //do not overwrite published cleansing metadata CollectSurvey temporarySurvey = surveyDao.loadById(temporarySurveyId); dataCleansingManager.moveMetadata(temporarySurvey, survey); } samplingDesignManager.moveSamplingDesign(temporarySurveyId, newSurveyId); speciesManager.moveTaxonomies(temporarySurveyId, newSurveyId); codeListManager.moveCodeLists(temporarySurveyId, newSurveyId); surveyFileDao.deleteBySurvey(newSurveyId); surveyFileDao.moveItems(temporarySurveyId, newSurveyId); surveyDao.delete(temporarySurveyId); CollectSurvey oldPublishedSurvey = getById(oldPublishedSurveyId); if (oldPublishedSurvey != null) { removeFromCache(oldPublishedSurvey); } } addToCache(survey); if (eventQueue != null && eventQueue.isEnabled()) { eventQueue.publish(new SurveyUpdatedEvent(survey.getName())); } } /** * If no temporary survey is associated to the published one with the specified id, * it duplicates the published survey into a temporary one, then removes the published one. */ @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public CollectSurvey unpublish(int surveyId) throws SurveyStoreException { CollectSurvey publishedSurvey = getById(surveyId); String uri = publishedSurvey.getUri(); SurveySummary temporarySurveySummary = surveyDao.loadSurveySummaryByUri(uri, true); CollectSurvey temporarySurvey; if (temporarySurveySummary == null) { temporarySurvey = createTemporarySurveyFromPublished(uri, false, false); } else { temporarySurvey = loadSurvey(temporarySurveySummary.getId()); temporarySurvey.setPublished(false); temporarySurvey.setPublishedId(null); save(temporarySurvey); if (dataCleansingManager != null) { //overwrite temporary cleansing metadata with published one dataCleansingManager.moveMetadata(publishedSurvey, temporarySurvey); } } //delete published survey deleteSurvey(surveyId); return temporarySurvey; } public void cancelRecordValidation(int surveyId) { ProcessStatus status = getRecordValidationProcessStatus(surveyId); if ( status != null ) { status.cancel(); } } public void validateRecords(int surveyId, User user) { CollectSurvey survey = surveysById.get(surveyId); if ( survey == null ) { throw new IllegalStateException("Published survey not found, id="+surveyId); } ProcessStatus status = getRecordValidationProcessStatus(surveyId); if ( status != null && status.isRunning() ) { throw new IllegalStateException("Record validation process already started"); } else { RecordValidationProcess process = applicationContext.getBean(RecordValidationProcess.class); process.setSurvey(survey); process.setUser(user); UUID sessionId = UUID.randomUUID(); process.setSessionId(sessionId.toString()); try { process.init(); recordValidationStatusBySurvey.put(survey.getId(), process.getStatus()); ExecutorServiceUtil.executeInCachedPool(process); } catch (Exception e) { LOG.error("Error validating survey records", e); } } } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public void deleteSurvey(int id) { if ( isRecordValidationInProgress(id) ) { cancelRecordValidation(id); } CollectSurvey publishedSurvey = getById(id); boolean temporary = publishedSurvey == null; //delete records if ( ! temporary ) { recordDao.deleteBySurvey(id); } //delete metadata speciesManager.deleteTaxonomiesBySurvey(id); samplingDesignManager.deleteBySurvey(id); codeListManager.deleteAllItemsBySurvey(id, temporary); surveyFileDao.deleteBySurvey(id); if (dataCleansingManager != null) { CollectSurvey survey = loadSurvey(id); dataCleansingManager.deleteMetadata(survey); } //delete survey surveyDao.delete(id); if ( ! temporary ) { removeFromCache(publishedSurvey); } } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public void removeVersion(CollectSurvey survey, ModelVersion version) { survey.removeVersion(version); codeListManager.removeVersioningReference(survey, version); } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public void updateLanguages(CollectSurvey survey, List<String> newLanguageCodes) { codeListManager.updateSurveyLanguages(survey, newLanguageCodes); List<String> oldLangCodes = new ArrayList<String>(survey.getLanguages()); // remove languages from survey for (String oldLangCode : oldLangCodes) { if (! newLanguageCodes.contains(oldLangCode)) { survey.removeLanguage(oldLangCode); } } // add new languages for (String lang : newLanguageCodes) { if ( ! oldLangCodes.contains(lang) ) { survey.addLanguage(lang); } } // sort languages for (int i = 0; i < newLanguageCodes.size(); i++) { String lang = newLanguageCodes.get(i); survey.moveLanguage(lang, i); } } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public void addSurveyFile(CollectSurvey survey, SurveyFile file, File content) { try { surveyFileDao.insert(file); byte[] contentBytes = FileUtils.readFileToByteArray(content); surveyFileDao.updateContent(file, contentBytes); } catch(Exception e) { throw new RuntimeException(e); } } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public void updateSurveyFile(CollectSurvey survey, SurveyFile file, File content) { try { surveyFileDao.update(file); if (content != null) { byte[] contentBytes = FileUtils.readFileToByteArray(content); surveyFileDao.updateContent(file, contentBytes); } } catch(Exception e) { throw new RuntimeException(e); } } public byte[] loadSurveyFileContent(SurveyFile surveyFile) { return surveyFileDao.loadContent(surveyFile); } public List<SurveyFile> loadSurveyFileSummaries(CollectSurvey survey) { return surveyFileDao.loadBySurvey(survey); } public void deleteSurveyFile(SurveyFile surveyFile) { surveyFileDao.delete(surveyFile.getId()); } public void deleteSurveyFiles(CollectSurvey survey) { surveyFileDao.deleteBySurvey(survey.getId()); } protected ProcessStatus getRecordValidationProcessStatus(int surveyId) { ProcessStatus status = recordValidationStatusBySurvey.get(surveyId); return status; } public boolean isRecordValidationInProgress(int surveyId) { ProcessStatus status = getRecordValidationProcessStatus(surveyId); return status != null && status.isRunning(); } /* * Getters and setters * */ public SamplingDesignManager getSamplingDesignManager() { return samplingDesignManager; } public void setSamplingDesignManager(SamplingDesignManager samplingDesignManager) { this.samplingDesignManager = samplingDesignManager; } public SpeciesManager getSpeciesManager() { return speciesManager; } public void setSpeciesManager(SpeciesManager speciesManager) { this.speciesManager = speciesManager; } public SurveyDao getSurveyDao() { return surveyDao; } public void setSurveyDao(SurveyDao surveyDao) { this.surveyDao = surveyDao; } public CollectSurveyContext getCollectSurveyContext() { return collectSurveyContext; } public void setCollectSurveyContext(CollectSurveyContext collectSurveyContext) { this.collectSurveyContext = collectSurveyContext; } public CodeListManager getCodeListManager() { return codeListManager; } public void setCodeListManager(CodeListManager codeListManager) { this.codeListManager = codeListManager; } public SurveyValidator getSurveyValidator() { return surveyValidator; } public void setSurveyValidator(SurveyValidator validator) { this.surveyValidator = validator; } public CollectSurveyIdmlBinder getSurveySerializer() { return surveySerializer; } public void setSurveySerializer(CollectSurveyIdmlBinder surveySerializer) { this.surveySerializer = surveySerializer; } }
package com.orientechnologies.common.collection; import java.io.IOException; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.profiler.OProfiler; @SuppressWarnings("unchecked") public abstract class OTreeMap<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, Cloneable, java.io.Serializable { protected OTreeMapEventListener<K, V> listener; boolean pageItemFound = false; int pageItemComparator = 0; protected volatile int pageIndex = -1; protected int lastPageSize = 63; // PERSISTENT FIELDS /** * The number of entries in the tree */ protected int size = 0; // PERSISTENT FIELDS protected float pageLoadFactor = 0.7f; /** * The comparator used to maintain order in this tree map, or null if it uses the natural ordering of its keys. * * @serial */ private final Comparator<? super K> comparator; protected transient OTreeMapEntry<K, V> root = null; /** * The number of structural modifications to the tree. */ transient int modCount = 0; transient boolean runtimeCheckEnabled = false; public OTreeMap(final int iSize, final float iLoadFactor) { lastPageSize = iSize; pageLoadFactor = iLoadFactor; comparator = null; init(); } public OTreeMap(final OTreeMapEventListener<K, V> iListener) { init(); comparator = null; listener = iListener; } /** * Constructs a new, empty tree map, using the natural ordering of its keys. All keys inserted into the map must implement the * {@link Comparable} interface. Furthermore, all such keys must be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not * throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts to put a key into * the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers), * the <tt>put(Object key, Object value)</tt> call will throw a <tt>ClassCastException</tt>. */ public OTreeMap() { init(); comparator = null; } /** * Constructs a new, empty tree map, ordered according to the given comparator. All keys inserted into the map must be <i>mutually * comparable</i> by the given comparator: <tt>comparator.compare(k1, * k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts * to put a key into the map that violates this constraint, the <tt>put(Object * key, Object value)</tt> call will throw a <tt>ClassCastException</tt>. * * @param comparator * the comparator that will be used to order this map. If <tt>null</tt>, the {@linkplain Comparable natural ordering} of * the keys will be used. */ public OTreeMap(final Comparator<? super K> comparator) { init(); this.comparator = comparator; } /** * Constructs a new tree map containing the same mappings as the given map, ordered according to the <i>natural ordering</i> of * its keys. All keys inserted into the new map must implement the {@link Comparable} interface. Furthermore, all such keys must * be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> * and <tt>k2</tt> in the map. This method runs in n*log(n) time. * * @param m * the map whose mappings are to be placed in this map * @throws ClassCastException * if the keys in m are not {@link Comparable}, or are not mutually comparable * @throws NullPointerException * if the specified map is null */ public OTreeMap(final Map<? extends K, ? extends V> m) { init(); comparator = null; putAll(m); } /** * Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method * runs in linear time. * * @param m * the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort this map * @throws NullPointerException * if the specified map is null */ public OTreeMap(final SortedMap<K, ? extends V> m) { init(); comparator = m.comparator(); try { buildFromSorted(m.size(), m.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } /** * Create a new entry with the first key/value to handle. */ protected abstract OTreeMapEntry<K, V> createEntry(final K key, final V value); /** * Create a new node with the same parent of the node is splitting. */ protected abstract OTreeMapEntry<K, V> createEntry(final OTreeMapEntry<K, V> parent); public int getNodes() { int counter = -1; OTreeMapEntry<K, V> entry = getFirstEntry(); while (entry != null) { entry = successor(entry); counter++; } return counter; } /** * Returns the number of key-value mappings in this map. * * @return the number of key-value mappings in this map */ @Override public int size() { return size; } /** * Returns <tt>true</tt> if this map contains a mapping for the specified key. * * @param key * key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public boolean containsKey(final Object key) { OTreeMapEntry<K, V> entry = getEntry(key); return entry != null; } /** * Returns <tt>true</tt> if this map maps one or more keys to the specified value. More formally, returns <tt>true</tt> if and * only if this map contains at least one mapping to a value <tt>v</tt> such that * <tt>(value==null ? v==null : value.equals(v))</tt>. This operation will probably require time linear in the map size for most * implementations. * * @param value * value whose presence in this map is to be tested * @return <tt>true</tt> if a mapping to <tt>value</tt> exists; <tt>false</tt> otherwise * @since 1.2 */ @Override public boolean containsValue(final Object value) { for (OTreeMapEntry<K, V> e = getFirstEntry(); e != null; e = successor(e)) if (valEquals(value, e.getValue())) return true; return false; } /** * Returns the value to which the specified key is mapped, or {@code null} if this map contains no mapping for the key. * * <p> * More formally, if this map contains a mapping from a key {@code k} to a value {@code v} such that {@code key} compares equal to * {@code k} according to the map's ordering, then this method returns {@code v}; otherwise it returns {@code null}. (There can be * at most one such mapping.) * * <p> * A return value of {@code null} does not <i>necessarily</i> indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public V get(final Object key) { if (size == 0) return null; OTreeMapEntry<K, V> entry = getEntry(key); return entry == null ? null : entry.getValue(); } public Comparator<? super K> comparator() { return comparator; } /** * @throws NoSuchElementException * {@inheritDoc} */ public K firstKey() { return key(getFirstEntry()); } /** * @throws NoSuchElementException * {@inheritDoc} */ public K lastKey() { return key(getLastEntry()); } /** * Copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of * the keys currently in the specified map. * * @param map * mappings to be stored in this map * @throws ClassCastException * if the class of a key or value in the specified map prevents it from being stored in this map * @throws NullPointerException * if the specified map is null or the specified map contains a null key and this map does not permit null keys */ @Override public void putAll(final Map<? extends K, ? extends V> map) { int mapSize = map.size(); if (size == 0 && mapSize != 0 && map instanceof SortedMap) { Comparator<?> c = ((SortedMap<? extends K, ? extends V>) map).comparator(); if (c == comparator || (c != null && c.equals(comparator))) { ++modCount; try { buildFromSorted(mapSize, map.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return; } } super.putAll(map); } /** * Returns this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key. * * @return this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ final OTreeMapEntry<K, V> getEntry(final Object key) { return getEntry(key, false); } final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer) { if (key == null) return null; pageItemFound = false; // Off-load comparator-based version for sake of performance if (comparator != null) return getEntryUsingComparator(key, iGetContainer); OTreeMapEntry<K, V> p = getBestEntryPoint(key); // System.out.println("Best entry point for key " + key + " is: "+p); checkTreeStructure(p); if (p == null) return null; OTreeMapEntry<K, V> lastNode = p; OTreeMapEntry<K, V> prevNode = null; OTreeMapEntry<K, V> tmpNode; int beginKey = -1; int steps = -1; final Comparable<? super K> k = (Comparable<? super K>) key; // //System.out.println("Searching key " + key + "..."); try { while (p != null) { steps++; lastNode = p; try { beginKey = k.compareTo(p.getFirstKey()); } catch (Exception e) { } if (beginKey == 0) { // EXACT MATCH, YOU'RE VERY LUCKY: RETURN THE FIRST KEY WITHOUT SEARCH INSIDE THE NODE pageIndex = 0; pageItemFound = true; pageItemComparator = 0; return p; } pageItemComparator = k.compareTo(p.getLastKey()); if (beginKey < 0) { if (pageItemComparator < 0) { // System.out.println("-> Load predecessor of " + p + "..."); tmpNode = predecessor(p); // System.out.println("-> Loaded " + tmpNode); if (tmpNode != null && tmpNode != prevNode) { // MINOR THAN THE CURRENT: GET THE LEFT NODE // p = p.getLeft(); prevNode = p; p = tmpNode; continue; } } } else if (beginKey > 0) { if (pageItemComparator > 0) { // System.out.println("-> Load successor of " + p + "..."); tmpNode = successor(p); // System.out.println("-> Loaded " + tmpNode); if (tmpNode != null && tmpNode != prevNode) { // MAJOR THAN THE CURRENT: GET THE RIGHT NODE // p = p.getRight(); prevNode = p; p = tmpNode; continue; } } } // SEARCH INSIDE THE NODE final V value = lastNode.search(k); if (value != null || iGetContainer) // FOUND: RETURN CURRENT NODE OR AT LEAST THE CONTAINER NODE return lastNode; // NOT FOUND return null; } } finally { checkTreeStructure(p); OProfiler.getInstance().updateStat("[OTreeMap.getEntry] Steps of search", steps); } return null; } /** * Basic implementation that returns the root node. */ protected OTreeMapEntry<K, V> getBestEntryPoint(final Object key) { return root; } public OTreeMapEventListener<K, V> getListener() { return listener; } public void setListener(final OTreeMapEventListener<K, V> listener) { this.listener = listener; } /** * Version of getEntry using comparator. Split off from getEntry for performance. (This is not worth doing for most methods, that * are less dependent on comparator performance, but is worthwhile here.) * * @param iGetContainer */ final OTreeMapEntry<K, V> getEntryUsingComparator(final Object key, final boolean iGetContainer) { K k = (K) key; Comparator<? super K> cpr = comparator; if (cpr != null) { OTreeMapEntry<K, V> p = root; OTreeMapEntry<K, V> lastNode = null; while (p != null) { lastNode = p; int beginKey = cpr.compare(k, p.getFirstKey()); if (beginKey < 0) p = p.getLeft(); else if (beginKey > 0) { if (cpr.compare(k, p.getLastKey()) > 0) p = p.getRight(); else break; } else { pageIndex = 0; return p; } } if (lastNode != null) { // SEARCH INSIDE THE NODE for (int i = 1; i < lastNode.getSize(); ++i) { int cmp = cpr.compare(k, lastNode.getKey(i)); if (cmp == 0) { // FOUND: SET THE INDEX AND RETURN THE NODE lastNode.getValue(i); pageItemFound = true; return lastNode; } else if (cmp < 0) break; } if (iGetContainer) // RETURN THE CONTAINER NODE ANYWAY return lastNode; } } return null; } /** * Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the least key greater than * the specified key; if no such entry exists (i.e., the greatest key in the Tree is less than the specified key), returns * <tt>null</tt>. */ final OTreeMapEntry<K, V> getCeilingEntry(final K key) { OTreeMapEntry<K, V> p = root; while (p != null) { int cmp = compare(key, p.getKey()); if (cmp < 0) { if (p.getLeft() != null) p = p.getLeft(); else return p; } else if (cmp > 0) { if (p.getRight() != null) { p = p.getRight(); } else { OTreeMapEntry<K, V> parent = p.getParent(); Entry<K, V> ch = p; while (parent != null && ch == parent.getRight()) { ch = parent; parent = parent.getParent(); } return parent; } } else return p; } return null; } /** * Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the greatest key less than * the specified key; if no such entry exists, returns <tt>null</tt>. */ final OTreeMapEntry<K, V> getFloorEntry(final K key) { OTreeMapEntry<K, V> p = root; while (p != null) { int cmp = compare(key, p.getKey()); if (cmp > 0) { if (p.getRight() != null) p = p.getRight(); else return p; } else if (cmp < 0) { if (p.getLeft() != null) { p = p.getLeft(); } else { OTreeMapEntry<K, V> parent = p.getParent(); Entry<K, V> ch = p; while (parent != null && ch == parent.getLeft()) { ch = parent; parent = parent.getParent(); } return parent; } } else return p; } return null; } /** * Gets the entry for the least key greater than the specified key; if no such entry exists, returns the entry for the least key * greater than the specified key; if no such entry exists returns <tt>null</tt>. */ final OTreeMapEntry<K, V> getHigherEntry(final K key) { OTreeMapEntry<K, V> p = root; while (p != null) { int cmp = compare(key, p.getKey()); if (cmp < 0) { if (p.getLeft() != null) p = p.getLeft(); else return p; } else { if (p.getRight() != null) { p = p.getRight(); } else { OTreeMapEntry<K, V> parent = p.getParent(); Entry<K, V> ch = p; while (parent != null && ch == parent.getRight()) { ch = parent; parent = parent.getParent(); } return parent; } } } return null; } /** * Returns the entry for the greatest key less than the specified key; if no such entry exists (i.e., the least key in the Tree is * greater than the specified key), returns <tt>null</tt>. */ final OTreeMapEntry<K, V> getLowerEntry(final K key) { OTreeMapEntry<K, V> p = root; while (p != null) { int cmp = compare(key, p.getKey()); if (cmp > 0) { if (p.getRight() != null) p = p.getRight(); else return p; } else { if (p.getLeft() != null) { p = p.getLeft(); } else { OTreeMapEntry<K, V> parent = p.getParent(); Entry<K, V> ch = p; while (parent != null && ch == parent.getLeft()) { ch = parent; parent = parent.getParent(); } return parent; } } } return null; } /** * Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the * old value is replaced. * * @param key * key with which the specified value is to be associated * @param value * value to be associated with the specified key * * @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A * <tt>null</tt> return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.) * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public V put(final K key, final V value) { OTreeMapEntry<K, V> parentNode = null; try { if (root == null) { root = createEntry(key, value); root.setColor(BLACK); size = 1; modCount++; if (listener != null) listener.signalTreeChanged(this); return null; } // System.out.println("Put of key " + key + "..."); // SEARCH THE ITEM parentNode = getEntry(key, true); // System.out.println("Parent node: " + parentNode+", pageItemFound="+pageItemFound); if (pageItemFound) // EXACT MATCH: UPDATE THE VALUE return parentNode.setValue(value); if (parentNode == null) parentNode = root; // System.out.println("Parent node free space: " + parentNode.getFreeSpace()); if (parentNode.getFreeSpace() > 0) { // INSERT INTO THE PAGE parentNode.insert(pageIndex, key, value); } else { // CREATE NEW NODE AND COPY HALF OF VALUES FROM THE ORIGIN TO THE NEW ONE IN ORDER TO GET VALUES BALANCED final OTreeMapEntry<K, V> newNode = createEntry(parentNode); // System.out.println("Created new entry: " + newEntry+ ", insert the key as index="+pageIndex); if (pageIndex < parentNode.getPageSplitItems()) // INSERT IN THE ORIGINAL NODE parentNode.insert(pageIndex, key, value); else // INSERT IN THE NEW NODE newNode.insert(pageIndex - parentNode.getPageSplitItems(), key, value); final OTreeMapEntry<K, V> prevNode = parentNode.getRight(); // REPLACE THE RIGHT ONE WITH THE NEW NODE parentNode.setRight(newNode); if (prevNode != null) { // INSERT THE NODE IN THE TREE IN THE RIGHT MOVING CURRENT RIGHT TO THE RIGHT OF THE NEW NODE newNode.setRight(prevNode); fixAfterInsertion(prevNode); } else fixAfterInsertion(newNode); checkTreeStructure(parentNode); modCount++; } checkTreeStructure(parentNode); size++; if (listener != null) listener.signalTreeChanged(this); } finally { checkTreeStructure(parentNode); } return null; } /** * Removes the mapping for this key from this OTreeMap if present. * * @param key * key for which mapping should be removed * @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A * <tt>null</tt> return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.) * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public V remove(final Object key) { OTreeMapEntry<K, V> p = getEntry(key); if (p == null) return null; V oldValue = p.getValue(); deleteEntry(p); return oldValue; } /** * Removes all of the mappings from this map. The map will be empty after this call returns. */ @Override public void clear() { modCount++; size = 0; setRoot(null); } /** * Returns a shallow copy of this <tt>OTreeMap</tt> instance. (The keys and values themselves are not cloned.) * * @return a shallow copy of this map */ @Override public Object clone() { OTreeMap<K, V> clone = null; try { clone = (OTreeMap<K, V>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } // Put clone into "virgin" state (except for comparator) clone.listener = listener; clone.lastPageSize = lastPageSize; clone.pageIndex = pageIndex; clone.pageItemFound = pageItemFound; clone.pageLoadFactor = pageLoadFactor; clone.root = null; clone.size = 0; clone.modCount = 0; clone.entrySet = null; clone.navigableKeySet = null; clone.descendingMap = null; // Initialize clone with our mappings try { clone.buildFromSorted(size, entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return clone; } // ONavigableMap API methods /** * @since 1.6 */ public Map.Entry<K, V> firstEntry() { return exportEntry(getFirstEntry()); } /** * @since 1.6 */ public Map.Entry<K, V> lastEntry() { return exportEntry(getLastEntry()); } /** * @since 1.6 */ public Entry<K, V> pollFirstEntry() { OTreeMapEntry<K, V> p = getFirstEntry(); Map.Entry<K, V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } /** * @since 1.6 */ public Entry<K, V> pollLastEntry() { OTreeMapEntry<K, V> p = getLastEntry(); Map.Entry<K, V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> lowerEntry(final K key) { return exportEntry(getLowerEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K lowerKey(final K key) { return keyOrNull(getLowerEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> floorEntry(final K key) { return exportEntry(getFloorEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K floorKey(final K key) { return keyOrNull(getFloorEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> ceilingEntry(final K key) { return exportEntry(getCeilingEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K ceilingKey(final K key) { return keyOrNull(getCeilingEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> higherEntry(final K key) { return exportEntry(getHigherEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K higherKey(final K key) { return keyOrNull(getHigherEntry(key)); } // Views /** * Fields initialized to contain an instance of the entry set view the first time this view is requested. Views are stateless, so * there's no reason to create more than one. */ private transient EntrySet entrySet = null; private transient KeySet<K> navigableKeySet = null; private transient ONavigableMap<K, V> descendingMap = null; /** * Returns a {@link Set} view of the keys contained in this map. The set's iterator returns the keys in ascending order. The set * is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration * over the set is in progress (except through the iterator's own <tt>remove</tt> operation), the results of the iteration are * undefined. The set supports element removal, which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations. It does * not support the <tt>add</tt> or <tt>addAll</tt> operations. */ @Override public Set<K> keySet() { return navigableKeySet(); } /** * @since 1.6 */ public ONavigableSet<K> navigableKeySet() { KeySet<K> nks = navigableKeySet; return (nks != null) ? nks : (navigableKeySet = (KeySet<K>) new KeySet<Object>((ONavigableMap<Object, Object>) this)); } /** * @since 1.6 */ public ONavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } /** * Returns a {@link Collection} view of the values contained in this map. The collection's iterator returns the values in * ascending order of the corresponding keys. The collection is backed by the map, so changes to the map are reflected in the * collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the * iterator's own <tt>remove</tt> operation), the results of the iteration are undefined. The collection supports element removal, * which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. */ @Override public Collection<V> values() { Collection<V> vs = super.values(); return (vs != null) ? vs : null; } /** * Returns a {@link Set} view of the mappings contained in this map. The set's iterator returns the entries in ascending key * order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through the iterator's own <tt>remove</tt> operation, or through the * <tt>setValue</tt> operation on a map entry returned by the iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support the <tt>add</tt> * or <tt>addAll</tt> operations. */ @Override public Set<Map.Entry<K, V>> entrySet() { EntrySet es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } /** * @since 1.6 */ public ONavigableMap<K, V> descendingMap() { ONavigableMap<K, V> km = descendingMap; return (km != null) ? km : (descendingMap = new DescendingSubMap<K, V>(this, true, null, true, true, null, true)); } public ONavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return new AscendingSubMap<K, V>(this, false, fromKey, fromInclusive, false, toKey, toInclusive); } public ONavigableMap<K, V> headMap(K toKey, boolean inclusive) { return new AscendingSubMap<K, V>(this, true, null, true, false, toKey, inclusive); } public ONavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return new AscendingSubMap<K, V>(this, false, fromKey, inclusive, true, null, true); } public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } // View class support class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { return new ValueIterator(getFirstEntry()); } @Override public int size() { return OTreeMap.this.size(); } @Override public boolean contains(Object o) { return OTreeMap.this.containsValue(o); } @Override public boolean remove(Object o) { for (OTreeMapEntry<K, V> e = getFirstEntry(); e != null; e = successor(e)) { if (valEquals(e.getValue(), o)) { deleteEntry(e); return true; } } return false; } @Override public void clear() { OTreeMap.this.clear(); } } class EntrySet extends AbstractSet<Map.Entry<K, V>> { @Override public Iterator<Map.Entry<K, V>> iterator() { return new EntryIterator(getFirstEntry()); } @Override public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o; V value = entry.getValue(); V p = get(entry.getKey()); return p != null && valEquals(p, value); } @Override public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o; V value = entry.getValue(); OTreeMapEntry<K, V> p = getEntry(entry.getKey()); if (p != null && valEquals(p.getValue(), value)) { deleteEntry(p); return true; } return false; } @Override public int size() { return OTreeMap.this.size(); } @Override public void clear() { OTreeMap.this.clear(); } } /* * Unlike Values and EntrySet, the KeySet class is static, delegating to a ONavigableMap to allow use by SubMaps, which outweighs * the ugliness of needing type-tests for the following Iterator methods that are defined appropriately in main versus submap * classes. */ Iterator<K> keyIterator() { return new KeyIterator(getFirstEntry()); } Iterator<K> descendingKeyIterator() { return new DescendingKeyIterator(getLastEntry()); } @SuppressWarnings("rawtypes") static final class KeySet<E> extends AbstractSet<E> implements ONavigableSet<E> { private final ONavigableMap<E, Object> m; KeySet(ONavigableMap<E, Object> map) { m = map; } @Override public Iterator<E> iterator() { if (m instanceof OTreeMap) return ((OTreeMap<E, Object>) m).keyIterator(); else return (((OTreeMap.NavigableSubMap) m).keyIterator()); } public Iterator<E> descendingIterator() { if (m instanceof OTreeMap) return ((OTreeMap<E, Object>) m).descendingKeyIterator(); else return (((OTreeMap.NavigableSubMap) m).descendingKeyIterator()); } @Override public int size() { return m.size(); } @Override public boolean isEmpty() { return m.isEmpty(); } @Override public boolean contains(Object o) { return m.containsKey(o); } @Override public void clear() { m.clear(); } public E lower(E e) { return m.lowerKey(e); } public E floor(E e) { return m.floorKey(e); } public E ceiling(E e) { return m.ceilingKey(e); } public E higher(E e) { return m.higherKey(e); } public E first() { return m.firstKey(); } public E last() { return m.lastKey(); } public Comparator<? super E> comparator() { return m.comparator(); } public E pollFirst() { Map.Entry<E, Object> e = m.pollFirstEntry(); return e == null ? null : e.getKey(); } public E pollLast() { Map.Entry<E, Object> e = m.pollLastEntry(); return e == null ? null : e.getKey(); } @Override public boolean remove(Object o) { int oldSize = size(); m.remove(o); return size() != oldSize; } public ONavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new OTreeSetMemory<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } public ONavigableSet<E> headSet(E toElement, boolean inclusive) { return new OTreeSetMemory<E>(m.headMap(toElement, inclusive)); } public ONavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new OTreeSetMemory<E>(m.tailMap(fromElement, inclusive)); } public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } public ONavigableSet<E> descendingSet() { return new OTreeSetMemory<E>(m.descendingMap()); } } final class EntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> { EntryIterator(OTreeMapEntry<K, V> first) { super(first); } public Map.Entry<K, V> next() { return nextEntry(); } } final class ValueIterator extends AbstractEntryIterator<K, V, V> { ValueIterator(OTreeMapEntry<K, V> first) { super(first); } public V next() { return nextEntry().getValue(); } } final class KeyIterator extends AbstractEntryIterator<K, V, K> { KeyIterator(OTreeMapEntry<K, V> first) { super(first); } public K next() { return nextEntry().getKey(); } } final class DescendingKeyIterator extends AbstractEntryIterator<K, V, K> { DescendingKeyIterator(OTreeMapEntry<K, V> first) { super(first); } public K next() { return prevEntry().getKey(); } } // Little utilities /** * Compares two keys using the correct comparison method for this OTreeMap. */ final int compare(Object k1, Object k2) { return comparator == null ? ((Comparable<? super K>) k1).compareTo((K) k2) : comparator.compare((K) k1, (K) k2); } /** * Test two values for equality. Differs from o1.equals(o2) only in that it copes with <tt>null</tt> o1 properly. */ final static boolean valEquals(Object o1, Object o2) { return (o1 == null ? o2 == null : o1.equals(o2)); } /** * Return SimpleImmutableEntry for entry, or null if null */ static <K, V> Map.Entry<K, V> exportEntry(OTreeMapEntry<K, V> e) { return e == null ? null : new OSimpleImmutableEntry<K, V>(e); } /** * Return key for entry, or null if null */ static <K, V> K keyOrNull(OTreeMapEntry<K, V> e) { return e == null ? null : e.getKey(); } /** * Returns the key corresponding to the specified Entry. * * @throws NoSuchElementException * if the Entry is null */ static <K> K key(OTreeMapEntry<K, ?> e) { if (e == null) throw new NoSuchElementException(); return e.getKey(); } // SubMaps /** * @serial include */ @SuppressWarnings("serial") static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, java.io.Serializable { /** * The backing map. */ final OTreeMap<K, V> m; /** * Endpoints are represented as triples (fromStart, lo, loInclusive) and (toEnd, hi, hiInclusive). If fromStart is true, then * the low (absolute) bound is the start of the backing map, and the other values are ignored. Otherwise, if loInclusive is * true, lo is the inclusive bound, else lo is the exclusive bound. Similarly for the upper bound. */ final K lo, hi; final boolean fromStart, toEnd; final boolean loInclusive, hiInclusive; NavigableSubMap(OTreeMap<K, V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) { if (!fromStart && !toEnd) { if (m.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); } else { if (!fromStart) // type check m.compare(lo, lo); if (!toEnd) m.compare(hi, hi); } this.m = m; this.fromStart = fromStart; this.lo = lo; this.loInclusive = loInclusive; this.toEnd = toEnd; this.hi = hi; this.hiInclusive = hiInclusive; } // internal utilities final boolean tooLow(Object key) { if (!fromStart) { int c = m.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } final boolean tooHigh(Object key) { if (!toEnd) { int c = m.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } final boolean inRange(Object key) { return !tooLow(key) && !tooHigh(key); } final boolean inClosedRange(Object key) { return (fromStart || m.compare(key, lo) >= 0) && (toEnd || m.compare(hi, key) >= 0); } final boolean inRange(Object key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } /* * Absolute versions of relation operations. Subclasses map to these using like-named "sub" versions that invert senses for * descending maps */ final OTreeMapEntry<K, V> absLowest() { OTreeMapEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo) : m.getHigherEntry(lo))); return (e == null || tooHigh(e.getKey())) ? null : e; } final OTreeMapEntry<K, V> absHighest() { OTreeMapEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi) : m.getLowerEntry(hi))); return (e == null || tooLow(e.getKey())) ? null : e; } final OTreeMapEntry<K, V> absCeiling(K key) { if (tooLow(key)) return absLowest(); OTreeMapEntry<K, V> e = m.getCeilingEntry(key); return (e == null || tooHigh(e.getKey())) ? null : e; } final OTreeMapEntry<K, V> absHigher(K key) { if (tooLow(key)) return absLowest(); OTreeMapEntry<K, V> e = m.getHigherEntry(key); return (e == null || tooHigh(e.getKey())) ? null : e; } final OTreeMapEntry<K, V> absFloor(K key) { if (tooHigh(key)) return absHighest(); OTreeMapEntry<K, V> e = m.getFloorEntry(key); return (e == null || tooLow(e.getKey())) ? null : e; } final OTreeMapEntry<K, V> absLower(K key) { if (tooHigh(key)) return absHighest(); OTreeMapEntry<K, V> e = m.getLowerEntry(key); return (e == null || tooLow(e.getKey())) ? null : e; } /** Returns the absolute high fence for ascending traversal */ final OTreeMapEntry<K, V> absHighFence() { return (toEnd ? null : (hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi))); } /** Return the absolute low fence for descending traversal */ final OTreeMapEntry<K, V> absLowFence() { return (fromStart ? null : (loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo))); } // Abstract methods defined in ascending vs descending classes // These relay to the appropriate absolute versions abstract OTreeMapEntry<K, V> subLowest(); abstract OTreeMapEntry<K, V> subHighest(); abstract OTreeMapEntry<K, V> subCeiling(K key); abstract OTreeMapEntry<K, V> subHigher(K key); abstract OTreeMapEntry<K, V> subFloor(K key); abstract OTreeMapEntry<K, V> subLower(K key); /** Returns ascending iterator from the perspective of this submap */ abstract Iterator<K> keyIterator(); /** Returns descending iterator from the perspective of this submap */ abstract Iterator<K> descendingKeyIterator(); // public methods @Override public boolean isEmpty() { return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty(); } @Override public int size() { return (fromStart && toEnd) ? m.size() : entrySet().size(); } @Override public final boolean containsKey(Object key) { return inRange(key) && m.containsKey(key); } @Override public final V put(K key, V value) { if (!inRange(key)) throw new IllegalArgumentException("key out of range"); return m.put(key, value); } @Override public final V get(Object key) { return !inRange(key) ? null : m.get(key); } @Override public final V remove(Object key) { return !inRange(key) ? null : m.remove(key); } public final Map.Entry<K, V> ceilingEntry(K key) { return exportEntry(subCeiling(key)); } public final K ceilingKey(K key) { return keyOrNull(subCeiling(key)); } public final Map.Entry<K, V> higherEntry(K key) { return exportEntry(subHigher(key)); } public final K higherKey(K key) { return keyOrNull(subHigher(key)); } public final Map.Entry<K, V> floorEntry(K key) { return exportEntry(subFloor(key)); } public final K floorKey(K key) { return keyOrNull(subFloor(key)); } public final Map.Entry<K, V> lowerEntry(K key) { return exportEntry(subLower(key)); } public final K lowerKey(K key) { return keyOrNull(subLower(key)); } public final K firstKey() { return key(subLowest()); } public final K lastKey() { return key(subHighest()); } public final Map.Entry<K, V> firstEntry() { return exportEntry(subLowest()); } public final Map.Entry<K, V> lastEntry() { return exportEntry(subHighest()); } public final Map.Entry<K, V> pollFirstEntry() { OTreeMapEntry<K, V> e = subLowest(); Map.Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } public final Map.Entry<K, V> pollLastEntry() { OTreeMapEntry<K, V> e = subHighest(); Map.Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } // Views transient ONavigableMap<K, V> descendingMapView = null; transient EntrySetView entrySetView = null; transient KeySet<K> navigableKeySetView = null; @SuppressWarnings("rawtypes") public final ONavigableSet<K> navigableKeySet() { KeySet<K> nksv = navigableKeySetView; return (nksv != null) ? nksv : (navigableKeySetView = new OTreeMap.KeySet(this)); } @Override public final Set<K> keySet() { return navigableKeySet(); } public ONavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } public final SortedMap<K, V> subMap(final K fromKey, final K toKey) { return subMap(fromKey, true, toKey, false); } public final SortedMap<K, V> headMap(final K toKey) { return headMap(toKey, false); } public final SortedMap<K, V> tailMap(final K fromKey) { return tailMap(fromKey, true); } // View classes abstract class EntrySetView extends AbstractSet<Map.Entry<K, V>> { private transient int size = -1, sizeModCount; @Override public int size() { if (fromStart && toEnd) return m.size(); if (size == -1 || sizeModCount != m.modCount) { sizeModCount = m.modCount; size = 0; Iterator<?> i = iterator(); while (i.hasNext()) { size++; i.next(); } } return size; } @Override public boolean isEmpty() { OTreeMapEntry<K, V> n = absLowest(); return n == null || tooHigh(n.getKey()); } @Override public boolean contains(final Object o) { if (!(o instanceof OTreeMapEntry)) return false; OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o; K key = entry.getKey(); if (!inRange(key)) return false; V nodeValue = m.get(key); return nodeValue != null && valEquals(nodeValue, entry.getValue()); } @Override public boolean remove(final Object o) { if (!(o instanceof OTreeMapEntry)) return false; final OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o; K key = entry.getKey(); if (!inRange(key)) return false; final OTreeMapEntry<K, V> node = m.getEntry(key); if (node != null && valEquals(node.getValue(), entry.getValue())) { m.deleteEntry(node); return true; } return false; } } /** * Iterators for SubMaps */ abstract class SubMapIterator<T> implements Iterator<T> { OTreeMapEntry<K, V> lastReturned; OTreeMapEntry<K, V> next; final K fenceKey; int expectedModCount; SubMapIterator(final OTreeMapEntry<K, V> first, final OTreeMapEntry<K, V> fence) { expectedModCount = m.modCount; lastReturned = null; next = first; fenceKey = fence == null ? null : fence.getKey(); } public final boolean hasNext() { return next != null && next.getKey() != fenceKey; } final OTreeMapEntry<K, V> nextEntry() { OTreeMapEntry<K, V> e = next; if (e == null || e.getKey() == fenceKey) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next = successor(e); lastReturned = e; return e; } final OTreeMapEntry<K, V> prevEntry() { OTreeMapEntry<K, V> e = next; if (e == null || e.getKey() == fenceKey) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next = predecessor(e); lastReturned = e; return e; } final void removeAscending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.getLeft() != null && lastReturned.getRight() != null) next = lastReturned; m.deleteEntry(lastReturned); lastReturned = null; expectedModCount = m.modCount; } final void removeDescending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); m.deleteEntry(lastReturned); lastReturned = null; expectedModCount = m.modCount; } } final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { SubMapEntryIterator(final OTreeMapEntry<K, V> first, final OTreeMapEntry<K, V> fence) { super(first, fence); } public Map.Entry<K, V> next() { return nextEntry(); } public void remove() { removeAscending(); } } final class SubMapKeyIterator extends SubMapIterator<K> { SubMapKeyIterator(final OTreeMapEntry<K, V> first, final OTreeMapEntry<K, V> fence) { super(first, fence); } public K next() { return nextEntry().getKey(); } public void remove() { removeAscending(); } } final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { DescendingSubMapEntryIterator(final OTreeMapEntry<K, V> last, final OTreeMapEntry<K, V> fence) { super(last, fence); } public Map.Entry<K, V> next() { return prevEntry(); } public void remove() { removeDescending(); } } final class DescendingSubMapKeyIterator extends SubMapIterator<K> { DescendingSubMapKeyIterator(final OTreeMapEntry<K, V> last, final OTreeMapEntry<K, V> fence) { super(last, fence); } public K next() { return prevEntry().getKey(); } public void remove() { removeDescending(); } } } /** * @serial include */ static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866124060L; AscendingSubMap(final OTreeMap<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd, K hi, final boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return m.comparator(); } public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<K, V>(m, false, fromKey, fromInclusive, false, toKey, toInclusive); } public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, toKey, inclusive); } public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new AscendingSubMap<K, V>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive); } public ONavigableMap<K, V> descendingMap() { ONavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } @Override Iterator<K> keyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } @Override Iterator<K> descendingKeyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } final class AscendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new SubMapEntryIterator(absLowest(), absHighFence()); } } @Override public Set<Map.Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new AscendingEntrySetView(); } @Override OTreeMapEntry<K, V> subLowest() { return absLowest(); } @Override OTreeMapEntry<K, V> subHighest() { return absHighest(); } @Override OTreeMapEntry<K, V> subCeiling(final K key) { return absCeiling(key); } @Override OTreeMapEntry<K, V> subHigher(final K key) { return absHigher(key); } @Override OTreeMapEntry<K, V> subFloor(final K key) { return absFloor(key); } @Override OTreeMapEntry<K, V> subLower(final K key) { return absLower(key); } } /** * @serial include */ static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866120460L; private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator); DescendingSubMap(final OTreeMap<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd, final K hi, final boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return reverseComparator; } public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<K, V>(m, false, toKey, toInclusive, false, fromKey, fromInclusive); } public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<K, V>(m, false, toKey, inclusive, toEnd, hi, hiInclusive); } public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, fromKey, inclusive); } public ONavigableMap<K, V> descendingMap() { ONavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } @Override Iterator<K> keyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } @Override Iterator<K> descendingKeyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } final class DescendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new DescendingSubMapEntryIterator(absHighest(), absLowFence()); } } @Override public Set<Map.Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new DescendingEntrySetView(); } @Override OTreeMapEntry<K, V> subLowest() { return absHighest(); } @Override OTreeMapEntry<K, V> subHighest() { return absLowest(); } @Override OTreeMapEntry<K, V> subCeiling(final K key) { return absFloor(key); } @Override OTreeMapEntry<K, V> subHigher(final K key) { return absLower(key); } @Override OTreeMapEntry<K, V> subFloor(final K key) { return absCeiling(key); } @Override OTreeMapEntry<K, V> subLower(final K key) { return absHigher(key); } } // Red-black mechanics static final boolean RED = false; static final boolean BLACK = true; /** * Node in the Tree. Doubles as a means to pass key-value pairs back to user (see Map.Entry). */ /** * Returns the first Entry in the OTreeMap (according to the OTreeMap's key-sort function). Returns null if the OTreeMap is empty. */ protected OTreeMapEntry<K, V> getFirstEntry() { OTreeMapEntry<K, V> p = root; if (p != null) { if (p.getSize() > 0) pageIndex = 0; while (p.getLeft() != null) p = p.getLeft(); } return p; } /** * Returns the last Entry in the OTreeMap (according to the OTreeMap's key-sort function). Returns null if the OTreeMap is empty. */ protected final OTreeMapEntry<K, V> getLastEntry() { OTreeMapEntry<K, V> p = root; if (p != null) while (p.getRight() != null) p = p.getRight(); if (p != null) pageIndex = p.getSize() - 1; return p; } /** * Returns the successor of the specified Entry, or null if no such. */ public static <K, V> OTreeMapEntry<K, V> successor(final OTreeMapEntry<K, V> t) { if (t == null) return null; OTreeMapEntry<K, V> p = null; if (t.getRight() != null) { p = t.getRight(); while (p.getLeft() != null) p = p.getLeft(); } else { p = t.getParent(); OTreeMapEntry<K, V> ch = t; while (p != null && ch == p.getRight()) { ch = p; p = p.getParent(); } } return p; } /** * Returns the predecessor of the specified Entry, or null if no such. */ public static <K, V> OTreeMapEntry<K, V> predecessor(final OTreeMapEntry<K, V> t) { if (t == null) return null; else if (t.getLeft() != null) { OTreeMapEntry<K, V> p = t.getLeft(); while (p.getRight() != null) p = p.getRight(); return p; } else { OTreeMapEntry<K, V> p = t.getParent(); Entry<K, V> ch = t; while (p != null && ch == p.getLeft()) { ch = p; p = p.getParent(); } return p; } } /** * Balancing operations. * * Implementations of rebalancings during insertion and deletion are slightly different than the CLR version. Rather than using * dummy nilnodes, we use a set of accessors that deal properly with null. They are used to avoid messiness surrounding nullness * checks in the main algorithms. */ private static <K, V> boolean colorOf(final OTreeMapEntry<K, V> p) { return (p == null ? BLACK : p.getColor()); } private static <K, V> OTreeMapEntry<K, V> parentOf(final OTreeMapEntry<K, V> p) { return (p == null ? null : p.getParent()); } private static <K, V> void setColor(final OTreeMapEntry<K, V> p, final boolean c) { if (p != null) p.setColor(c); } private static <K, V> OTreeMapEntry<K, V> leftOf(final OTreeMapEntry<K, V> p) { return (p == null) ? null : p.getLeft(); } private static <K, V> OTreeMapEntry<K, V> rightOf(final OTreeMapEntry<K, V> p) { return (p == null) ? null : p.getRight(); } /** From CLR */ private void rotateLeft(final OTreeMapEntry<K, V> p) { if (p != null) { OTreeMapEntry<K, V> r = p.getRight(); p.setRight(r.getLeft()); if (r.getLeft() != null) r.getLeft().setParent(p); r.setParent(p.getParent()); if (p.getParent() == null) setRoot(r); else if (p.getParent().getLeft() == p) p.getParent().setLeft(r); else p.getParent().setRight(r); p.setParent(r); r.setLeft(p); } } protected void setRoot(final OTreeMapEntry<K, V> iRoot) { root = iRoot; } /** From CLR */ private void rotateRight(final OTreeMapEntry<K, V> p) { if (p != null) { OTreeMapEntry<K, V> l = p.getLeft(); p.setLeft(l.getRight()); if (l.getRight() != null) l.getRight().setParent(p); l.setParent(p.getParent()); if (p.getParent() == null) setRoot(l); else if (p.getParent().getRight() == p) p.getParent().setRight(l); else p.getParent().setLeft(l); l.setRight(p); p.setParent(l); } } /** From CLR */ /* * private void fixAfterInsertion(OTreeMapEntry<K, V> x) { x.setColor(RED); * * // if (x != null && x != root && x.getParent() != null && x.getParent().getColor() == RED) { // * //System.out.println("BEFORE FIX on node: " + x); // printInMemoryStructure(x); * * OTreeMapEntry<K, V> parent; OTreeMapEntry<K, V> grandParent; * * while (x != null && x != root && x.getParent() != null && x.getParent().getColor() == RED) { parent = parentOf(x); grandParent * = parentOf(parent); * * if (parent == leftOf(grandParent)) { // MY PARENT IS THE LEFT OF THE GRANDFATHER. GET MY UNCLE final OTreeMapEntry<K, V> uncle * = rightOf(grandParent); if (colorOf(uncle) == RED) { // SET MY PARENT AND UNCLE TO BLACK setColor(parent, BLACK); * setColor(uncle, BLACK); // SET GRANDPARENT'S COLOR TO RED setColor(grandParent, RED); // CONTINUE RECURSIVELY WITH MY * GRANDFATHER x = grandParent; } else { if (x == rightOf(parent)) { // I'M THE RIGHT x = parent; parent = parentOf(x); * grandParent = parentOf(parent); rotateLeft(x); } setColor(parent, BLACK); setColor(grandParent, RED); rotateRight(grandParent); * } } else { // MY PARENT IS THE RIGHT OF THE GRANDFATHER. GET MY UNCLE final OTreeMapEntry<K, V> uncle = leftOf(grandParent); if * (colorOf(uncle) == RED) { setColor(parent, BLACK); setColor(uncle, BLACK); setColor(grandParent, RED); x = grandParent; } else * { if (x == leftOf(parent)) { x = parentOf(x); parent = parentOf(x); grandParent = parentOf(parent); rotateRight(x); } * setColor(parent, BLACK); setColor(grandParent, RED); rotateLeft(grandParent); } } } * * // //System.out.println("AFTER FIX"); // printInMemoryStructure(x); // } * * root.setColor(BLACK); } */ private OTreeMapEntry<K, V> grandparent(final OTreeMapEntry<K, V> n) { return parentOf(parentOf(n)); } private OTreeMapEntry<K, V> uncle(final OTreeMapEntry<K, V> n) { if (parentOf(n) == leftOf(grandparent(n))) return rightOf(grandparent(n)); else return leftOf(grandparent(n)); } private void fixAfterInsertion(final OTreeMapEntry<K, V> n) { if (parentOf(n) == null) setColor(n, BLACK); else insert_case2(n); } private void insert_case2(final OTreeMapEntry<K, V> n) { if (colorOf(parentOf(n)) == BLACK) return; /* Tree is still valid */ else insert_case3(n); } private void insert_case3(final OTreeMapEntry<K, V> n) { if (uncle(n) != null && colorOf(uncle(n)) == RED) { setColor(parentOf(n), BLACK); setColor(uncle(n), BLACK); setColor(grandparent(n), RED); fixAfterInsertion(grandparent(n)); } else insert_case4(n); } private void insert_case4(OTreeMapEntry<K, V> n) { if (n == rightOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) { rotateLeft(parentOf(n)); n = leftOf(n); } else if (n == leftOf(parentOf(n)) && parentOf(n) == rightOf(grandparent(n))) { rotateRight(parentOf(n)); n = rightOf(n); } insert_case5(n); } private void insert_case5(final OTreeMapEntry<K, V> n) { setColor(parentOf(n), BLACK); setColor(grandparent(n), RED); if (n == leftOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) { rotateRight(grandparent(n)); } else { /* Here, n == parentOf(n)->right && parentOf(n) == grandparent(n)->right */ rotateLeft(grandparent(n)); } } /** * Delete node p, and then re-balance the tree. * * @param iIndex * -1 = delete the node, otherwise the item inside of it */ void deleteEntry(OTreeMapEntry<K, V> p) { size if (listener != null) listener.signalTreeChanged(this); if (pageIndex > -1) { // DELETE INSIDE THE NODE p.remove(); if (p.getSize() > 0) return; } // DELETE THE ENTIRE NODE, RE-BUILDING THE STRUCTURE modCount++; // If strictly internal, copy successor's element to p and then make p // point to successor. if (p.getLeft() != null && p.getRight() != null) { OTreeMapEntry<K, V> s = successor(p); p.copyFrom(s); p = s; } // p has 2 children // Start fixup at replacement node, if it exists. final OTreeMapEntry<K, V> replacement = (p.getLeft() != null ? p.getLeft() : p.getRight()); if (replacement != null) { // Link replacement to parent replacement.setParent(p.getParent()); if (p.getParent() == null) setRoot(replacement); else if (p == p.getParent().getLeft()) p.getParent().setLeft(replacement); else p.getParent().setRight(replacement); // Null out links so they are OK to use by fixAfterDeletion. p.setLeft(p.setRight(p.setParent(null))); // Fix replacement if (p.getColor() == BLACK) fixAfterDeletion(replacement); } else if (p.getParent() == null) { // return if we are the only node. clear(); } else { // No children. Use self as phantom replacement and unlink. if (p.getColor() == BLACK) fixAfterDeletion(p); if (p.getParent() != null) { if (p == p.getParent().getLeft()) p.getParent().setLeft(null); else if (p == p.getParent().getRight()) p.getParent().setRight(null); p.setParent(null); } } } /** From CLR */ private void fixAfterDeletion(OTreeMapEntry<K, V> x) { while (x != root && colorOf(x) == BLACK) { if (x == leftOf(parentOf(x))) { OTreeMapEntry<K, V> sib = rightOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateLeft(parentOf(x)); sib = rightOf(parentOf(x)); } if (colorOf(leftOf(sib)) == BLACK && colorOf(rightOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(rightOf(sib)) == BLACK) { setColor(leftOf(sib), BLACK); setColor(sib, RED); rotateRight(sib); sib = rightOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(rightOf(sib), BLACK); rotateLeft(parentOf(x)); x = root; } } else { // symmetric OTreeMapEntry<K, V> sib = leftOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateRight(parentOf(x)); sib = leftOf(parentOf(x)); } if (colorOf(rightOf(sib)) == BLACK && colorOf(leftOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(leftOf(sib)) == BLACK) { setColor(rightOf(sib), BLACK); setColor(sib, RED); rotateLeft(sib); sib = leftOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(leftOf(sib), BLACK); rotateRight(parentOf(x)); x = root; } } } setColor(x, BLACK); } private static final long serialVersionUID = 919286545866124006L; /** * Save the state of the <tt>OTreeMap</tt> instance to a stream (i.e., serialize it). * * @serialData The <i>size</i> of the OTreeMap (the number of key-value mappings) is emitted (int), followed by the key (Object) * and value (Object) for each key-value mapping represented by the OTreeMap. The key-value mappings are emitted in * key-order (as determined by the OTreeMap's Comparator, or by the keys' natural ordering if the OTreeMap has no * Comparator). */ private void writeObject(final java.io.ObjectOutputStream s) throws java.io.IOException { // Write out the Comparator and any hidden stuff s.defaultWriteObject(); // Write out size (number of Mappings) s.writeInt(size); // Write out keys and values (alternating) for (Iterator<Map.Entry<K, V>> i = entrySet().iterator(); i.hasNext();) { Entry<K, V> e = i.next(); s.writeObject(e.getKey()); s.writeObject(e.getValue()); } } /** * Reconstitute the <tt>OTreeMap</tt> instance from a stream (i.e., deserialize it). */ private void readObject(final java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in the Comparator and any hidden stuff s.defaultReadObject(); // Read in size int size = s.readInt(); buildFromSorted(size, null, s, null); } /** Intended to be called only from OTreeSet.readObject */ void readOTreeSet(int size, java.io.ObjectInputStream s, V defaultVal) throws java.io.IOException, ClassNotFoundException { buildFromSorted(size, null, s, defaultVal); } /** Intended to be called only from OTreeSet.addAll */ void addAllForOTreeSet(SortedSet<? extends K> set, V defaultVal) { try { buildFromSorted(set.size(), set.iterator(), null, defaultVal); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } /** * Linear time tree building algorithm from sorted data. Can accept keys and/or values from iterator or stream. This leads to too * many parameters, but seems better than alternatives. The four formats that this method accepts are: * * 1) An iterator of Map.Entries. (it != null, defaultVal == null). 2) An iterator of keys. (it != null, defaultVal != null). 3) A * stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it == * null, defaultVal != null). * * It is assumed that the comparator of the OTreeMap is already set prior to calling this method. * * @param size * the number of keys (or key-value pairs) to be read from the iterator or stream * @param it * If non-null, new entries are created from entries or keys read from this iterator. * @param str * If non-null, new entries are created from keys and possibly values read from this stream in serialized form. Exactly * one of it and str should be non-null. * @param defaultVal * if non-null, this default value is used for each value in the map. If null, each value is read from iterator or * stream, as described above. * @throws IOException * propagated from stream reads. This cannot occur if str is null. * @throws ClassNotFoundException * propagated from readObject. This cannot occur if str is null. */ private void buildFromSorted(final int size, final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException, ClassNotFoundException { this.size = size; root = buildFromSorted(0, 0, size - 1, computeRedLevel(size), it, str, defaultVal); } /** * Recursive "helper method" that does the real work of the previous method. Identically named parameters have identical * definitions. Additional parameters are documented below. It is assumed that the comparator and size fields of the OTreeMap are * already set prior to calling this method. (It ignores both fields.) * * @param level * the current level of tree. Initial call should be 0. * @param lo * the first element index of this subtree. Initial should be 0. * @param hi * the last element index of this subtree. Initial should be size-1. * @param redLevel * the level at which nodes should be red. Must be equal to computeRedLevel for tree of this size. */ private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo, final int hi, final int redLevel, final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException, ClassNotFoundException { /* * Strategy: The root is the middlemost element. To get to it, we have to first recursively construct the entire left subtree, * so as to grab all of its elements. We can then proceed with right subtree. * * The lo and hi arguments are the minimum and maximum indices to pull out of the iterator or stream for current subtree. They * are not actually indexed, we just proceed sequentially, ensuring that items are extracted in corresponding order. */ if (hi < lo) return null; final int mid = (lo + hi) / 2; OTreeMapEntry<K, V> left = null; if (lo < mid) left = buildFromSorted(level + 1, lo, mid - 1, redLevel, it, str, defaultVal); // extract key and/or value from iterator or stream K key; V value; if (it != null) { if (defaultVal == null) { OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) it.next(); key = entry.getKey(); value = entry.getValue(); } else { key = (K) it.next(); value = defaultVal; } } else { // use stream key = (K) str.readObject(); value = (defaultVal != null ? defaultVal : (V) str.readObject()); } final OTreeMapEntry<K, V> middle = createEntry(key, value); // color nodes in non-full bottom most level red if (level == redLevel) middle.setColor(RED); if (left != null) { middle.setLeft(left); left.setParent(middle); } if (mid < hi) { OTreeMapEntry<K, V> right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it, str, defaultVal); middle.setRight(right); right.setParent(middle); } return middle; } /** * Find the level down to which to assign all nodes BLACK. This is the last `full' level of the complete binary tree produced by * buildTree. The remaining nodes are colored RED. (This makes a `nice' set of color assignments wrt future insertions.) This * level number is computed by finding the number of splits needed to reach the zeroeth node. (The answer is ~lg(N), but in any * case must be computed by same quick O(lg(N)) loop.) */ private static int computeRedLevel(final int sz) { int level = 0; for (int m = sz - 1; m >= 0; m = m / 2 - 1) level++; return level; } public int getPageSize() { return lastPageSize; } public int getPageIndex() { return pageIndex; } private void init() { } public OTreeMapEntry<K, V> getRoot() { return root; } protected void printInMemoryStructure(final OTreeMapEntry<K, V> iRootNode) { printInMemoryNode("root", iRootNode, 0); } private void printInMemoryNode(final String iLabel, OTreeMapEntry<K, V> iNode, int iLevel) { if (iNode == null) return; for (int i = 0; i < iLevel; ++i) System.out.print(' '); System.out.println(iLabel + ": " + iNode.toString() + " (" + (iNode.getColor() ? "B" : "R") + ")"); ++iLevel; printInMemoryNode(iLevel + ".left", iNode.getLeftInMemory(), iLevel); printInMemoryNode(iLevel + ".right", iNode.getRightInMemory(), iLevel); } @SuppressWarnings("rawtypes") public void checkTreeStructure(final OTreeMapEntry<K, V> iRootNode) { if (!runtimeCheckEnabled || iRootNode == null) return; int currPageIndex = pageIndex; OTreeMapEntry<K, V> prevNode = null; int i = 0; for (OTreeMapEntry<K, V> e = iRootNode.getFirstInMemory(); e != null; e = e.getNextInMemory()) { if (prevNode != null) { if (prevNode.getTree() == null) OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Freed record %d found in memory\n", i); if (((Comparable) e.getFirstKey()).compareTo(((Comparable) e.getLastKey())) > 0) { OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] begin key is > than last key\n", e.getFirstKey(), e.getLastKey()); printInMemoryStructure(iRootNode); } if (((Comparable) e.getFirstKey()).compareTo(((Comparable) prevNode.getLastKey())) < 0) { OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s starts with a key minor than the last key of the previous node %s\n", e, prevNode); printInMemoryStructure(e.getParentInMemory() != null ? e.getParentInMemory() : e); } } if (e.getLeftInMemory() != null && e.getLeftInMemory() == e) { OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s has left that points to itself!\n", e); printInMemoryStructure(iRootNode); } if (e.getRightInMemory() != null && e.getRightInMemory() == e) { OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s has right that points to itself!\n", e); printInMemoryStructure(iRootNode); } if (e.getLeftInMemory() != null && e.getLeftInMemory() == e.getRightInMemory()) { OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s has left and right equals!\n", e); printInMemoryStructure(iRootNode); } if (e.getParentInMemory() != null && e.getParentInMemory().getRightInMemory() != e && e.getParentInMemory().getLeftInMemory() != e) { OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s is the children of node %s but the cross-reference is missed!\n", e, e.getParentInMemory()); printInMemoryStructure(iRootNode); } prevNode = e; ++i; } pageIndex = currPageIndex; } public boolean isRuntimeCheckEnabled() { return runtimeCheckEnabled; } public void setChecks(boolean checks) { this.runtimeCheckEnabled = checks; } }
package pw.ian.vrtransit; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import org.gearvrf.GVRAndroidResource; import org.gearvrf.GVRBitmapTexture; import org.gearvrf.GVRContext; import org.gearvrf.GVRMesh; import org.gearvrf.GVRScene; import org.gearvrf.GVRSceneObject; import org.gearvrf.GVRScript; import org.gearvrf.animation.GVRAnimation; import org.gearvrf.animation.GVRRelativeMotionAnimation; import pw.ian.vrtransit.data.BusUpdate; import pw.ian.vrtransit.data.TransitDataAccessor; public class MUNIVisualizerScript extends GVRScript { private MainActivity core; private GVRContext mCtx; private GVRMesh busMesh; private GVRBitmapTexture busTex; private GVRBitmapTexture trainTex; private GVRBitmapTexture mapTex; private TransitDataAccessor tda; private GVRSceneObject root; private Map<String, GVRSceneObject> vehicles = new HashMap<>(); public MUNIVisualizerScript(MainActivity core) { this.core = core; } @Override public void onInit(GVRContext ctx) throws Throwable { mCtx = ctx; tda = new TransitDataAccessor(); GVRScene scene = ctx.getMainScene(); scene.setFrustumCulling(true); scene.getMainCameraRig().getLeftCamera() .setBackgroundColor(0.0f, 0.0f, 0.0f, 1.0f); scene.getMainCameraRig().getRightCamera() .setBackgroundColor(0.0f, 0.0f, 0.0f, 1.0f); scene.getMainCameraRig().getOwnerObject().getTransform() .setPosition(0f, 0f, 0f); busMesh = ctx.loadMesh(new GVRAndroidResource(ctx, "cube.obj")); busTex = ctx.loadTexture(new GVRAndroidResource(ctx, "bus.jpg")); busTex.setKeepWrapper(true); trainTex = ctx.loadTexture(new GVRAndroidResource(ctx, "train.jpg")); trainTex.setKeepWrapper(true); mapTex = ctx.loadTexture(new GVRAndroidResource(ctx, "map2.jpg")); root = new GVRSceneObject(ctx); scene.addSceneObject(root); GVRSceneObject map = new GVRSceneObject(ctx, 10f, 10f, mapTex); map.getTransform().setPosition(0f, 0f, -5f); root.addChildObject(map); initBusObjectPool(Constants.MAX_OBJECTS); } @Override public void onStep() { List<BusUpdate> bs = tda.nextUpdates(); for (BusUpdate bu : bs) { if (bu.getRoute().equals("25")) continue; if (vehicles.containsKey(bu.getId())) { if (bu.remove) { GVRSceneObject bus = vehicles.remove(bu.getId()); } else { GVRSceneObject bus = vehicles.get(bu.getId()); smoothSetBusPos(bus, bu.getLat(), bu.getLon()); } } else { GVRSceneObject bus = setBusPos(nextBus(), bu.getLat(), bu.getLon()); if (vehicles.containsValue(bus)) { String key = null; for (Entry<String, GVRSceneObject> e : vehicles.entrySet()) { if (e.getValue().equals(bus)) { key = e.getKey(); break; } } vehicles.remove(key); } if (bu.getType().equals("train")) { bus.getTransform().setScale(0.15f, 0.05f, 0.05f); bus.getRenderData().getMaterial().setMainTexture(trainTex); } else { bus.getTransform().setScale(0.05f, 0.05f, 0.05f); bus.getRenderData().getMaterial().setMainTexture(busTex); } vehicles.put(bu.getId(), bus); } } } private Queue<GVRSceneObject> busPool = new LinkedList<>(); private void initBusObjectPool(int amt) { for (int i = 0; i < amt; i++) { busPool.add(constructBus(mCtx)); } } private GVRSceneObject nextBus() { GVRSceneObject bus = busPool.poll(); busPool.add(bus); return bus; } private GVRSceneObject constructBus(GVRContext ctx) { GVRSceneObject bus = new GVRSceneObject(ctx, busMesh, busTex); root.addChildObject(bus); return bus; } public GVRSceneObject smoothSetBusPos(GVRSceneObject bus, double lat, double lon) { // 37.809607, -122.387515 // 37.734027, -122.514716 float dx = scaleCoordX((float) lat, 5f) - bus.getTransform().getPositionX(); float dy = scaleCoordY((float) lon, 5f) - bus.getTransform().getPositionY(); GVRAnimation anim = new GVRRelativeMotionAnimation(bus, 1.0f, dx, dy, 0f); anim.start(mCtx.getAnimationEngine()); return bus; } public GVRSceneObject setBusPos(GVRSceneObject bus, double lat, double lon) { // 37.809607, -122.387515 // 37.734027, -122.514716 lat = scaleCoordX((float) lat, 5f); lon = scaleCoordY((float) lon, 5f); bus.getTransform().setPosition((float) lat, (float) lon, -5f); return bus; } /** * Scales a coordinate * * @param min * @param max * @param val * @param extent * @return */ private float scaleCoord(float min, float max, float val, float extent) { float fmin = Math.min(min, max); float fmax = Math.max(min, max); float diff = fmax - fmin; float scale = (val - fmin) / diff; return ((extent * 2 * scale) - extent) * 0.8f; } private float scaleCoordX(float val, float extent) { return scaleCoord(37.702100f, 37.814604f, val, extent); } private float scaleCoordY(float val, float extent) { return scaleCoord(-122.553643f, -122.35528f, val, extent); } }
package sample.java.project; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Setter; /** * The main class of the application. It contains the main() method, * the first method called. */ @NoArgsConstructor @AllArgsConstructor public class SampleJavaProject implements Runnable { /** The delay between printed messages. */ private static final long PRINT_DELAY = 1000L; /** The name to be printed in the output message. */ @Getter @Setter @NonNull @Parameter(names = "--name", description = "set the user's name", required = true) private String name = "world"; /** Command line parameter for --loop. */ @Parameter(names = "--loop", description = "print endlessly, hotswap demo") private boolean loop = false; /** Command line parameter for --help. */ @Parameter(names = { "-h", "--help" }, description = "print help message") private boolean help = false; /** * Print the "Hello, world!" string. * @param args application input arguments */ public static void main(final String[] args) { /* Parse command line arguments. */ SampleJavaProject sjp = new SampleJavaProject(); try { JCommander jc = new JCommander(sjp, args); if (sjp.help) { jc.usage(); return; } } catch (ParameterException e) { System.err.println("error: " + e.getMessage()); new JCommander(new SampleJavaProject()).usage(); System.exit(-1); } sjp.run(); } /** * Print the "Hello, world!" string. */ public final void sayHello() { System.out.printf("Hello, %s!%n", name); } @Override public final void run() { do { sayHello(); try { Thread.sleep(PRINT_DELAY); } catch (InterruptedException e) { return; } } while (loop); } }
package se.raddo.raddose3D; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /* * TODO: This whole class appears to be overly complicated. The subclass seems * unnecessary and the int->double->int conversion is probably not helpful. */ /** * Returns vertices and indices for use by CrystalPolyhedron. * Vertices have not been rotated by the initial rotation angles * and this must be executed by the Crystal class. This simply * imports data from a text file of OBJ file type. */ public class ImportWireframeObj implements ImportWireframe { /** Import file name of OBJ file type. */ private final String wireframeFileName; /** List of vertices from OBJ file. */ private final List<Triad> vertexTriads; /** List of faces from OBJ file. */ private final List<Triad> faceTriads; /** * Sets up a wireframe object and sets file name for later * importing. * * @param filename .obj filename. */ public ImportWireframeObj(final String filename) { if (filename == null) { throw new IllegalArgumentException( "Filename not found, please set ModelFile"); } wireframeFileName = filename; vertexTriads = new ArrayList<Triad>(); faceTriads = new ArrayList<Triad>(); try { loadWireframeFile(); } catch (IOException e) { throw new IllegalArgumentException( "Could not read wireframe file ".concat(filename), e); } } /** * Opens file and takes any line from the file beginning * with the identifier token (e.g. "v " or "f ") and splits * into the component numbers, and stores the values. * * @throws IOException * Error occured when reading from file. */ private void loadWireframeFile() throws IOException { FileInputStream is = new FileInputStream(wireframeFileName); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; String[] components; while ((line = br.readLine()) != null) { // vertex lines begin with 'v ' if ("v ".equals(line.substring(0, 2))) { components = line.split(" ", -1); // if components are not 4, then this was a false positive if (components.length < 4) { continue; } // components should be: "v", x, y, z. // TODO: there could be a localization bug here Triad newVertex = new Triad( Double.parseDouble(components[1]), Double.parseDouble(components[2]), Double.parseDouble(components[3])); vertexTriads.add(newVertex); } // face lines begin with 'f ' if ("f ".equals(line.substring(0, 2))) { components = line.split(" ", -1); // if components are not 4, then this was a false positive if (components.length < 4) { continue; } // components typically of form: "f", "x//a//e", "y//b//f", "z//c//g". // Require only x, y, z here // TODO: there could be a localization bug here Triad newVertex = new Triad( Double.parseDouble(components[1].split(" Double.parseDouble(components[2].split(" Double.parseDouble(components[3].split(" faceTriads.add(newVertex); } } br.close(); isr.close(); } @Override public double[][] getVertices() { double[][] returnVertices = new double[vertexTriads.size()][3]; for (int i = 0; i < vertexTriads.size(); i++) { System .arraycopy(vertexTriads.get(i).getXYZ(), 0, returnVertices[i], 0, 3); } return returnVertices; } @Override public int[][] getIndices() { int[][] returnIndices = new int[faceTriads.size()][3]; for (int i = 0; i < faceTriads.size(); i++) { double[] xyz = faceTriads.get(i).getXYZ(); returnIndices[i][0] = (int) xyz[0]; returnIndices[i][1] = (int) xyz[1]; returnIndices[i][2] = (int) xyz[2]; } return returnIndices; } /** * Small triad class which looks after xyz coordinates before * being sent back to the caller object. */ private static class Triad { /** xyz coordinates. */ private double[] xyz = new double[3]; /** * constructor with particular xyz. * * @param newXYZ new xyz coordinates */ public Triad(final double[] newXYZ) { System.arraycopy(newXYZ, 0, xyz, 0, 3); } /** * constructor with particular xyz. * * @param x x coordinate. * @param y y coordinate. * @param z z coordinate. */ public Triad(final double x, final double y, final double z) { xyz[0] = x; xyz[1] = y; xyz[2] = z; } /** * xyz setter. * * @param newXYZ new xyz coordinates. */ @Deprecated public void setXyz(final double[] newXYZ) { System.arraycopy(newXYZ, 0, xyz, 0, 3); } /** * xyz getter. * * @return stored xyz coordinates */ public double[] getXYZ() { double[] returnXYZ = new double[3]; System.arraycopy(xyz, 0, returnXYZ, 0, 3); return returnXYZ; } } }
package de.nitri.gauge; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RadialGradient; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.Typeface; import android.os.Bundle; import android.os.Parcelable; import android.text.Html; import android.text.Spanned; import android.util.AttributeSet; import android.util.Log; import android.view.View; public class Gauge extends View { private Paint needlePaint; private Path needlePath; private Paint needleScrewPaint; private float canvasCenterX; private float canvasCenterY; private float canvasWidth; private float canvasHeight; private float needleTailLength; private float needleWidth; private float needleLength; private RectF rimRect; private Paint rimPaint; private Paint rimCirclePaint; private RectF faceRect; private Paint facePaint; private Paint rimShadowPaint; private Paint scalePaint; private RectF scaleRect; private int totalNicks = 120; // on a full circle private float degreesPerNick = totalNicks / 360; private float valuePerNick = 10; private float minValue = 0; private float maxValue = 1000; private boolean intScale = true; private float requestedLabelTextSize = 0; private float initialValue = 0; private float value = 0; private float needleValue = 0; private float needleStep; private float centerValue; private float labelRadius; private int majorNickInterval = 10; private int deltaTimeInterval = 5; private float needleStepFactor = 3f; private static final String TAG = Gauge.class.getSimpleName(); private Paint labelPaint; private long lastMoveTime; private boolean needleShadow = true; private int faceColor; private int scaleColor; private int needleColor; private Paint upperTextPaint; private Paint lowerTextPaint; private float requestedTextSize = 0; private float requestedUpperTextSize = 0; private float requestedLowerTextSize = 0; private String upperText = ""; private String lowerText = ""; private float textScaleFactor; private static final int REF_MAX_PORTRAIT_CANVAS_SIZE = 1080; // reference size, scale text accordingly public Gauge(Context context) { super(context); initValues(); initPaint(); } public Gauge(Context context, AttributeSet attrs) { super(context, attrs); applyAttrs(context, attrs); initValues(); initPaint(); } public Gauge(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); applyAttrs(context, attrs); initValues(); initPaint(); } private void applyAttrs(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Gauge, 0, 0); totalNicks = a.getInt(R.styleable.Gauge_totalNicks, totalNicks); degreesPerNick = 360.0f / totalNicks; valuePerNick = a.getFloat(R.styleable.Gauge_valuePerNick, valuePerNick); majorNickInterval = a.getInt(R.styleable.Gauge_majorNickInterval, 10); minValue = a.getFloat(R.styleable.Gauge_minValue, minValue); maxValue = a.getFloat(R.styleable.Gauge_maxValue, maxValue); intScale = a.getBoolean(R.styleable.Gauge_intScale, intScale); initialValue = a.getFloat(R.styleable.Gauge_initialValue, initialValue); requestedLabelTextSize = a.getFloat(R.styleable.Gauge_labelTextSize, requestedLabelTextSize); faceColor = a.getColor(R.styleable.Gauge_faceColor, Color.argb(0xff, 0xff, 0xff, 0xff)); scaleColor = a.getColor(R.styleable.Gauge_scaleColor, 0x9f004d0f); needleColor = a.getColor(R.styleable.Gauge_needleColor, Color.RED); needleShadow = a.getBoolean(R.styleable.Gauge_needleShadow, needleShadow); requestedTextSize = a.getFloat(R.styleable.Gauge_textSize, requestedTextSize); upperText = a.getString(R.styleable.Gauge_upperText) == null ? upperText : fromHtml(a.getString(R.styleable.Gauge_upperText)).toString(); lowerText = a.getString(R.styleable.Gauge_lowerText) == null ? lowerText : fromHtml(a.getString(R.styleable.Gauge_lowerText)).toString(); requestedUpperTextSize = a.getFloat(R.styleable.Gauge_upperTextSize, 0); requestedLowerTextSize = a.getFloat(R.styleable.Gauge_lowerTextSize, 0); a.recycle(); validate(); } private void initValues() { needleStep = needleStepFactor * valuePerDegree(); centerValue = (minValue + maxValue) / 2; needleValue = value = initialValue; int widthPixels = getResources().getDisplayMetrics().widthPixels; textScaleFactor = (float) widthPixels / (float) REF_MAX_PORTRAIT_CANVAS_SIZE; if (getResources().getBoolean(R.bool.landscape)) { int heightPixels = getResources().getDisplayMetrics().heightPixels; float portraitAspectRatio = (float) heightPixels / (float) widthPixels; textScaleFactor = textScaleFactor * portraitAspectRatio; } } private void initPaint() { setSaveEnabled(true); // Rim and shadow are based on the Vintage Thermometer: rimPaint = new Paint(); rimPaint.setFlags(Paint.ANTI_ALIAS_FLAG); rimCirclePaint = new Paint(); rimCirclePaint.setAntiAlias(true); rimCirclePaint.setStyle(Paint.Style.STROKE); rimCirclePaint.setColor(Color.argb(0x4f, 0x33, 0x36, 0x33)); rimCirclePaint.setStrokeWidth(0.005f); facePaint = new Paint(); facePaint.setAntiAlias(true); facePaint.setStyle(Paint.Style.FILL); facePaint.setColor(faceColor); rimShadowPaint = new Paint(); rimShadowPaint.setStyle(Paint.Style.FILL); scalePaint = new Paint(); scalePaint.setStyle(Paint.Style.STROKE); scalePaint.setAntiAlias(true); scalePaint.setColor(scaleColor); labelPaint = new Paint(); labelPaint.setColor(scaleColor); labelPaint.setTypeface(Typeface.SANS_SERIF); labelPaint.setTextAlign(Paint.Align.CENTER); upperTextPaint = new Paint(); upperTextPaint.setColor(scaleColor); upperTextPaint.setTypeface(Typeface.SANS_SERIF); upperTextPaint.setTextAlign(Paint.Align.CENTER); lowerTextPaint = new Paint(); lowerTextPaint.setColor(scaleColor); lowerTextPaint.setTypeface(Typeface.SANS_SERIF); lowerTextPaint.setTextAlign(Paint.Align.CENTER); needlePaint = new Paint(); needlePaint.setColor(needleColor); needlePaint.setStyle(Paint.Style.FILL_AND_STROKE); needlePaint.setAntiAlias(true); needlePath = new Path(); needleScrewPaint = new Paint(); needleScrewPaint.setColor(Color.BLACK); needleScrewPaint.setAntiAlias(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawRim(canvas); drawFace(canvas); drawScale(canvas); drawLabels(canvas); drawTexts(canvas); canvas.rotate(scaleToCanvasDegrees(valueToDegrees(needleValue)), canvasCenterX, canvasCenterY); canvas.drawPath(needlePath, needlePaint); canvas.drawCircle(canvasCenterX, canvasCenterY, canvasWidth / 61f, needleScrewPaint); if (needsToMove()) { moveNeedle(); } } private void moveNeedle() { long currentTime = System.currentTimeMillis(); long deltaTime = currentTime - lastMoveTime; if (deltaTime >= deltaTimeInterval) { if (Math.abs(value - needleValue) <= needleStep) { needleValue = value; } else { if (value > needleValue) { needleValue += 2 * valuePerDegree(); } else { needleValue -= 2 * valuePerDegree(); } } lastMoveTime = System.currentTimeMillis(); postInvalidateDelayed(deltaTimeInterval); } } private void drawRim(Canvas canvas) { canvas.drawOval(rimRect, rimPaint); canvas.drawOval(rimRect, rimCirclePaint); } private void drawFace(Canvas canvas) { canvas.drawOval(faceRect, facePaint); canvas.drawOval(faceRect, rimCirclePaint); canvas.drawOval(faceRect, rimShadowPaint); } private void drawScale(Canvas canvas) { canvas.save(); for (int i = 0; i < totalNicks; ++i) { float y1 = scaleRect.top; float y2 = y1 + (0.020f * canvasHeight); float y3 = y1 + (0.060f * canvasHeight); float y4 = y1 + (0.030f * canvasHeight); float value = nickToValue(i); if (value >= minValue && value <= maxValue) { canvas.drawLine(0.5f * canvasWidth, y1, 0.5f * canvasWidth, y2, scalePaint); if (i % majorNickInterval == 0) { canvas.drawLine(0.5f * canvasWidth, y1, 0.5f * canvasWidth, y3, scalePaint); } if (i % (majorNickInterval / 2) == 0) { canvas.drawLine(0.5f * canvasWidth, y1, 0.5f * canvasWidth, y4, scalePaint); } } canvas.rotate(degreesPerNick, 0.5f * canvasWidth, 0.5f * canvasHeight); } canvas.restore(); } private void drawLabels(Canvas canvas) { for (int i = 0; i < totalNicks; i += majorNickInterval) { float value = nickToValue(i); if (value >= minValue && value <= maxValue) { float scaleAngle = i * degreesPerNick; float scaleAngleRads = (float) Math.toRadians(scaleAngle); //Log.d(TAG, "i = " + i + ", angle = " + scaleAngle + ", value = " + value); float deltaX = labelRadius * (float) Math.sin(scaleAngleRads); float deltaY = labelRadius * (float) Math.cos(scaleAngleRads); String valueLabel; if (intScale) { valueLabel = String.valueOf((int) value); } else { valueLabel = String.valueOf(value); } drawTextCentered(valueLabel, canvasCenterX + deltaX, canvasCenterY - deltaY, labelPaint, canvas); } } } private void drawTexts(Canvas canvas) { drawTextCentered(upperText, canvasCenterX, canvasCenterY - (canvasHeight / 6.5f), upperTextPaint, canvas); drawTextCentered(lowerText, canvasCenterX, canvasCenterY + (canvasHeight / 6.5f), lowerTextPaint, canvas); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { canvasWidth = (float) w; canvasHeight = (float) h; canvasCenterX = w / 2f; canvasCenterY = h / 2f; needleTailLength = canvasWidth / 12f; needleWidth = canvasWidth / 98f; needleLength = (canvasWidth / 2f) * 0.8f; needlePaint.setStrokeWidth(canvasWidth / 197f); if (needleShadow) needlePaint.setShadowLayer(canvasWidth / 123f, canvasWidth / 10000f, canvasWidth / 10000f, Color.GRAY); setNeedle(); rimRect = new RectF(canvasWidth * .05f, canvasHeight * .05f, canvasWidth * 0.95f, canvasHeight * 0.95f); rimPaint.setShader(new LinearGradient(canvasWidth * 0.40f, canvasHeight * 0.0f, canvasWidth * 0.60f, canvasHeight * 1.0f, Color.rgb(0xf0, 0xf5, 0xf0), Color.rgb(0x30, 0x31, 0x30), Shader.TileMode.CLAMP)); float rimSize = 0.02f * canvasWidth; faceRect = new RectF(); faceRect.set(rimRect.left + rimSize, rimRect.top + rimSize, rimRect.right - rimSize, rimRect.bottom - rimSize); rimShadowPaint.setShader(new RadialGradient(0.5f * canvasWidth, 0.5f * canvasHeight, faceRect.width() / 2.0f, new int[]{0x00000000, 0x00000500, 0x50000500}, new float[]{0.96f, 0.96f, 0.99f}, Shader.TileMode.MIRROR)); scalePaint.setStrokeWidth(0.005f * canvasWidth); scalePaint.setTextSize(0.045f * canvasWidth); scalePaint.setTextScaleX(0.8f * canvasWidth); float scalePosition = 0.015f * canvasWidth; scaleRect = new RectF(); scaleRect.set(faceRect.left + scalePosition, faceRect.top + scalePosition, faceRect.right - scalePosition, faceRect.bottom - scalePosition); labelRadius = (canvasCenterX - scaleRect.left) * 0.70f; /* Log.d(TAG, "width = " + w); Log.d(TAG, "height = " + h); Log.d(TAG, "width pixels = " + getResources().getDisplayMetrics().widthPixels); Log.d(TAG, "height pixels = " + getResources().getDisplayMetrics().heightPixels); Log.d(TAG, "density = " + getResources().getDisplayMetrics().density); Log.d(TAG, "density dpi = " + getResources().getDisplayMetrics().densityDpi); Log.d(TAG, "scaled density = " + getResources().getDisplayMetrics().scaledDensity); */ float textSize; if (requestedLabelTextSize > 0) { textSize = requestedLabelTextSize * textScaleFactor; } else { textSize = canvasWidth / 16f; } Log.d(TAG, "Label text size = " + textSize); labelPaint.setTextSize(textSize); if (requestedTextSize > 0) { textSize = requestedTextSize * textScaleFactor; } else { textSize = canvasWidth / 14f; } Log.d(TAG, "Default upper/lower text size = " + textSize); upperTextPaint.setTextSize(requestedUpperTextSize > 0 ? requestedUpperTextSize * textScaleFactor: textSize); lowerTextPaint.setTextSize(requestedLowerTextSize > 0 ? requestedLowerTextSize * textScaleFactor: textSize); super.onSizeChanged(w, h, oldw, oldh); } private void setNeedle() { needlePath.reset(); needlePath.moveTo(canvasCenterX - needleTailLength, canvasCenterY); needlePath.lineTo(canvasCenterX, canvasCenterY - (needleWidth / 2)); needlePath.lineTo(canvasCenterX + needleLength, canvasCenterY); needlePath.lineTo(canvasCenterX, canvasCenterY + (needleWidth / 2)); needlePath.lineTo(canvasCenterX - needleTailLength, canvasCenterY); needlePath.addCircle(canvasCenterX, canvasCenterY, canvasWidth / 49f, Path.Direction.CW); needlePath.close(); needleScrewPaint.setShader(new RadialGradient(canvasCenterX, canvasCenterY, needleWidth / 2, Color.DKGRAY, Color.BLACK, Shader.TileMode.CLAMP)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int size; int width = getMeasuredWidth(); int height = getMeasuredHeight(); int widthWithoutPadding = width - getPaddingLeft() - getPaddingRight(); int heightWithoutPadding = height - getPaddingTop() - getPaddingBottom(); if (widthWithoutPadding > heightWithoutPadding) { size = heightWithoutPadding; } else { size = widthWithoutPadding; } setMeasuredDimension(size + getPaddingLeft() + getPaddingRight(), size + getPaddingTop() + getPaddingBottom()); } @Override protected Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); bundle.putParcelable("superState", super.onSaveInstanceState()); bundle.putFloat("value", value); bundle.putFloat("needleValue", needleValue); return bundle; } @Override protected void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle) state; value = bundle.getFloat("value"); needleValue = bundle.getFloat("needleValue"); super.onRestoreInstanceState(bundle.getParcelable("superState")); } else { super.onRestoreInstanceState(state); } } private float nickToValue(int nick) { float rawValue = ((nick < totalNicks / 2) ? nick : (nick - totalNicks)) * valuePerNick; return rawValue + centerValue; } private float valueToDegrees(float value) { // these are scale degrees, 0 is on top return ((value - centerValue) / valuePerNick) * degreesPerNick; } private float valuePerDegree() { return valuePerNick / degreesPerNick; } private float scaleToCanvasDegrees(float degrees) { return degrees - 90; } private boolean needsToMove() { return Math.abs(needleValue - value) > 0; } private void drawTextCentered(String text, float x, float y, Paint paint, Canvas canvas) { //float xPos = x - (paint.measureText(text)/2f); float yPos = (y - ((paint.descent() + paint.ascent()) / 2f)); canvas.drawText(text, x, yPos, paint); } /** * Set gauge to value. * * @param value Value */ public void setValue(float value) { needleValue = this.value = value; invalidate(); } /** * Animate gauge to value. * * @param value Value */ public void moveToValue(float value) { this.value = value; invalidate(); } /** * Set string to display on upper gauge face. * * @param text Text */ public void setUpperText(String text) { upperText = text; invalidate(); } /** * Set string to display on lower gauge face. * * @param text Text */ public void setLowerText(String text) { lowerText = text; invalidate(); } /** * Request a text size. * * @param size Size (pixels) * @see Paint#setTextSize(float); */ @Deprecated public void setRequestedTextSize(float size) { setTextSize(size); } /** * Set a text size for the upper and lower text. * * Size is in pixels at a screen width (max. canvas width/height) of 1080 and is scaled * accordingly at different resolutions. E.g. a value of 48 is unchanged at 1080 x 1920 * and scaled down to 27 at 600 x 1024. * * @param size Size (relative pixels) * @see Paint#setTextSize(float); */ public void setTextSize(float size) { requestedTextSize = size; } /** * Set or override the text size for the upper text. * * Size is in pixels at a screen width (max. canvas width/height) of 1080 and is scaled * accordingly at different resolutions. E.g. a value of 48 is unchanged at 1080 x 1920 * and scaled down to 27 at 600 x 1024. * * @param size (relative pixels) * @see Paint#setTextSize(float); */ public void setUpperTextSize(float size) { requestedUpperTextSize = size; } /** * Set or override the text size for the lower text * * Size is in pixels at a screen width (max. canvas width/height) of 1080 and is scaled * accordingly at different resolutions. E.g. a value of 48 is unchanged at 1080 x 1920 * and scaled down to 27 at 600 x 1024. * * @param size (relative pixels) * @see Paint#setTextSize(float); */ public void setLowerTextSize(float size) { requestedLowerTextSize = size; } /** * Set the delta time between movement steps during needle animation (default: 5 ms). * * @param interval Time (ms) */ public void setDeltaTimeInterval(int interval) { deltaTimeInterval = interval; } /** * Set the factor that determines the step size during needle animation (default: 3f). * The actual step size is calulated as follows: step_size = step_factor * scale_value_per_degree. * * @param factor Step factor */ public void setNeedleStepFactor(float factor) { needleStepFactor = factor; } /** * Set the minimum scale value. * * @param value minimum value */ public void setMinValue(float value) { minValue = value; initValues(); validate(); invalidate(); } /** * Set the maximum scale value. * * @param value maximum value */ public void setMaxValue(float value) { maxValue = value; initValues(); validate(); invalidate(); } /** * Set the total amount of nicks on a full 360 degree scale. Should be a multiple of majorNickInterval. * * @param nicks number of nicks */ public void setTotalNicks(int nicks) { totalNicks = nicks; degreesPerNick = 360.0f / totalNicks; initValues(); validate(); invalidate(); } /** * Set the value (interval) per nick. * * @param value value per nick */ public void setValuePerNick(float value) { valuePerNick = value; initValues(); validate(); invalidate(); } /** * Set the interval (number of nicks) between enlarged nicks. * * @param interval major nick interval */ public void setMajorNickInterval(int interval) { majorNickInterval = interval; validate(); invalidate(); } private void validate() { boolean valid = true; if (totalNicks % majorNickInterval != 0) { valid = false; Log.w(TAG, getResources().getString(R.string.invalid_number_of_nicks, totalNicks, majorNickInterval)); } float sum = minValue + maxValue; int intSum = Math.round(sum); if ((maxValue >= 1 && (sum != intSum || (intSum & 1) != 0)) || minValue >= maxValue) { valid = false; Log.w(TAG, getResources().getString(R.string.invalid_min_max_ratio, minValue, maxValue)); } if (Math.round(sum % valuePerNick) != 0) { valid = false; Log.w(TAG, getResources().getString(R.string.invalid_min_max, minValue, maxValue, valuePerNick)); } if (valid) Log.i(TAG, getResources().getString(R.string.scale_ok)); } @SuppressWarnings("deprecation") private static Spanned fromHtml(String html) { Spanned result; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY); } else { result = Html.fromHtml(html); } return result; } }
package com.badlogic.gdx.net; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Net; import com.badlogic.gdx.Net.HttpMethods; import com.badlogic.gdx.Net.HttpRequest; import com.badlogic.gdx.Net.HttpResponse; import com.badlogic.gdx.Net.HttpResponseListener; import com.badlogic.gdx.StreamUtils; import com.badlogic.gdx.utils.GdxRuntimeException; /** Implements part of the {@link Net} API using {@link HttpURLConnection}, to be easily reused between the Android and Desktop * backends. * @author acoppes */ public class NetJavaImpl { static class HttpClientResponse implements HttpResponse { private HttpURLConnection connection; private HttpStatus status; private InputStream inputStream; public HttpClientResponse (HttpURLConnection connection) throws IOException { this.connection = connection; this.inputStream = connection.getInputStream(); try { this.status = new HttpStatus(connection.getResponseCode()); } catch (IOException e) { this.status = new HttpStatus(-1); } } @Override public byte[] getResult () { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; try { while ((nRead = inputStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); } catch (IOException e) { return new byte[0]; } return buffer.toByteArray(); } @Override public String getResultAsString () { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String tmp, line = ""; try { while ((tmp = reader.readLine()) != null) line += tmp; reader.close(); return line; } catch (IOException e) { return ""; } } @Override public InputStream getResultAsStream () { return inputStream; } @Override public HttpStatus getStatus () { return status; } } private final ExecutorService executorService; public NetJavaImpl () { executorService = Executors.newCachedThreadPool(); } public void sendHttpRequest (final HttpRequest httpRequest, final HttpResponseListener httpResponseListener) { if (httpRequest.getUrl() == null) { httpResponseListener.failed(new GdxRuntimeException("can't process a HTTP request without URL set")); return; } try { final String method = httpRequest.getMethod(); URL url; if (method.equalsIgnoreCase(HttpMethods.GET)) { String queryString = ""; String value = httpRequest.getContent(); if (value != null && !"".equals(value)) queryString = "?" + value; url = new URL(httpRequest.getUrl() + queryString); } else { url = new URL(httpRequest.getUrl()); } final HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // should be enabled to upload data. connection.setDoOutput(method.equalsIgnoreCase(HttpMethods.POST)); connection.setDoInput(true); connection.setRequestMethod(method); // Headers get set regardless of the method Map<String, String> headers = httpRequest.getHeaders(); Set<String> keySet = headers.keySet(); for (String name : keySet) connection.addRequestProperty(name, headers.get(name)); // Set Timeouts connection.setConnectTimeout(httpRequest.getTimeOut()); connection.setReadTimeout(httpRequest.getTimeOut()); executorService.submit(new Runnable() { @Override public void run () { try { // Set the content for POST (GET has the information embedded in the URL) if (method.equalsIgnoreCase(HttpMethods.POST)) { // we probably need to use the content as stream here instead of using it as a string. String contentAsString = httpRequest.getContent(); InputStream contentAsStream = httpRequest.getContentStream(); OutputStream outputStream = connection.getOutputStream(); if (contentAsString != null) { OutputStreamWriter writer = new OutputStreamWriter(outputStream); writer.write(contentAsString); writer.flush(); writer.close(); } else if (contentAsStream != null) { StreamUtils.copyStream(contentAsStream, outputStream); outputStream.flush(); outputStream.close(); } } connection.connect(); final HttpClientResponse clientResponse = new HttpClientResponse(connection); // post a runnable to sync the handler with the main thread Gdx.app.postRunnable(new Runnable() { @Override public void run () { try { httpResponseListener.handleHttpResponse(clientResponse); } finally { connection.disconnect(); } } }); } catch (final Exception e) { // post a runnable to sync the handler with the main thread Gdx.app.postRunnable(new Runnable() { @Override public void run () { connection.disconnect(); httpResponseListener.failed(e); } }); } // finally { // connection.disconnect(); } }); } catch (Exception e) { httpResponseListener.failed(e); return; } } }
package ui; import ui.event.MenuEvent; import javax.swing.*; import java.awt.*; public class MainMenuPanel extends JPanel { // Variables declaration private JButton hostGameButton; private JButton joinGameButton; private JButton logoutButton; private JButton creditsButton; /** * Creates new form MainMenuPanel */ public MainMenuPanel() { initComponents(); } @SuppressWarnings("unchecked") private void initComponents() { setLayout(new BorderLayout()); addMenu(); addBottomPanel(); } private void addMenu() { JPanel menuWrapper = new JPanel(); menuWrapper.setLayout(new BoxLayout(menuWrapper, BoxLayout.Y_AXIS)); hostGameButton = new JButton(); creditsButton = new JButton(); joinGameButton = new JButton(); hostGameButton.setText("HOST GAME"); hostGameButton.setBackground(Color.white); hostGameButton.setAlignmentX(Component.CENTER_ALIGNMENT); joinGameButton.setText("JOIN GAME"); joinGameButton.setBackground(Color.white); joinGameButton.setAlignmentX(Component.CENTER_ALIGNMENT); creditsButton.setText("CREDITS"); creditsButton.setBackground(Color.white); creditsButton.setAlignmentX(Component.CENTER_ALIGNMENT); menuWrapper.add(hostGameButton); menuWrapper.add(joinGameButton); menuWrapper.add(creditsButton); add(menuWrapper, BorderLayout.CENTER); } private void addBottomPanel() { JPanel bottomWrapper = new JPanel(); JLabel accountStatusLabel = new JLabel(); logoutButton = new JButton(); accountStatusLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N accountStatusLabel.setText("signed in as XXX"); logoutButton.setText("LOG OUT"); logoutButton.setBackground(Color.white); bottomWrapper.add(accountStatusLabel); bottomWrapper.add(logoutButton); add(bottomWrapper, BorderLayout.SOUTH); } public void setMenuEventListeners(MenuEvent.Listener listener) { hostGameButton.addActionListener(event -> listener.onMenuEvent(MenuEvent.ItemType.host)); joinGameButton.addActionListener(event -> listener.onMenuEvent(MenuEvent.ItemType.join)); creditsButton.addActionListener(event -> listener.onMenuEvent(MenuEvent.ItemType.credits)); logoutButton.addActionListener(event -> listener.onMenuEvent(MenuEvent.ItemType.logout)); } }
package BlueTurtle.TSE; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.junit.Before; import org.junit.Test; /** * Unit test for simple Analyser. */ public class AnalyserTest { @Before public void initialize() throws IOException { JavaController javacontroller = new JavaController(); javacontroller.execute(); } /** * Simple test to check if running the analyser actually produces output for checkstyle. * @throws IOException */ @Test public void testCheckStyleOutput() throws IOException { BufferedReader br = new BufferedReader(new FileReader(JavaController.getUserDir() + "/Runnables/Testcode/checkstyle.xml")); assert(br.readLine() != null); } /** * Simple test to check if running the analyser actually produces output for PMD. * @throws IOException */ @Test public void testPMDOutput() throws IOException { BufferedReader br = new BufferedReader(new FileReader(JavaController.getUserDir() + "/Runnables/Testcode/pmd.xml")); assert(br.readLine() != null); } }
package VASSAL.tools.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.util.Arrays; import java.util.Random; import java.util.zip.ZipFile; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import org.apache.commons.io.input.ClosedInputStream; import org.apache.commons.io.input.NullInputStream; import org.apache.commons.io.FileUtils; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; @RunWith(JMock.class) public class IOUtilsTest { protected final Mockery context = new JUnit4Mockery(); @Test public void testCopyFileChannels() throws IOException { final File ifile = new File("test/VASSAL/tools/io/IOUtilsTest.java"); final File ofile = new File("test/VASSAL/tools/io/test.out"); try { final FileInputStream in = new FileInputStream(ifile); final FileOutputStream out = new FileOutputStream(ofile); final int count = IOUtils.copy(in, out); assertEquals(ifile.length(), count); assertTrue(FileUtils.contentEquals(ifile, ofile)); } finally { ofile.delete(); } } @Test public void testCopyLargeFileChannels() throws IOException { final File ifile = new File("test/VASSAL/tools/io/IOUtilsTest.java"); final File ofile = new File("test/VASSAL/tools/io/test.out"); try { final FileInputStream in = new FileInputStream(ifile); final FileOutputStream out = new FileOutputStream(ofile); final long count = IOUtils.copy(in, out); assertEquals(ifile.length(), count); assertTrue(FileUtils.contentEquals(ifile, ofile)); } finally { ofile.delete(); } } @Test public void testCopyBuffer() throws IOException { final byte[] buf = new byte[1024]; final byte[] expected = new byte[10000]; final long seed = System.currentTimeMillis(); final Random rng = new Random(seed); rng.nextBytes(expected); final ByteArrayInputStream in = new ByteArrayInputStream(expected); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final int count = IOUtils.copy(in, out, buf); assertEquals("seed == " + seed, expected.length, count); assertArrayEquals("seed == " + seed, expected, out.toByteArray()); } @Test public void testCopyLargeBuffer() throws IOException { final byte[] buf = new byte[1024]; final byte[] expected = new byte[10000]; final long seed = System.currentTimeMillis(); final Random rng = new Random(seed); rng.nextBytes(expected); final ByteArrayInputStream in = new ByteArrayInputStream(expected); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final long count = IOUtils.copyLarge(in, out, buf); assertEquals("seed == " + seed, expected.length, count); assertArrayEquals("seed == " + seed, expected, out.toByteArray()); } }
package de.bmoth.app; import javafx.stage.Stage; import org.junit.After; import org.junit.BeforeClass; import org.testfx.framework.junit.ApplicationTest; import org.testfx.util.WaitForAsyncUtils; import java.util.concurrent.TimeoutException; import static org.testfx.api.FxToolkit.setupStage; public abstract class HeadlessUITest extends ApplicationTest { @BeforeClass public static void setupHeadlessIfRequested() { if (Boolean.getBoolean("headless")) { System.setProperty("testfx.robot", "glass"); System.setProperty("testfx.headless", "true"); System.setProperty("prism.order", "sw"); System.setProperty("prism.text", "t2k"); System.setProperty("java.awt.headless", "true"); } } @After public void cleanup() throws TimeoutException { WaitForAsyncUtils.waitForFxEvents(); setupStage(Stage::close); } }
package jwbroek.io; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.*; import java.util.regex.Pattern; /** * Unit test for {@link jwbroek.io.FileSelector}. * * @author jwbroek */ public class FileSelectorTest { /** * The root of the testing environment. */ private File testRoot; /** * Maximum number of files to create. */ private final static int maxFiles = 200; /** * First file will have a name based on this number. */ private final static int firstFile = 1000; /** * Maximum number of directories to create. */ private final static int maxDirs = 30; /** * First directories will have a name based on this number. */ private final static int firstDir = 2000; /** * Prefix for numbered files in the root directory. Numbers range from {@link FileSelectorTest#firstFile} to * {@link FileSelectorTest#firstFile} + {@link FileSelectorTest#maxFiles}. */ private final static String rootFilePrefix = "testFile"; /** * Prefix for numbered subdirs in the root directory. Numbers range from {@link FileSelectorTest#firstDir} to * {@link FileSelectorTest#firstDir} + {@link FileSelectorTest#maxDirs}. */ private final static String rootSubdirPrefix = "testDir"; /** * <p>Create a testing environment containing various files and directories.</p> * <p>The layout is as follows: ([] is directory; {} is logical name (not actual name))</p> * <ul> * <li>[{testRoot}]</li> * <ul> * <li>{rootFilePrefix}{firstFile}</li> * <li>...</li> * <li>{rootFilePrefix}{firstFile+maxFiles-1}</li> * <li>{testRoot}file</li> * <li>[{rootFilePrefix}{firstDir}]</li> * <li>[...]</li> * <li>[testDir{firstDir+maxDirs-1}]</li> * <li>[{testRoot}]</li> * <li>[a]</li> * <ul> * <li>[a]</li> * <ul> * <li>a</li> * <li>[b1]</li> * <li>[b2]</li> * <li>b3</li> * <li>b4</li> * </ul> * <li>[b1]</li> * <li>[b2]</li> * <li>b3</li> * <li>b4</li> * </ul> * </ul> * </ul> * * @throws SecurityException * @throws IOException */ @Before public void setUp() throws SecurityException, IOException { // File bound final int fileBound = firstFile + maxFiles; // Dir bound final int dirBound = firstDir + maxDirs; // Create a temporary directory in which to create a test environment. this.testRoot = TemporaryFileCreator.createTemporaryDirectory(); // Create numbered files. for (int fileIndex = firstFile; fileIndex < fileBound; fileIndex++) { TemporaryFileCreator.createNamedTemporaryFileOrDirectory(FileSelectorTest.rootFilePrefix + fileIndex, "", this.testRoot, false, true); } // Create a file with a name that starts with the name of the root directory and ends in "file". TemporaryFileCreator.createNamedTemporaryFileOrDirectory(this.testRoot.getName() + "file", "", this.testRoot, false, true); // Create numbered directories. for (int dirIndex = firstDir; dirIndex < dirBound; dirIndex++) { TemporaryFileCreator.createNamedTemporaryFileOrDirectory("testDir" + dirIndex, "", this.testRoot, true, true); } // Create a directory with the same name as the root directory. TemporaryFileCreator.createNamedTemporaryFileOrDirectory(this.testRoot.getName(), "", this.testRoot, true, true); // Create a directory called "a" in the root. File newRootDir = TemporaryFileCreator.createNamedTemporaryFileOrDirectory("a", "", this.testRoot, true, true); // Create a subdirectory "a" in directory "a", as well as b1...b4. File subDir = TemporaryFileCreator.createNamedTemporaryFileOrDirectory("a", "", newRootDir, true, true); TemporaryFileCreator.createNamedTemporaryFileOrDirectory("b1", "", newRootDir, true, true); TemporaryFileCreator.createNamedTemporaryFileOrDirectory("b2", "", newRootDir, true, true); TemporaryFileCreator.createNamedTemporaryFileOrDirectory("b3", "", newRootDir, false, true); TemporaryFileCreator.createNamedTemporaryFileOrDirectory("b4", "", newRootDir, false, true); // Create a file "a" in directory "a/a", as well as b1...b4. TemporaryFileCreator.createNamedTemporaryFileOrDirectory("a", "", subDir, false, true); TemporaryFileCreator.createNamedTemporaryFileOrDirectory("b1", "", subDir, true, true); TemporaryFileCreator.createNamedTemporaryFileOrDirectory("b2", "", subDir, true, true); TemporaryFileCreator.createNamedTemporaryFileOrDirectory("b3", "", subDir, false, true); TemporaryFileCreator.createNamedTemporaryFileOrDirectory("b4", "", subDir, false, true); } /** * Clean up the testing environment. */ @After public void cleanUp() { // Delete the temporary file. First check if creation went OK. if (this.testRoot != null) { this.testRoot.delete(); } } /** * Test for {@link FileSelector#getDirsFilter()}. */ @Test public void testDirsFileFilter() throws IOException { FileFilter filter = FileSelector.getDirsFilter(); Set<File> prediction = new HashSet<File>(); final int bound = FileSelectorTest.firstDir + FileSelectorTest.maxDirs; for (int index = FileSelectorTest.firstDir; index < bound; index++) { prediction.add(new File(this.testRoot, FileSelectorTest.rootSubdirPrefix + index)); } prediction.add(new File(this.testRoot, this.testRoot.getName())); prediction.add(new File(this.testRoot, "a")); testFileFilter(this.testRoot, filter, prediction, "FileSelector.getDirsFilter()"); } /** * Test for {@link FileSelector#getFilesFilter()}. */ @Test public void testFilesFileFilter() throws IOException { FileFilter filter = FileSelector.getFilesFilter(); Set<File> prediction = new HashSet<File>(); final int bound = FileSelectorTest.firstFile + FileSelectorTest.maxFiles; for (int index = FileSelectorTest.firstFile; index < bound; index++) { prediction.add(new File(this.testRoot, FileSelectorTest.rootFilePrefix + index)); } prediction.add(new File(this.testRoot, this.testRoot.getName() + "file")); testFileFilter(this.testRoot, filter, prediction, "FileSelector.testFilesFileFilter()"); } /** * Test for {@link FileSelector#getFileNamePatternFilter(Pattern)}. */ @Test public void testFileNamePatternFilter() { // Create a FileNamePatternFilter that must match any file of which the name begins with "test", then either // "File" or "Dir", then 3 digits, and then a "1" or "2". No other files must be matched. FileFilter filter = FileSelector.getFileNamePatternFilter(Pattern.compile("test(?:File|Dir)\\d{3}[12].*")); Set<File> prediction = new HashSet<File>(); // We can be clever and optimize these loops by using "%", greater increments and some "if" statements. This is // much clearer though, and speed isn't much of an issue, so I'll leave it like this. // Add all qualifying files. final int fileBound = FileSelectorTest.firstFile + FileSelectorTest.maxFiles; for (int index = FileSelectorTest.firstFile; index < fileBound; index++) { if (index > 1000 && index < 10000 && (index % 10 == 1 || index % 10 == 2)) { prediction.add(new File(this.testRoot, FileSelectorTest.rootFilePrefix + index)); } } // Add all qualifying directories. final int dirBound = FileSelectorTest.firstDir + FileSelectorTest.maxDirs; for (int index = FileSelectorTest.firstDir; index < dirBound; index++) { if (index > 1000 && index < 10000 && (index % 10 == 1 || index % 10 == 2)) { prediction.add(new File(this.testRoot, FileSelectorTest.rootSubdirPrefix + index)); } } testFileFilter(this.testRoot, filter, prediction, "FileSelector.getFileNamePatternFilter(Pattern)"); } /** * Create a Pattern that must match any file that starts with the name of its parent directory. * * @return A Pattern that must match any file that starts with the name of its parent directory. */ public static Pattern getParentDirNameAsFileNamePattern() { final String patternDirSeparator = Pattern.quote(File.separator); final StringBuilder patternHelper = new StringBuilder(".*").append(patternDirSeparator).append("([^").append(patternDirSeparator).append("]*)").append(patternDirSeparator).append("\\1[^").append(patternDirSeparator).append("]*").append(patternDirSeparator).append("?$"); return Pattern.compile(patternHelper.toString()); } /** * Test for {@link FileSelector#getPathPatternFilter(Pattern)}. */ @Test public void testPathPatternFilter() { // Create a FileNamePatternFilter that must match any file that starts with the name of its parent directory. final FileFilter filter = FileSelector.getPathPatternFilter(FileSelectorTest.getParentDirNameAsFileNamePattern()); final Set<File> prediction = new HashSet<File>(); prediction.add(new File(this.testRoot, this.testRoot.getName() + "file")); prediction.add(new File(this.testRoot, this.testRoot.getName())); testFileFilter(this.testRoot, filter, prediction, "FileSelector.getPathPatternFilter(Pattern)"); } /** * Test for {@link FileSelector#getCombinedFileFilter(FileFilter[])} and * {@link FileSelector#getCombinedFileFilter(Iterable)}. */ @Test public void testCombinedFileFilterFromArray() { // Create a CombinedFileFilter that must match only files (not directories) that start with the name // of their parent directory. final FileFilter filesFilter = FileSelector.getFilesFilter(); final FileFilter pathPatternFilter = FileSelector.getPathPatternFilter(FileSelectorTest.getParentDirNameAsFileNamePattern()); final FileFilter combinedFileFilter = FileSelector.getIntersectionFileFilter(filesFilter, pathPatternFilter); final Set<File> prediction = new HashSet<File>(); prediction.add(new File(this.testRoot, this.testRoot.getName() + "file")); testFileFilter(this.testRoot, combinedFileFilter, prediction, "FileSelector.getCombinedFileFilter(FileFilter[])"); } /** * Test for {@link FileSelector#getCombinedFileFilter(Iterable)}. */ @Test public void testCombinedFileFilterFromIterable() { // Create a CombinedFileFilter that must match only files (not directories) that start with the name // of their parent directory. final FileFilter filesFilter = FileSelector.getFilesFilter(); final FileFilter pathPatternFilter = FileSelector.getPathPatternFilter(FileSelectorTest.getParentDirNameAsFileNamePattern()); final List<FileFilter> fileFilterList = new ArrayList<FileFilter>(); fileFilterList.add(filesFilter); fileFilterList.add(pathPatternFilter); final FileFilter combinedFileFilter = FileSelector.getIntersectionFileFilter(fileFilterList); final Set<File> prediction = new HashSet<File>(); prediction.add(new File(this.testRoot, this.testRoot.getName() + "file")); testFileFilter(this.testRoot, combinedFileFilter, prediction, "FileSelector.getCombinedFileFilter(Iterable)"); } /** * Test for {@link FileSelector#getIntersectionFileFilter(FileFilter[])} and * {@link FileSelector#getIntersectionFileFilter(Iterable)}. */ @Test public void testIntersectionFileFilterFromArray() { // Create an IntersectionFileFilter that must match only files (not directories) that start with the name // of their parent directory. final FileFilter filesFilter = FileSelector.getFilesFilter(); final FileFilter pathPatternFilter = FileSelector.getPathPatternFilter(FileSelectorTest.getParentDirNameAsFileNamePattern()); final FileFilter intersectionFileFilter = FileSelector.getIntersectionFileFilter(filesFilter, pathPatternFilter); final Set<File> prediction = new HashSet<File>(); prediction.add(new File(this.testRoot, this.testRoot.getName() + "file")); testFileFilter(this.testRoot, intersectionFileFilter, prediction, "FileSelector.getIntersectionFileFilter(FileFilter[])"); } /** * Test for {@link FileSelector#getIntersectionFileFilter(Iterable)}. */ @Test public void testIntersectionFileFilterFromIterable() { // Create an IntersectionFileFilter that must match only files (not directories) that start with the name // of their parent directory. final FileFilter filesFilter = FileSelector.getFilesFilter(); final FileFilter pathPatternFilter = FileSelector.getPathPatternFilter(FileSelectorTest.getParentDirNameAsFileNamePattern()); final List<FileFilter> fileFilterList = new ArrayList<FileFilter>(); fileFilterList.add(filesFilter); fileFilterList.add(pathPatternFilter); final FileFilter intersectionFileFilter = FileSelector.getIntersectionFileFilter(fileFilterList); final Set<File> prediction = new HashSet<File>(); prediction.add(new File(this.testRoot, this.testRoot.getName() + "file")); testFileFilter(this.testRoot, intersectionFileFilter, prediction, "FileSelector.getIntersectionFileFilter(Iterable)"); } /** * Test for {@link FileSelector#getUnionFileFilter(FileFilter[])} and * {@link FileSelector#getUnionFileFilter(Iterable)}. */ @Test public void testUnionFileFilterFromArray() { // Create an UnionFileFilter that must match only files or directories named "b1" or "b3". final FileFilter unionFileFilter = FileSelector.getUnionFileFilter(FileSelector.getFileNamePatternFilter("b1"), FileSelector.getFileNamePatternFilter("b3")); final Set<File> prediction = new HashSet<File>(); prediction.add(new File(this.testRoot, "a/b1")); prediction.add(new File(this.testRoot, "a/b3")); testFileFilter(new File(this.testRoot, "a"), unionFileFilter, prediction, "FileSelector.getUnionFileFilter(FileFilter[])"); } /** * Test for {@link FileSelector#getUnionFileFilter(Iterable)}. */ @Test public void testUnionFileFilterFromIterable() { // Create an UnionFileFilter that must match only files or directories named "b1" or "b3". final FileFilter nameFilterB1 = FileSelector.getFileNamePatternFilter("b1"); final FileFilter nameFilterB3 = FileSelector.getFileNamePatternFilter("b3"); final List<FileFilter> fileFilterList = new ArrayList<FileFilter>(); fileFilterList.add(nameFilterB1); fileFilterList.add(nameFilterB3); final FileFilter unionFileFilter = FileSelector.getUnionFileFilter(fileFilterList); final Set<File> prediction = new HashSet<File>(); prediction.add(new File(this.testRoot, "a/b1")); prediction.add(new File(this.testRoot, "a/b3")); testFileFilter(new File(this.testRoot, "a"), unionFileFilter, prediction, "FileSelector.getUnionFileFilter(Iterable)"); } /** * Test for {@link FileSelector#selectFiles(File, Pattern, long, boolean, boolean)} with negative depth. */ @Test public void testSelectFilesWithNegativeDepth() { final List<File> matchedFiles; final Set<File> prediction = new HashSet<File>(); // Should match no files due to depth of -1. matchedFiles = FileSelector.selectFiles(this.testRoot, Pattern.compile(".*"), -1, true, true); testFilesAgainstPrediction(matchedFiles, prediction, "FileSelector.selectFiles(File,Pattern,boolean,boolean); negative depth"); } /** * Test for {@link FileSelector#selectFiles(File, Pattern, long, boolean, boolean)} with depth zero. */ @Test public void testSelectFilesWithDepthZero() { final List<File> matchedFiles; final Set<File> prediction = new HashSet<File>(); // Should match only root due to depth of 0. matchedFiles = FileSelector.selectFiles(this.testRoot, Pattern.compile(".*"), 0, true, true); prediction.add(this.testRoot); testFilesAgainstPrediction(matchedFiles, prediction, "FileSelector.selectFiles(File,Pattern,boolean,boolean); depth zero"); } /** * Test for {@link FileSelector#selectFiles(File, Pattern, long, boolean, boolean)} with depth zero and no * consideration of base file. */ @Test public void testSelectFilesWithDepthZeroNoBaseFile() { final List<File> matchedFiles; final Set<File> prediction = new HashSet<File>(); // Should match nothing due to considerBaseFile=false and depth = 0. matchedFiles = FileSelector.selectFiles(this.testRoot, Pattern.compile(".*"), 0, false, true); testFilesAgainstPrediction(matchedFiles, prediction, "FileSelector.selectFiles(File,Pattern,boolean,boolean); depth zero, no consideration of base file"); } /** * Test for {@link FileSelector#selectFiles(File, Pattern, long, boolean, boolean)} for all files at depth one * of which the name starts with the name of the root. */ @Test public void testSelectFilesWithDepthOneAndNameStartingWithRootName() { final List<File> matchedFiles; final Set<File> prediction; // Match all files and directories in the root directory that have the same name as the root. matchedFiles = FileSelector.selectFiles(this.testRoot, FileSelectorTest.getParentDirNameAsFileNamePattern(), 1, false, true); prediction = new HashSet<File>(); prediction.add(new File(this.testRoot, this.testRoot.getName() + "file")); prediction.add(new File(this.testRoot, this.testRoot.getName())); testFilesAgainstPrediction(matchedFiles, prediction, "FileSelector.selectFiles(File,Pattern,boolean,boolean);" + " all files at depth one of which the name starts with the name of the root"); } /** * Test for {@link FileSelector#selectFiles(File, Pattern, long, boolean, boolean)} for all files of which the * name starts with the name of their parent. */ @Test public void testSelectFilesWithNameStartingWithParentName() { final List<File> matchedFiles; final Set<File> prediction; // Match all files and directories in the entire tree minus the root that have a name that starts with // the name of their parent. matchedFiles = FileSelector.selectFiles(this.testRoot, FileSelectorTest.getParentDirNameAsFileNamePattern(), Integer.MAX_VALUE, false, true); prediction = new HashSet<File>(); prediction.add(new File(this.testRoot, "a" + File.separator + "a")); prediction.add(new File(this.testRoot, "a" + File.separator + "a" + File.separator + "a")); prediction.add(new File(this.testRoot, this.testRoot.getName())); prediction.add(new File(this.testRoot, this.testRoot.getName() + "file")); testFilesAgainstPrediction(matchedFiles, prediction, "FileSelector.selectFiles(File,Pattern,boolean,boolean); " + "all files of which the name starts with the name of the root"); } /** * Test for {@link FileSelector#selectFiles(File, FileFilter, List, long, boolean, boolean)}. */ @Test public void testSelectFilesFromFileFilter() { final FileFilter filter = FileSelector.getFilesFilter(); final List<File> matchedFiles = new ArrayList<File>(); final Set<File> prediction = new HashSet<File>(); final int bound = FileSelectorTest.firstFile + FileSelectorTest.maxFiles; for (int index = FileSelectorTest.firstFile; index < bound; index++) { prediction.add(new File(this.testRoot, FileSelectorTest.rootFilePrefix + index)); } prediction.add(new File(this.testRoot, this.testRoot.getName() + "file")); prediction.add(new File(this.testRoot, "a" + File.separator + "b3")); prediction.add(new File(this.testRoot, "a" + File.separator + "b4")); prediction.add(new File(this.testRoot, "a" + File.separator + "a" + File.separator + "a")); prediction.add(new File(this.testRoot, "a" + File.separator + "a" + File.separator + "b3")); prediction.add(new File(this.testRoot, "a" + File.separator + "a" + File.separator + "b4")); // Match all files. FileSelector.selectFiles(this.testRoot, filter, matchedFiles, Integer.MAX_VALUE, false, true); testFilesAgainstPrediction(matchedFiles, prediction, "FileSelector.selectFiles(File, FileFilter, List, long, boolean, boolean); " + "all files, but not directories"); } /** * Test the specified {@link FileFilter}. * * @param directory The directory where the test must take place. * @param filter The filter to test. * @param predictedResult The files and directories predicted to pass the filter. * @param filterName The name of the filter. Is used for reporting purposes. */ private void testFileFilter(final File directory, final FileFilter filter, final Set<File> predictedResult, final String filterName) { // Get the files that matched the filter. final File[] matchedFiles = directory.listFiles(filter); testFilesAgainstPrediction(Arrays.asList(matchedFiles), predictedResult, filterName); } /** * Test the specified set of {@link File} instances against the predicted set of instances. * * @param filesFound The files and directories that were found. * @param predictedResult The files and directories predicted to be found. * @param methodDescription The method that was used to find the files. Is used for reporting purposes. */ private void testFilesAgainstPrediction(final List<File> filesFound, final Set<File> predictedResult, final String methodDescription) { // Set of files that have not (yet) been matched, but have been predicted. final Set<File> unmatchedFiles = new HashSet<File>(predictedResult); final Set<File> matchedFiles = new HashSet<File>(); matchedFiles.addAll(filesFound); // There should be no duplicate files matched. While this is not explicitly guaranteed, it would certainly be // highly undesirable. Assert.assertEquals("List of files found by '" + methodDescription + "' contains duplicates.", filesFound.size(), matchedFiles.size()); // All matched files must be in the prediction. for (File acceptedFile : filesFound) { Assert.assertTrue(methodDescription + " accepted the unpredicted file: '" + acceptedFile.toString() + "'", unmatchedFiles.contains(acceptedFile)); unmatchedFiles.remove(acceptedFile); } for (File unmatchedFile : unmatchedFiles) { Assert.assertTrue(methodDescription + " did not match predicted file: '" + unmatchedFile.toString() + "'", false); } } }
package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import org.cactoos.Input; import org.cactoos.text.TextOf; import org.hamcrest.MatcherAssert; import org.hamcrest.core.IsEqual; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Test case for {@link ReaderOf}. * @author Yegor Bugayenko (yegor256@gmail.com) * @author Roman Proshin (roman@proshin.org) * @version $Id$ * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") public final class ReaderOfTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test(expected = NullPointerException.class) public void readsNull() throws IOException { MatcherAssert.assertThat( new TextOf(new ReaderOf((Input) null)).asString(), new IsEqual<>("") ); } @Test public void readsEmpty() throws IOException { MatcherAssert.assertThat( new TextOf(new ReaderOf("")).asString(), new IsEqual<>("") ); } @Test public void readsCharVarArg() throws IOException { MatcherAssert.assertThat( new TextOf(new ReaderOf('a', 'b', 'c')).asString(), new IsEqual<>("abc") ); } @Test public void readsCharArrayWithCharset() throws IOException { final String message = "char array on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( message.toCharArray(), StandardCharsets.UTF_8 ) ).asString(), new IsEqual<>(message) ); } @Test public void readsCharArrayWithCharsetByName() throws IOException { final String message = "char array with charset on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( message.toCharArray(), StandardCharsets.UTF_8.name() ) ).asString(), new IsEqual<>(message) ); } @Test public void readsByteArray() throws IOException { final String message = "byte array on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( message.getBytes(StandardCharsets.UTF_8) ) ).asString(), new IsEqual<>(message) ); } @Test public void readsByteArrayWithCharset() throws IOException { final String message = "byte array with charset on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( message.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8 ) ).asString(), new IsEqual<>(message) ); } @Test public void readsByteArrayWithCharsetByName() throws IOException { final String message = "bte array with charset by name on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( message.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8.name() ) ).asString(), new IsEqual<>(message) ); } @Test public void readsPath() throws IOException { final String message = "path on äÄ üÜ öÖ ß жш"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); MatcherAssert.assertThat( new TextOf(new ReaderOf(input)).asString(), new IsEqual<>(message) ); } @Test public void readsFile() throws IOException { final String message = "file on äÄ üÜ öÖ ß жш"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); MatcherAssert.assertThat( new TextOf(new ReaderOf(input)).asString(), new IsEqual<>(message) ); } @Test public void readsUrl() throws IOException { final String message = "URL on äÄ üÜ öÖ ß жш"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); MatcherAssert.assertThat( new TextOf( new ReaderOf( input .toURI() .toURL() ) ).asString(), new IsEqual<>(message) ); } @Test public void readsUri() throws IOException { final String message = "URI on äÄ üÜ öÖ ß жш"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); MatcherAssert.assertThat( new TextOf(new ReaderOf(input.toURI())).asString(), new IsEqual<>(message) ); } @Test public void readsBytes() throws IOException { final String input = "Bytes on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf(new ReaderOf(new BytesOf(input))).asString(), new IsEqual<>(input) ); } @Test public void readsText() throws IOException { final String input = "Text on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf(new ReaderOf(new TextOf(input))).asString(), new IsEqual<>(input) ); } @Test public void readsTextWithCharset() throws IOException { final String input = "Text with charset on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( new TextOf(input), StandardCharsets.UTF_8 ) ).asString(), new IsEqual<>(input) ); } @Test public void readsTextWithCharsetByName() throws IOException { final String input = "Text with charset by name on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( new TextOf(input), StandardCharsets.UTF_8.name() ) ).asString(), new IsEqual<>(input) ); } @Test public void readsCharSequence() throws IOException { final String input = "char sequence on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf(new ReaderOf(input)).asString(), new IsEqual<>(input) ); } @Test public void readsCharSequenceWithCharset() throws IOException { final String input = "char sequence with charset on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( input, StandardCharsets.UTF_8 ) ).asString(), new IsEqual<>(input) ); } @Test public void readsCharSequenceWithCharsetByName() throws IOException { final String input = "char sequence with charset by name on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( input, StandardCharsets.UTF_8.name() ) ).asString(), new IsEqual<>(input) ); } @Test public void readsInput() throws IOException { final String input = "Input on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf(new ReaderOf(new InputOf(input))).asString(), new IsEqual<>(input) ); } @Test public void readsInputWithCharset() throws IOException { final String input = "Input with charset on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( new InputOf(input), StandardCharsets.UTF_8 ) ).asString(), new IsEqual<>(input) ); } @Test public void readsInputWithCharsetByName() throws IOException { final String input = "Input with charset by name on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( new InputOf(input), StandardCharsets.UTF_8.name() ) ).asString(), new IsEqual<>(input) ); } @Test public void readsInputWithCharsetDecoder() throws IOException { final String input = "Input with charset decoder on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( new InputOf(input), StandardCharsets.UTF_8.newDecoder() ) ).asString(), new IsEqual<>(input) ); } @Test public void readsInputStream() throws IOException { final String input = "InputStream on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf(new ReaderOf(new InputStreamOf(input))).asString(), new IsEqual<>(input) ); } @Test public void readsInputStreamWithCharset() throws IOException { final String input = "InputStream with charset on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( new InputStreamOf(input), StandardCharsets.UTF_8 ) ).asString(), new IsEqual<>(input) ); } @Test public void readsInputStreamWithCharsetByName() throws IOException { final String input = "InputStream with charset by name on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( new InputStreamOf(input), StandardCharsets.UTF_8.name() ) ).asString(), new IsEqual<>(input) ); } @Test public void readsInputStreamWithCharsetDecoder() throws IOException { final String input = "InputStream with charset decoder on äÄ üÜ öÖ ß жш"; MatcherAssert.assertThat( new TextOf( new ReaderOf( new InputStreamOf(input), StandardCharsets.UTF_8.newDecoder() ) ).asString(), new IsEqual<>(input) ); } }
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.nodes.Comment; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** Tests for the Parser @author Jonathan Hedley, jonathan@hedley.net */ public class ParserTest { @Test public void parsesSimpleDocument() { String html = "<html><head><title>First!</title></head><body><p>First post! <img src=\"foo.png\" /></p></body></html>"; Document doc = Jsoup.parse(html); // need a better way to verify these: Element p = doc.body().child(0); assertEquals("p", p.tagName()); Element img = p.child(0); assertEquals("foo.png", img.attr("src")); assertEquals("img", img.tagName()); } @Test public void parsesRoughAttributes() { String html = "<html><head><title>First!</title></head><body><p class=\"foo > bar\">First post! <img src=\"foo.png\" /></p></body></html>"; Document doc = Jsoup.parse(html); // need a better way to verify these: Element p = doc.body().child(0); assertEquals("p", p.tagName()); assertEquals("foo > bar", p.attr("class")); } @Test public void parsesQuiteRoughAttributes() { String html = "<p =a>One<a <p>Something</p>Else"; // this gets a <p> with attr '=a' and an <a tag with an attribue named '<p'; and then auto-recreated Document doc = Jsoup.parse(html); assertEquals("<p =a=\"\">One<a <p=\"\">Something</a></p>\n" + "<a <p=\"\">Else</a>", doc.body().html()); doc = Jsoup.parse("<p .....>"); assertEquals("<p .....=\"\"></p>", doc.body().html()); } @Test public void parsesComments() { String html = "<html><head></head><body><img src=foo><!-- <table><tr><td></table> --><p>Hello</p></body></html>"; Document doc = Jsoup.parse(html); Element body = doc.body(); Comment comment = (Comment) body.childNode(1); // comment should not be sub of img, as it's an empty tag assertEquals(" <table><tr><td></table> ", comment.getData()); Element p = body.child(1); TextNode text = (TextNode) p.childNode(0); assertEquals("Hello", text.getWholeText()); } @Test public void parsesUnterminatedComments() { String html = "<p>Hello<!-- <tr><td>"; Document doc = Jsoup.parse(html); Element p = doc.getElementsByTag("p").get(0); assertEquals("Hello", p.text()); TextNode text = (TextNode) p.childNode(0); assertEquals("Hello", text.getWholeText()); Comment comment = (Comment) p.childNode(1); assertEquals(" <tr><td>", comment.getData()); } @Test public void dropsUnterminatedTag() { // jsoup used to parse this to <p>, but whatwg, webkit will drop. String h1 = "<p"; Document doc = Jsoup.parse(h1); assertEquals(0, doc.getElementsByTag("p").size()); assertEquals("", doc.text()); String h2 = "<div id=1<p id='2'"; doc = Jsoup.parse(h2); assertEquals("", doc.text()); } @Test public void dropsUnterminatedAttribute() { // jsoup used to parse this to <p id="foo">, but whatwg, webkit will drop. String h1 = "<p id=\"foo"; Document doc = Jsoup.parse(h1); assertEquals("", doc.text()); } @Test public void parsesUnterminatedTextarea() { // don't parse right to end, but break on <p> Document doc = Jsoup.parse("<body><p><textarea>one<p>two"); Element t = doc.select("textarea").first(); assertEquals("one", t.text()); assertEquals("two", doc.select("p").get(1).text()); } @Test public void parsesUnterminatedOption() { // bit weird this -- browsers and spec get stuck in select until there's a </select> Document doc = Jsoup.parse("<body><p><select><option>One<option>Two</p><p>Three</p>"); Elements options = doc.select("option"); assertEquals(2, options.size()); assertEquals("One", options.first().text()); assertEquals("TwoThree", options.last().text()); } @Test public void testSpaceAfterTag() { Document doc = Jsoup.parse("<div > <a name=\"top\"></a ><p id=1 >Hello</p></div>"); assertEquals("<div> <a name=\"top\"></a><p id=\"1\">Hello</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void createsDocumentStructure() { String html = "<meta name=keywords /><link rel=stylesheet /><title>jsoup</title><p>Hello world</p>"; Document doc = Jsoup.parse(html); Element head = doc.head(); Element body = doc.body(); assertEquals(1, doc.children().size()); // root node: contains html node assertEquals(2, doc.child(0).children().size()); // html node: head and body assertEquals(3, head.children().size()); assertEquals(1, body.children().size()); assertEquals("keywords", head.getElementsByTag("meta").get(0).attr("name")); assertEquals(0, body.getElementsByTag("meta").size()); assertEquals("jsoup", doc.title()); assertEquals("Hello world", body.text()); assertEquals("Hello world", body.children().get(0).text()); } @Test public void createsStructureFromBodySnippet() { // the bar baz stuff naturally goes into the body, but the 'foo' goes into root, and the normalisation routine // needs to move into the start of the body String html = "foo <b>bar</b> baz"; Document doc = Jsoup.parse(html); assertEquals("foo bar baz", doc.text()); } @Test public void handlesEscapedData() { String html = "<div title='Surf &amp; Turf'>Reef &amp; Beef</div>"; Document doc = Jsoup.parse(html); Element div = doc.getElementsByTag("div").get(0); assertEquals("Surf & Turf", div.attr("title")); assertEquals("Reef & Beef", div.text()); } @Test public void handlesDataOnlyTags() { String t = "<style>font-family: bold</style>"; List<Element> tels = Jsoup.parse(t).getElementsByTag("style"); assertEquals("font-family: bold", tels.get(0).data()); assertEquals("", tels.get(0).text()); String s = "<p>Hello</p><script>Nope</script><p>There</p>"; Document doc = Jsoup.parse(s); assertEquals("Hello There", doc.text()); assertEquals("Nope", doc.data()); } @Test public void handlesTextAfterData() { String h = "<html><body>pre <script>inner</script> aft</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head></head><body>pre <script>inner</script> aft</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesTextArea() { Document doc = Jsoup.parse("<textarea>Hello</textarea>"); Elements els = doc.select("textarea"); assertEquals("Hello", els.text()); assertEquals("Hello", els.val()); } @Test public void doesNotCreateImplicitLists() { // old jsoup used to wrap this in <ul>, but that's not to spec String h = "<li>Point one<li>Point two"; Document doc = Jsoup.parse(h); Elements ol = doc.select("ul"); // should NOT have created a default ul. assertEquals(0, ol.size()); Elements lis = doc.select("li"); assertEquals(2, lis.size()); assertEquals("body", lis.first().parent().tagName()); // no fiddling with non-implicit lists String h2 = "<ol><li><p>Point the first<li><p>Point the second"; Document doc2 = Jsoup.parse(h2); assertEquals(0, doc2.select("ul").size()); assertEquals(1, doc2.select("ol").size()); assertEquals(2, doc2.select("ol li").size()); assertEquals(2, doc2.select("ol li p").size()); assertEquals(1, doc2.select("ol li").get(0).children().size()); // one p in first li } @Test public void discardsNakedTds() { // jsoup used to make this into an implicit table; but browsers make it into a text run String h = "<td>Hello<td><p>There<p>now"; Document doc = Jsoup.parse(h); assertEquals("Hello<p>There</p><p>now</p>", TextUtil.stripNewlines(doc.body().html())); // <tbody> is introduced if no implicitly creating table, but allows tr to be directly under table } @Test public void handlesNestedImplicitTable() { Document doc = Jsoup.parse("<table><td>1</td></tr> <td>2</td></tr> <td> <table><td>3</td> <td>4</td></table> <tr><td>5</table>"); assertEquals("<table><tbody><tr><td>1</td></tr> <tr><td>2</td></tr> <tr><td> <table><tbody><tr><td>3</td> <td>4</td></tr></tbody></table> </td></tr><tr><td>5</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesWhatWgExpensesTableExample() { // http://www.whatwg.org/specs/web-apps/current-work/multipage/tabular-data.html#examples-0 Document doc = Jsoup.parse("<table> <colgroup> <col> <colgroup> <col> <col> <col> <thead> <tr> <th> <th>2008 <th>2007 <th>2006 <tbody> <tr> <th scope=rowgroup> Research and development <td> $ 1,109 <td> $ 782 <td> $ 712 <tr> <th scope=row> Percentage of net sales <td> 3.4% <td> 3.3% <td> 3.7% <tbody> <tr> <th scope=rowgroup> Selling, general, and administrative <td> $ 3,761 <td> $ 2,963 <td> $ 2,433 <tr> <th scope=row> Percentage of net sales <td> 11.6% <td> 12.3% <td> 12.6% </table>"); assertEquals("<table> <colgroup> <col /> </colgroup><colgroup> <col /> <col /> <col /> </colgroup><thead> <tr> <th> </th><th>2008 </th><th>2007 </th><th>2006 </th></tr></thead><tbody> <tr> <th scope=\"rowgroup\"> Research and development </th><td> $ 1,109 </td><td> $ 782 </td><td> $ 712 </td></tr><tr> <th scope=\"row\"> Percentage of net sales </th><td> 3.4% </td><td> 3.3% </td><td> 3.7% </td></tr></tbody><tbody> <tr> <th scope=\"rowgroup\"> Selling, general, and administrative </th><td> $ 3,761 </td><td> $ 2,963 </td><td> $ 2,433 </td></tr><tr> <th scope=\"row\"> Percentage of net sales </th><td> 11.6% </td><td> 12.3% </td><td> 12.6% </td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesTbodyTable() { Document doc = Jsoup.parse("<html><head></head><body><table><tbody><tr><td>aaa</td><td>bbb</td></tr></tbody></table></body></html>"); assertEquals("<table><tbody><tr><td>aaa</td><td>bbb</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesImplicitCaptionClose() { Document doc = Jsoup.parse("<table><caption>A caption<td>One<td>Two"); assertEquals("<table><caption>A caption</caption><tbody><tr><td>One</td><td>Two</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void noTableDirectInTable() { Document doc = Jsoup.parse("<table> <td>One <td><table><td>Two</table> <table><td>Three"); assertEquals("<table> <tbody><tr><td>One </td><td><table><tbody><tr><td>Two</td></tr></tbody></table> <table><tbody><tr><td>Three</td></tr></tbody></table></td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void ignoresDupeEndTrTag() { Document doc = Jsoup.parse("<table><tr><td>One</td><td><table><tr><td>Two</td></tr></tr></table></td><td>Three</td></tr></table>"); // two </tr></tr>, must ignore or will close table assertEquals("<table><tbody><tr><td>One</td><td><table><tbody><tr><td>Two</td></tr></tbody></table></td><td>Three</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesBaseTags() { // todo -- don't handle base tags like this -- spec and browsers don't (any more -- v. old ones do). // instead, just maintain one baseUri in the doc String h = "<a href=1> Document doc = Jsoup.parse(h, "http://foo/"); assertEquals("http://bar", doc.baseUri()); // gets updated as base changes, so doc.createElement has latest. Elements anchors = doc.getElementsByTag("a"); assertEquals(3, anchors.size()); assertEquals("http://foo/", anchors.get(0).baseUri()); assertEquals("http://foo/2/", anchors.get(1).baseUri()); assertEquals("http://bar", anchors.get(2).baseUri()); assertEquals("http://foo/1", anchors.get(0).absUrl("href")); assertEquals("http://foo/2/3", anchors.get(1).absUrl("href")); assertEquals("http://bar/4", anchors.get(2).absUrl("href")); } @Test public void handlesCdata() { // todo: as this is html namespace, should actually treat as bogus comment, not cdata. keep as cdata for now String h = "<div id=1><![CDATA[<html>\n<foo><&amp;]]></div>"; // the &amp; in there should remain literal Document doc = Jsoup.parse(h); Element div = doc.getElementById("1"); assertEquals("<html> <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodes().size()); // no elements, one text node } @Test public void handlesInvalidStartTags() { String h = "<div>Hello < There <&amp;></div>"; // parse to <div {#text=Hello < There <&>}> Document doc = Jsoup.parse(h); assertEquals("Hello < There <&>", doc.select("div").first().text()); } @Test public void handlesUnknownTags() { String h = "<div><foo title=bar>Hello<foo title=qux>there</foo></div>"; Document doc = Jsoup.parse(h); Elements foos = doc.select("foo"); assertEquals(2, foos.size()); assertEquals("bar", foos.first().attr("title")); assertEquals("qux", foos.last().attr("title")); assertEquals("there", foos.last().text()); } @Test public void handlesUnknownInlineTags() { String h = "<p><cust>Test</cust></p><p><cust><cust>Test</cust></cust></p>"; Document doc = Jsoup.parseBodyFragment(h); String out = doc.body().html(); assertEquals(h, TextUtil.stripNewlines(out)); } @Test public void parsesBodyFragment() { String h = "<!-- comment --><p><a href='foo'>One</a></p>"; Document doc = Jsoup.parseBodyFragment(h, "http://example.com"); assertEquals("<body><!-- comment --><p><a href=\"foo\">One</a></p></body>", TextUtil.stripNewlines(doc.body().outerHtml())); assertEquals("http://example.com/foo", doc.select("a").first().absUrl("href")); } @Test public void handlesUnknownNamespaceTags() { // note that the first foo:bar should not really be allowed to be self closing, if parsed in html mode. String h = "<foo:bar id='1' /><abc:def id=2>Foo<p>Hello</p></abc:def><foo:bar>There</foo:bar>"; Document doc = Jsoup.parse(h); assertEquals("<foo:bar id=\"1\" /><abc:def id=\"2\">Foo<p>Hello</p></abc:def><foo:bar>There</foo:bar>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesKnownEmptyBlocks() { // if known tag, must be defined as self closing to allow as self closing. unkown tags can be self closing. String h = "<div id='1' /><div id=2><img /><img></div> <hr /> hr text <hr> hr text two"; Document doc = Jsoup.parse(h); Element div1 = doc.getElementById("1"); assertTrue(!div1.children().isEmpty()); // <div /> is treated as <div>... assertTrue(doc.select("hr").first().children().isEmpty()); assertTrue(doc.select("hr").last().children().isEmpty()); assertTrue(doc.select("img").first().children().isEmpty()); assertTrue(doc.select("img").last().children().isEmpty()); } @Test public void handlesSolidusAtAttributeEnd() { // this test makes sure [<a href=/>link</a>] is parsed as [<a href="/">link</a>], not [<a href="" /><a>link</a>] String h = "<a href=/>link</a>"; Document doc = Jsoup.parse(h); assertEquals("<a href=\"/\">link</a>", doc.body().html()); } @Test public void handlesMultiClosingBody() { String h = "<body><p>Hello</body><p>there</p></body></body></html><p>now"; Document doc = Jsoup.parse(h); assertEquals(3, doc.select("p").size()); assertEquals(3, doc.body().children().size()); } @Test public void handlesUnclosedDefinitionLists() { // jsoup used to create a <dl>, but that's not to spec String h = "<dt>Foo<dd>Bar<dt>Qux<dd>Zug"; Document doc = Jsoup.parse(h); assertEquals(0, doc.select("dl").size()); // no auto dl assertEquals(4, doc.select("dt, dd").size()); Elements dts = doc.select("dt"); assertEquals(2, dts.size()); assertEquals("Zug", dts.get(1).nextElementSibling().text()); } @Test public void handlesBlocksInDefinitions() { // per the spec, dt and dd are inline, but in practise are block String h = "<dl><dt><div id=1>Term</div></dt><dd><div id=2>Def</div></dd></dl>"; Document doc = Jsoup.parse(h); assertEquals("dt", doc.select("#1").first().parent().tagName()); assertEquals("dd", doc.select("#2").first().parent().tagName()); assertEquals("<dl><dt><div id=\"1\">Term</div></dt><dd><div id=\"2\">Def</div></dd></dl>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesFrames() { String h = "<html><head><script></script><noscript></noscript></head><frameset><frame src=foo></frame><frame src=foo></frameset></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><script></script><noscript></noscript></head><frameset><frame src=\"foo\" /><frame src=\"foo\" /></frameset></html>", TextUtil.stripNewlines(doc.html())); // no body auto vivification } @Test public void handlesJavadocFont() { String h = "<TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A>&nbsp;</TD>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("Deprecated", a.text()); assertEquals("font", a.child(0).tagName()); assertEquals("b", a.child(0).child(0).tagName()); } @Test public void handlesBaseWithoutHref() { String h = "<head><base target='_blank'></head><body><a href=/foo>Test</a></body>"; Document doc = Jsoup.parse(h, "http://example.com/"); Element a = doc.select("a").first(); assertEquals("/foo", a.attr("href")); assertEquals("http://example.com/foo", a.attr("abs:href")); } @Test public void normalisesDocument() { String h = "<!doctype html>One<html>Two<head>Three<link></head>Four<body>Five </body>Six </html>Seven "; Document doc = Jsoup.parse(h); assertEquals("<!DOCTYPE html><html><head></head><body>OneTwoThree<link />FourFive Six Seven </body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesEmptyDocument() { Document doc = Jsoup.parse(""); assertEquals("<html><head></head><body></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesHeadlessBody() { Document doc = Jsoup.parse("<html><body><span class=\"foo\">bar</span>"); assertEquals("<html><head></head><body><span class=\"foo\">bar</span></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisedBodyAfterContent() { Document doc = Jsoup.parse("<font face=Arial><body class=name><div>One</div></body></font>"); assertEquals("<html><head></head><body class=\"name\"><font face=\"Arial\"><div>One</div></font></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void findsCharsetInMalformedMeta() { String h = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"; // example cited for reason of html5's <meta charset> element Document doc = Jsoup.parse(h); assertEquals("gb2312", doc.select("meta").attr("charset")); } @Test public void testHgroup() { // jsoup used to not allow hroup in h{n}, but that's not in spec, and browsers are OK Document doc = Jsoup.parse("<h1>Hello <h2>There <hgroup><h1>Another<h2>headline</hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup>"); assertEquals("<h1>Hello </h1><h2>There <hgroup><h1>Another</h1><h2>headline</h2></hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup></h2>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testRelaxedTags() { Document doc = Jsoup.parse("<abc_def id=1>Hello</abc_def> <abc-def>There</abc-def>"); assertEquals("<abc_def id=\"1\">Hello</abc_def> <abc-def>There</abc-def>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHeaderContents() { // h* tags (h1 .. h9) in browsers can handle any internal content other than other h*. which is not per any // spec, which defines them as containing phrasing content only. so, reality over theory. Document doc = Jsoup.parse("<h1>Hello <div>There</div> now</h1> <h2>More <h3>Content</h3></h2>"); assertEquals("<h1>Hello <div>There</div> now</h1> <h2>More </h2><h3>Content</h3>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testSpanContents() { // like h1 tags, the spec says SPAN is phrasing only, but browsers and publisher treat span as a block tag Document doc = Jsoup.parse("<span>Hello <div>there</div> <span>now</span></span>"); assertEquals("<span>Hello <div>there</div> <span>now</span></span>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testNoImagesInNoScriptInHead() { // jsoup used to allow, but against spec if parsing with noscript Document doc = Jsoup.parse("<html><head><noscript><img src='foo'></noscript></head><body><p>Hello</p></body></html>"); assertEquals("<html><head><noscript></noscript></head><body><img src=\"foo\" /><p>Hello</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testAFlowContents() { // html5 has <a> as either phrasing or block Document doc = Jsoup.parse("<a>Hello <div>there</div> <span>now</span></a>"); assertEquals("<a>Hello <div>there</div> <span>now</span></a>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testFontFlowContents() { // html5 has no definition of <font>; often used as flow Document doc = Jsoup.parse("<font>Hello <div>there</div> <span>now</span></font>"); assertEquals("<font>Hello <div>there</div> <span>now</span></font>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesMisnestedTagsBI() { // whatwg: <b><i></b></i> String h = "<p>1<b>2<i>3</b>4</i>5</p>"; Document doc = Jsoup.parse(h); assertEquals("<p>1<b>2<i>3</i></b><i>4</i>5</p>", doc.body().html()); // adoption agency on </b>, reconstruction of formatters on 4. } @Test public void handlesMisnestedTagsBP() { // whatwg: <b><p></b></p> String h = "<b>1<p>2</b>3</p>"; Document doc = Jsoup.parse(h); assertEquals("<b>1</b>\n<p><b>2</b>3</p>", doc.body().html()); } @Test public void handlesUnexpectedMarkupInTables() { // whatwg - tests markers in active formatting (if they didn't work, would get in in table) // also tests foster parenting String h = "<table><b><tr><td>aaa</td></tr>bbb</table>ccc"; Document doc = Jsoup.parse(h); assertEquals("<b></b><b>bbb</b><table><tbody><tr><td>aaa</td></tr></tbody></table><b>ccc</b>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesUnclosedFormattingElements() { // whatwg: formatting elements get collected and applied, but excess elements are thrown away String h = "<!DOCTYPE html>\n" + "<p><b class=x><b class=x><b><b class=x><b class=x><b>X\n" + "<p>X\n" + "<p><b><b class=x><b>X\n" + "<p></b></b></b></b></b></b>X"; Document doc = Jsoup.parse(h); doc.outputSettings().indentAmount(0); String want = "<!DOCTYPE html>\n" + "<html>\n" + "<head></head>\n" + "<body>\n" + "<p><b class=\"x\"><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b>X </b></b></b></b></b></b></p>\n" + "<p><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b>X </b></b></b></b></b></p>\n" + "<p><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b><b><b class=\"x\"><b>X </b></b></b></b></b></b></b></b></p>\n" + "<p>X</p>\n" + "</body>\n" + "</html>"; assertEquals(want, doc.html()); } @Test public void reconstructFormattingElements() { // tests attributes and multi b String h = "<p><b class=one>One <i>Two <b>Three</p><p>Hello</p>"; Document doc = Jsoup.parse(h); assertEquals("<p><b class=\"one\">One <i>Two <b>Three</b></i></b></p>\n<p><b class=\"one\"><i><b>Hello</b></i></b></p>", doc.body().html()); } @Test public void reconstructFormattingElementsInTable() { // tests that tables get formatting markers -- the <b> applies outside the table and does not leak in, // and the <i> inside the table and does not leak out. String h = "<p><b>One</p> <table><tr><td><p><i>Three<p>Four</i></td></tr></table> <p>Five</p>"; Document doc = Jsoup.parse(h); String want = "<p><b>One</b></p>\n" + "<b> \n" + " <table>\n" + " <tbody>\n" + " <tr>\n" + " <td><p><i>Three</i></p><p><i>Four</i></p></td>\n" + " </tr>\n" + " </tbody>\n" + " </table> <p>Five</p></b>"; assertEquals(want, doc.body().html()); } @Test public void commentBeforeHtml() { String h = "<!-- comment --><!-- comment 2 --><p>One</p>"; Document doc = Jsoup.parse(h); assertEquals("<!-- comment --><!-- comment 2 --><html><head></head><body><p>One</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void emptyTdTag() { String h = "<table><tr><td>One</td><td id='2' /></tr></table>"; Document doc = Jsoup.parse(h); assertEquals("<td>One</td>\n<td id=\"2\"></td>", doc.select("tr").first().html()); } @Test public void handlesSolidusInA() { // test for bug String h = "<a class=lp href=/lib/14160711/>link text</a>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("link text", a.text()); assertEquals("/lib/14160711/", a.attr("href")); } @Test public void handlesSpanInTbody() { // test for bug 64 String h = "<table><tbody><span class='1'><tr><td>One</td></tr><tr><td>Two</td></tr></span></tbody></table>"; Document doc = Jsoup.parse(h); assertEquals(doc.select("span").first().children().size(), 0); // the span gets closed assertEquals(doc.select("table").size(), 1); // only one table } @Test public void handlesUnclosedTitleAtEof() { assertEquals("Data", Jsoup.parse("<title>Data").title()); assertEquals("Data<", Jsoup.parse("<title>Data<").title()); assertEquals("Data</", Jsoup.parse("<title>Data</").title()); assertEquals("Data</t", Jsoup.parse("<title>Data</t").title()); assertEquals("Data</ti", Jsoup.parse("<title>Data</ti").title()); assertEquals("Data", Jsoup.parse("<title>Data</title>").title()); assertEquals("Data", Jsoup.parse("<title>Data</title >").title()); } @Test public void handlesUnclosedTitle() { Document one = Jsoup.parse("<title>One <b>Two <b>Three</TITLE><p>Test</p>"); // has title, so <b> is plain text assertEquals("One <b>Two <b>Three", one.title()); assertEquals("Test", one.select("p").first().text()); Document two = Jsoup.parse("<title>One<b>Two <p>Test</p>"); // no title, so <b> causes </title> breakout assertEquals("One", two.title()); assertEquals("<b>Two <p>Test</p></b>", two.body().html()); } @Test public void noImplicitFormForTextAreas() { // old jsoup parser would create implicit forms for form children like <textarea>, but no more Document doc = Jsoup.parse("<textarea>One</textarea>"); assertEquals("<textarea>One</textarea>", doc.body().html()); } }
package org.mariadb.jdbc; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import java.sql.*; import java.util.Arrays; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class CancelTest extends BaseTest { @Before public void cancelSupported() throws SQLException { requireMinimumVersion(5, 0); Assume.assumeTrue(System.getenv("MAXSCALE_VERSION") == null); } @Test public void cancelTest() { try (Connection tmpConnection = openNewConnection(connUri, new Properties())) { Statement stmt = tmpConnection.createStatement(); ExecutorService exec = Executors.newFixedThreadPool(1); //check blacklist shared exec.execute(new CancelThread(stmt)); stmt.execute("select * from information_schema.columns as c1, information_schema.tables, information_schema.tables as t2"); //wait for thread endings exec.shutdown(); Assert.fail(); } catch (SQLException e) { //normal exception } } @Test(timeout = 20000, expected = SQLTimeoutException.class) public void timeoutSleep() throws Exception { try (Connection tmpConnection = openNewConnection(connUri, new Properties())) { Statement stmt = tmpConnection.createStatement(); stmt.setQueryTimeout(5); //query take more than 20 seconds (local DB) stmt.execute("select * from information_schema.columns as c1, information_schema.tables, information_schema.tables as t2"); } } @Test(timeout = 20000, expected = SQLTimeoutException.class) public void timeoutPrepareSleep() throws Exception { try (Connection tmpConnection = openNewConnection(connUri, new Properties())) { try (PreparedStatement stmt = tmpConnection.prepareStatement( "select * from information_schema.columns as c1, information_schema.tables, information_schema.tables as t2")) { stmt.setQueryTimeout(5); //query take more than 20 seconds (local DB) stmt.execute(); } } } @Test(timeout = 5000, expected = BatchUpdateException.class) public void timeoutBatch() throws Exception { Assume.assumeFalse(sharedIsAurora()); Assume.assumeTrue(!sharedOptions().allowMultiQueries && !sharedIsRewrite()); createTable("timeoutBatch", "aa text"); Statement stmt = sharedConnection.createStatement(); char[] arr = new char[1000]; Arrays.fill(arr, 'a'); String str = String.valueOf(arr); for (int i = 0; i < 20000; i++) { stmt.addBatch("INSERT INTO timeoutBatch VALUES ('" + str + "')"); } stmt.setQueryTimeout(1); stmt.executeBatch(); } @Test(timeout = 5000, expected = BatchUpdateException.class) public void timeoutPrepareBatch() throws Exception { Assume.assumeFalse(sharedIsAurora()); Assume.assumeTrue(!sharedOptions().allowMultiQueries && !sharedIsRewrite()); Assume.assumeTrue(!(sharedOptions().useBulkStmts && isMariadbServer() && minVersion(10,2))); createTable("timeoutBatch", "aa text"); try (Connection tmpConnection = openNewConnection(connUri, new Properties())) { char[] arr = new char[1000]; Arrays.fill(arr, 'a'); String str = String.valueOf(arr); try (PreparedStatement stmt = tmpConnection.prepareStatement("INSERT INTO timeoutBatch VALUES (?)")) { stmt.setQueryTimeout(1); for (int i = 0; i < 20000; i++) { stmt.setString(1, str); stmt.addBatch(); } stmt.executeBatch(); } } } @Test public void noTimeoutSleep() throws Exception { Statement stmt = sharedConnection.createStatement(); stmt.setQueryTimeout(1); stmt.execute("select sleep(0.5)"); } @Test public void cancelIdleStatement() throws Exception { Statement stmt = sharedConnection.createStatement(); stmt.cancel(); ResultSet rs = stmt.executeQuery("select 1"); assertTrue(rs.next()); assertEquals(rs.getInt(1), 1); } private static class CancelThread implements Runnable { private final Statement stmt; public CancelThread(Statement stmt) { this.stmt = stmt; } @Override public void run() { try { Thread.sleep(100); stmt.cancel(); } catch (SQLException | InterruptedException e) { e.printStackTrace(); } } } }
package structure.impl; import monitoring.impl.configs.NonDetConfig; import structure.intf.Binding; import structure.intf.Transition; /** * This class represents a Quantified Event Automaton (QEA) with the following * characteristics: * <ul> * <li>There is one quantified variable * <li>It can contain any number of free variables * <li>The transitions in the function delta consist of a start state, an event * and an end state. Optionally, it can be associated to a guard and/or an * assignment * <li>The QEA is non-deterministic * </ul> * * @author Helena Cuenca * @author Giles Reger */ public class NonSimpleNonDetQEA extends NonSimpleQEA { /** * Transition function delta for this QEA. For a given Transition in the * array, the first index corresponds to the start state and the second * index corresponds to the event name. For a given start state and event * name, there may be an array of transitions (non-deterministic) */ private Transition[][][] delta; /** * Creates a NonSimpleNonDetQEA for the specified number of states, number * of events, initial state and quantification type * * @param numStates * Number of states * @param numEvents * Number of events * @param initialState * Initial state * @param quantification * Quantification type */ public NonSimpleNonDetQEA(int numStates, int numEvents, int initialState, Quantification quantification, int freeVariablesCount) { super(numStates, initialState, quantification, freeVariablesCount); delta = new Transition[numStates + 1][numEvents + 1][]; } /** * Adds a transition to the transition function delta of this QEA * * @param startState * Start state for the transition * @param event * Name of the event * @param transitions * Object containing the rest of the information of the * transition: Parameters for the event, guard, assignment and * end state */ public void addTransition(int startState, int event, Transition transition) { delta[startState][event] = new Transition[] { transition }; } /** * Adds a set of transitions to the transition function delta of this QEA * * @param startState * Start state for the transition * @param event * Name of the event * @param transitions * Array of objects containing the rest of the information of the * transitions: Parameters for the event, guard, assignment and * end state */ public void addTransitions(int startState, int event, Transition[] transitions) { delta[startState][event] = transitions; } /** * Computes the next configuration for a given start configuration, event * and arguments, according to the transition function delta of this QEA * * @param config * Start configuration containing the set of start states and the * set of bindings * @param event * Name of the event * @param args * Arguments for the event * @return End configuration containing the set of end state and the set of * bindings after the transition */ public NonDetConfig getNextConfig(NonDetConfig config, int event, Object[] args) { if (config.getStates().length == 1) { // Only one start state TransitionImpl[] transitions = (TransitionImpl[]) delta[config .getStates()[0]][event]; // If the event is not defined for the unique start state, return // the failing state with an empty binding if (transitions == null) { config.setState(0, 0); config.getBindings()[0].setEmpty(); return config; } // Check number of arguments vs. number of parameters of the event // for the first transition only checkArgParamLength(args.length, transitions[0].getVariableNames().length); if (transitions.length == 1) { // One start state - one transition // Update binding for free variables Binding binding = config.getBindings()[0]; Object[] prevBinding = updateBinding(binding, args, transitions[0]); // If there is a guard and is not satisfied, rollback the // binding and return the failing state if (transitions[0].getGuard() != null && !transitions[0].getGuard().check(binding)) { config.setState(0, 0); // Failing state rollBackBinding(binding, transitions[0], prevBinding); return config; } // If there is an assignment, execute it if (transitions[0].getAssignment() != null) { config.setBinding(0, transitions[0].getAssignment().apply(binding)); } // Set the end state config.setState(0, transitions[0].getEndState()); } else { // One start state - Multiple transitions // Create as many states and bindings as there are transitions int[] endStates = new int[transitions.length]; BindingImpl[] bindings = new BindingImpl[transitions.length]; // Initialise end states count int endStatesCount = 0; // Iterate over the transitions for (int i = 0; i < transitions.length; i++) { // Copy the binding of the start state BindingImpl binding = (BindingImpl) config.getBindings()[0] .copy(); // Update binding for free variables updateBinding(binding, args, transitions[i]); // If there is a guard, check it is satisfied if (transitions[i].getGuard() == null || transitions[i].getGuard().check(binding)) { // If there is an assignment, execute it if (transitions[i].getAssignment() != null) { binding = (BindingImpl) transitions[i] .getAssignment().apply(binding); } // Copy end state and binding in the arrays endStates[endStatesCount] = transitions[i] .getEndState(); bindings[endStatesCount] = binding; // TODO We are assuming here that there's no explicit // transition to the failing state endStatesCount++; } } if (endStatesCount == 0) { // All end states are failing states // Set failing state, leave binding as it is config.setState(0, 0); return config; } // Copy the states and bindings into the correct sized array if // needed and update the configuration if (endStatesCount != transitions.length) { int[] reducedEndStates = new int[endStatesCount]; BindingImpl[] reducedBindings = new BindingImpl[endStatesCount]; System.arraycopy(endStates, 0, reducedEndStates, 0, endStatesCount); System.arraycopy(bindings, 0, reducedBindings, 0, endStatesCount); config.setStates(reducedEndStates); config.setBindings(reducedBindings); } else { config.setStates(endStates); config.setBindings(bindings); } } } else { // Multiple start states int[] startStates = config.getStates(); int maxEndStates = 0; boolean argsNumberChecked = false; TransitionImpl[][] transitions = new TransitionImpl[startStates.length][]; // Compute maximum number of end states for (int i = 0; i < startStates.length; i++) { transitions[i] = (TransitionImpl[]) delta[startStates[i]][event]; if (transitions[i] != null) { maxEndStates += transitions[i].length; // Check number of arguments vs. number of parameters of the // event for one transition only if (!argsNumberChecked) { checkArgParamLength(args.length, transitions[i][0].getVariableNames().length); } } } // If the event is not defined for any of the current start states, // return the failing state with an empty binding if (maxEndStates == 0) { config.setStates(new int[] { 0 }); config.setBindings(new Binding[] { newBinding() }); return config; } // Create as many states and bindings as there are end states int[] endStates = new int[maxEndStates]; BindingImpl[] bindings = new BindingImpl[maxEndStates]; // Initialise end states count int endStatesCount = 0; // Iterate over the transitions for (int i = 0; i < transitions.length; i++) { if (transitions[i] != null) { for (int j = 0; j < transitions[i].length; j++) { // Copy the initial binding BindingImpl binding = (BindingImpl) config .getBindings()[i].copy(); // Update binding for free variables updateBinding(binding, args, transitions[i][j]); // If there is a guard, check it is satisfied if (transitions[i][j].getGuard() == null || transitions[i][j].getGuard().check(binding)) { // If there is an assignment, execute it if (transitions[i][j].getAssignment() != null) { binding = (BindingImpl) transitions[i][j] .getAssignment().apply(binding); } // Copy end state and binding in the arrays endStates[endStatesCount] = transitions[i][j] .getEndState(); bindings[endStatesCount] = binding; // TODO We are assuming here that there's no // explicit transition to the failing state endStatesCount++; } } } } if (endStatesCount == 0) { // All end states are failing states config.setStates(new int[] { 0 }); // TODO What happens with the binding here? What binding should // we rollback to if there are multiple (one for each start // state)? config.setBindings(new Binding[] { newBinding() }); return config; } // Copy the states and bindings into the correct sized array if // needed and update the configuration if (endStatesCount != maxEndStates) { int[] reducedEndStates = new int[endStatesCount]; BindingImpl[] reducedBindings = new BindingImpl[endStatesCount]; System.arraycopy(endStates, 0, reducedEndStates, 0, endStatesCount); System.arraycopy(bindings, 0, reducedBindings, 0, endStatesCount); config.setStates(reducedEndStates); config.setBindings(reducedBindings); } else { config.setStates(endStates); config.setBindings(bindings); } } return config; } /** * Determines if the set of states in the specified configuration contains * at least one final state * * @param config * Configuration encapsulating the set of states to be checked * @return <code>true</code> if the set of states in the specified * configuration contains at least one final state; * <code>false</code> otherwise */ public boolean containsFinalState(NonDetConfig config) { for (int i = 0; i < config.getStates().length; i++) { if (isStateFinal(config.getStates()[i])) { return true; } } return false; } @Override public int[] getEventsAlphabet() { int[] a = new int[delta[0].length - 1]; for (int i = 0; i < a.length; i++) { a[i] = i + 1; } return a; } @Override public boolean isDeterministic() { return false; } }
package gnu.mapping; import java.io.*; /** A Symbol is a Location in an Environment object. */ public class Symbol extends Location implements Externalizable // implements java.util.Map.Entry { public final String getNamespaceURI() { Environment env = getEnvironment(); return env == null ? null : env.getName(); } /** Synonym for getName - the "print name" of the symbol without Environment. * Useful when thinking of a Symbol as an XML QName. */ public final String getLocalName() { return getName(); } /** Find or create a symbol in a specificed environment. * @param environ can be an Environment, or a namespace/environment name * (resolved using Environment.getInstance), or null (in which case * an uninterned symbol is created. * @param name The "local name" or "print name" of the desired symbol. */ public static Symbol make (Object environ, String name) { if (name != null) name = name.intern(); if (environ == null) return new Symbol(name); Environment env = environ instanceof String ? Environment.getInstance((String) environ) : (Environment) environ; return env.getSymbol(name); } /** The current value of the binding. */ Object value; Constraint constraint; /** Magic value used to indicate there is no property binding. */ public static final String UNBOUND = new String("(unbound)"); /** Magic value used as a key for function bindings. */ static final String FUNCTION = new String("(function)."); public final Object get () { return constraint.get(this); } public final Object get (Object defaultValue) { return constraint.get(this, defaultValue); } public Procedure getProcedure () { try { return constraint.getProcedure(this); } catch (UnboundSymbol ex) { // FIXME!!! Object f = getFunctionValue(UNBOUND); if (f != UNBOUND) return (Procedure) f; throw ex; } } public final void defineValue(Object value) { Environment env = constraint.getEnvironment(this); if (env == null || env.locked) set(value); else { this.constraint = TrivialConstraint.getInstance(this); this.value = value; } } public final void defineConstant(Object value) { Environment env = constraint.getEnvironment(this); if (env.locked) set(value); else { this.constraint = ConstantConstraint.getInstance(env); this.value = value; } } public final void set (Object value) { constraint.set(this, value); } public final Constraint getConstraint() { return constraint; } public final void setConstraint (Constraint constraint) { this.constraint = constraint; } public boolean isBound () { return constraint.isBound(this); } public Symbol () { } public Symbol (String name) { setName(name); constraint = UnboundConstraint.getInstance((Environment) null); } // The compiler emits calls to this method. public static Symbol makeUninterned (Object init, String name) { Symbol binding = new Symbol(name); binding.value = init; binding.constraint = TrivialConstraint.getInstance((Environment) null); return binding; } public void print(java.io.PrintWriter ps) { ps.print ("#<binding "); String name = getName(); if (name != null) ps.print(name); if (isBound()) { ps.print(" -> "); ps.print(get()); } else ps.print("(unbound)"); ps.print ('>'); } // Methods that implement java.util.Map.Entry: public final Object getKey () { return getName(); } public final Object getValue () { return constraint.get(this); } public final Object setValue (Object value) { Object old = constraint.get(this); constraint.set(this, value); return old; } /** Just tests for identity. * Otherwise hashTables that have Symbols as keys will break. */ public boolean equals (Object o) { return this == o; } public int hashCode () { // Note: The hashCode should not depend on the value. // This is contrary to the Map.Entry specification. return System.identityHashCode(this); // ^ System.identityHashCode(env); } /** Used to mark deleted elements in a hash table. */ public final static Symbol hashDELETED = new Symbol(new String("<Deleted>")); /** Search a hash table using double hashing and open addressing. * @param table the hash table * @param log2Size log2 of the (used) size of table * @param mask must equal ((1 << log2Size) - 1) * @param key the search key * @param hash the hash of the search key * @return the index of the element in table containing the match * (such that table[index].getName()==key); * if there is no such element, returns an index * such that (table[index]==null || tabel[index]==DELETED). */ public static int hashSearch (Symbol[] table, int log2Size, int mask, String key, int hash) { int index = hash & mask; Symbol element = table[index]; if (element == null || element.getName() == key) return index; int avail = -1; int step = (((hash >> log2Size) ^ index) << 1) + 1; for (;;) { if (element == hashDELETED && avail < 0) avail = index; index = (index + step) & mask; element = table[index]; if (element == null) return avail < 0 ? index : avail; if (element.getName() == key) return index; } } public static int hashSearch (Symbol[] table, int log2Size, String key) { return hashSearch(table, log2Size, (1 << log2Size) - 1, key, System.identityHashCode(key)); } /** Find an entry in a hash table. * @param table the hash table * @param log2Size log2 of the (used) size of table * @param key the search key * @return null if the was no matching element in the hash table; * otherwise the matching element. */ public static Symbol hashGet (Symbol[] table, int log2Size, String key) { int index = hashSearch(table, log2Size, (1 << log2Size) - 1, key, System.identityHashCode(key)); Symbol element = table[index]; if (element == null || element == hashDELETED) return null; return element; } /** Set an entry in a hash table. * @param table the hash table * @param log2Size log2 of the (used) size of table * @param value the new entry * @return null if the was no matching element in the hash table; * otherwise the old match. */ public static Symbol hashSet (Symbol[] table, int log2Size, Symbol value) { String key = value.getName(); int index = hashSearch(table, log2Size, (1 << log2Size) - 1, key, System.identityHashCode(key)); Symbol element = table[index]; table[index] = value; return element == hashDELETED ? null : element; } /** Delete an entry from a hash table. * @param table the hash table * @param log2Size log2 of the (used) size of table * @param key the search key * @return null if the was no matching element in the hash table; * otherwise the old element. */ public static Symbol hashDelete (Symbol[] table, int log2Size, String key) { int index = hashSearch(table, log2Size, (1 << log2Size) - 1, key, System.identityHashCode(key)); Symbol element = table[index]; table[index] = hashDELETED; return element == hashDELETED ? null : element; } public static int hashInsertAll (Symbol[] tableDst, int log2SizeDst, Symbol[] tableSrc, int log2SizeSrc) { int countInserted = 0; int sizeSrc = 1 << log2SizeSrc; int sizeDst = 1 << log2SizeDst; int maskDst = (1 << log2SizeDst) - 1; for (int i = sizeSrc; --i >= 0;) { Symbol element = tableSrc[i]; if (element != null && element != hashDELETED) { String key = element.getName(); int index = hashSearch(tableDst, log2SizeDst, maskDst, key, System.identityHashCode(key)); Symbol oldElement = tableDst[index]; if (oldElement != null && oldElement != hashDELETED) countInserted++; tableDst[index] = element; } } return countInserted; } /** Get value of "function binding" of a Symbol. * Some languages (including Common Lisp and Emacs Lisp) associate both * a value binding and a function binding with a symbol. * @exception UnboundSymbol if no function binding. */ public final Object getFunctionValue() { Object value = constraint.getFunctionValue(this); if (value == UNBOUND) throw new UnboundSymbol(getName()); return value; } /** Get value of "function binding" of a Symbol. * Some languages (including Common Lisp and Emacs Lisp) associate both * a value binding and a function binding with a symbol. * @param defaultValue value to return if there is no function binding * @return the function value, or defaultValue if no function binding. */ public final Object getFunctionValue(Object defaultValue) { Object value = constraint.getFunctionValue(this); return value == UNBOUND ? defaultValue : value; } public boolean hasFunctionValue() { Object value = constraint.getFunctionValue(this); return value != UNBOUND; } public void setFunctionValue(Object value) { constraint.setFunctionValue(this, value); } public void removeFunctionValue() { constraint.setFunctionValue(this, UNBOUND); } public final Environment getEnvironment() { return constraint.getEnvironment(this); } public String toString() { String uri = getNamespaceURI(); if (uri == null || uri.length() == 0) return getName(); return '{'+getNamespaceURI()+"}"+getName(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(getEnvironment()); out.writeObject(getName()); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { Environment env = (Environment) in.readObject(); if (env == null) constraint = UnboundConstraint.getInstance((Environment) null); else constraint = env.unboundConstraint; String name = (String) in.readObject(); if (name != null) setName(name.intern()); } public Object readResolve() throws ObjectStreamException { if (constraint == null) return this; Environment env = constraint.getEnvironment(this); if (env == null) return this; return make(env, getName()); } }
package view; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.VPos; import javafx.scene.control.*; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.RowConstraints; import model.Proof; import java.util.prefs.Preferences; public class WelcomeView implements View { ViewTab tab; TextField premises; TextField conclusion; CheckBox notAgain; public WelcomeView(TabPane tabPane) { GridPane gridPane = new GridPane(); gridPane.setVgap(20.0); gridPane.setPadding(new Insets(20.0, 20.0, 20.0, 20.0)); String sTitle = "Conan"; String sWelcomeText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ante est, placerat quis ultricies sed, varius nec ante. Nullam interdum eu tortor quis faucibus. Duis accumsan purus ac diam porta, eget semper arcu pulvinar. Sed et ornare ligula. Morbi sollicitudin pretium eros, vitae feugiat ante tincidunt vel. Cras aliquam lobortis neque, non rutrum orci volutpat et. Nam at tincidunt mauris. Phasellus lobortis lorem dolor, sit amet tempus nulla pellentesque nec. Aenean a venenatis lectus."; sWelcomeText += " " + sWelcomeText; String sTab = "Welcome"; Label title = new Label(sTitle); title.getStyleClass().add("myTitle"); Label welcomeText = new Label(sWelcomeText); welcomeText.getStyleClass().add("myText"); welcomeText.setWrapText(true); RowConstraints rowC1 = new RowConstraints(); RowConstraints rowC2 = new RowConstraints(); RowConstraints rowC3 = new RowConstraints(); RowConstraints rowC4 = new RowConstraints(); RowConstraints rowC5 = new RowConstraints(); rowC1.setPrefHeight(20.0); rowC2.setPrefHeight(20.0); rowC3.setFillHeight(true); rowC4.setPrefHeight(20.0); rowC5.setPrefHeight(20.0); HBox premisesAndConclusion = CommonPanes.premisesAndConclusion(); this.premises = (TextField) premisesAndConclusion.getChildren().get(0); this.conclusion = (TextField) premisesAndConclusion.getChildren().get(2); Hyperlink help = new Hyperlink("Help me!"); Hyperlink rules = new Hyperlink("Rules!"); rules.setOnAction(event -> { Preferences prefs = Preferences.userRoot().node("General"); TabPane helpTab= tab.getTabPane(); new HelpView(helpTab); } ); this.notAgain = new CheckBox("Do not show again"); Button butNext = new Button("Continue"); butNext.setOnAction(event -> { Preferences prefs = Preferences.userRoot().node("General"); TabPane tabPane1 = tab.getTabPane(); if (!this.notAgain.isIndeterminate() && this.notAgain.selectedProperty().getValue()) { prefs.putBoolean("showWelcome", false); } tabPane1.getTabs().remove(tab); new ProofView(tabPane1, new Proof(), premises.getText(), conclusion.getText()); }); gridPane.getRowConstraints().addAll(rowC1, rowC2, rowC3, rowC4, rowC5); gridPane.add(title, 0, 0); gridPane.add(help, 0, 1); gridPane.add(rules, 0, 1); gridPane.add(welcomeText, 0, 2); gridPane.add(premisesAndConclusion, 0, 3); gridPane.add(this.notAgain, 0, 4); gridPane.add(butNext, 0, 4); gridPane.setHalignment(title, HPos.CENTER); gridPane.setValignment(title, VPos.CENTER); gridPane.setHalignment(help, HPos.CENTER); gridPane.setHalignment(rules, HPos.LEFT); gridPane.setHalignment(premisesAndConclusion, HPos.CENTER); gridPane.setValignment(premisesAndConclusion, VPos.CENTER); gridPane.setHalignment(notAgain, HPos.LEFT); gridPane.setHalignment(butNext, HPos.RIGHT); ScrollPane scrollPane = new ScrollPane(gridPane); scrollPane.setFitToWidth(true); scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS); AnchorPane ap = new AnchorPane(scrollPane); ap.setTopAnchor(scrollPane, 0.0); ap.setRightAnchor(scrollPane, 0.0); ap.setBottomAnchor(scrollPane, 0.0); ap.setLeftAnchor(scrollPane, 0.0); this.tab = new ViewTab(sTab, this); this.tab.setContent(ap); tabPane.getTabs().add(this.tab); tabPane.getSelectionModel().select(this.tab); } @Override public ViewTab getTab() { return this.tab; } }
package pt.fccn.sobre.arquivo.pages; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class IndexSobrePage { WebDriver driver; private final int timeout = 50; Map< String, String > textTolink; private final String dir = "sobreTestsFiles"; /** * * @param driver * @throws IOException */ public IndexSobrePage( WebDriver driver ) throws IOException { this.driver = driver; Properties prop = new Properties( ); InputStream input = null; try { input = new FileInputStream( "sobreTestsFiles/props_indexPage.properties" ); prop.load( new InputStreamReader( input, Charset.forName("UTF-8") ) ); //load a properties file } catch ( FileNotFoundException e ) { throw e; } catch ( IOException e1) { if( input != null) input.close( ); throw e1; } try { Thread.sleep( 5000 ); //wait for page to load } catch( InterruptedException ex ) { Thread.currentThread( ).interrupt( ); } // Check that we're on the right page. String pageTitle= driver.getTitle( ); Charset.forName( "UTF-8" ).encode( pageTitle ); System.out.println( "Page title = " + pageTitle + " == " + prop.getProperty( "title_pt" ) ); if ( !( pageTitle.contentEquals( prop.getProperty( "title_pt" ) ) || (pageTitle.contentEquals("title_en") ) ) ){ throw new IllegalStateException("This is not the index page\n Title of current page: " + pageTitle); } } /** * Click the link to the footer of the page * @throws FileNotFoundException */ public CommonQuestionsPage goToCommonQuestionsPage( ) throws FileNotFoundException{ try{ System.out.println( "Start goToCommonQuestionsPage() method" ); WebElement cQuestionsLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( /** * * @return */ public ExamplesPage goToExamplePage( ) { try{ System.out.println( "Start goToExamplePage() method" ); WebElement examplePageLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( /** * Check if link exists * @param URLName * @return */ private boolean linkExists( String URLName , String text ) { boolean redirect = false; try { System.out.println( "[Footer] url[" + URLName + "]" ); HttpURLConnection.setFollowRedirects( false ); HttpURLConnection con = ( HttpURLConnection ) new URL( URLName ).openConnection( ); con.setConnectTimeout( timeout ); con.setRequestMethod( "HEAD" ); con.addRequestProperty( "Accept-Language", "en-US,en;q=0.8" ); con.addRequestProperty( "User-Agent", "Mozilla" ); con.addRequestProperty( "Referer", "google.com" ); // normally, 3xx is redirect int status = con.getResponseCode( ); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } System.out.println( "[Footer] url[" + URLName + "] Status-code = " + con.getResponseCode( ) ); if( redirect ) { // get redirect url from "location" header field String newUrl = con.getHeaderField( "Location" ); System.out.println( "Redirect: true url["+URLName+"] newurl["+newUrl+"]" ); // get the cookie if need, for login String cookies = con.getHeaderField( "Set-Cookie" ); // open the new connection again con = ( HttpURLConnection ) new URL( newUrl ).openConnection( ); con.setConnectTimeout( timeout ); con.setRequestProperty( "Cookie", cookies ); con.addRequestProperty( "Accept-Language", "en-US,en;q=0.8" ); con.addRequestProperty( "User-Agent", "Mozilla" ); con.addRequestProperty( "Referer", "google.com" ); status = con.getResponseCode( ); URLName = newUrl; } System.out.println( "Compare textTolink.get( "+text+" ) = " + textTolink.get( text ) + " URLName = " + URLName ); if( status == HttpURLConnection.HTTP_OK && textTolink.get( text ).equals( URLName ) ) return true; else return false; } catch ( MalformedURLException e ) { e.printStackTrace( ); return false; } catch ( IOException e ) { e.printStackTrace( ); return false; } } private boolean readFromFile( String filename ) { textTolink = new HashMap< String , String >( ); try { BufferedReader in = new BufferedReader( new FileReader( dir.concat( File.separator ).concat( filename ) ) ); String line = ""; while( (line = in.readLine( )) != null ) { String parts[ ] = line.split( "," ); Charset.forName( "UTF-8" ).encode( parts[ 0 ] ); textTolink.put( parts[ 0 ], parts[ 1 ] ); } in.close( ); System.out.println( "Map => " + textTolink.toString( ) ); return true; } catch ( FileNotFoundException e ) { e.printStackTrace( ); return false; } catch (IOException e) { e.printStackTrace( ); return false; } } }
package org.voltdb.iv2; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.mockito.InOrder; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; import org.voltcore.utils.Pair; import junit.framework.*; import org.junit.Test; import org.voltdb.messaging.CompleteTransactionMessage; import org.voltdb.messaging.FragmentTaskMessage; import org.voltdb.messaging.Iv2RepairLogRequestMessage; import org.voltdb.messaging.Iv2RepairLogResponseMessage; public class TestMpPromoteAlgo extends TestCase { Iv2RepairLogResponseMessage makeFragResponse(long handle) { FragmentTaskMessage frag = mock(FragmentTaskMessage.class); Iv2RepairLogResponseMessage m = mock(Iv2RepairLogResponseMessage.class); when(m.getPayload()).thenReturn(frag); when(m.getHandle()).thenReturn(handle); return m; } Iv2RepairLogResponseMessage makeCompleteResponse(long handle) { CompleteTransactionMessage complete = mock(CompleteTransactionMessage.class); Iv2RepairLogResponseMessage m = mock(Iv2RepairLogResponseMessage.class); when(m.getPayload()).thenReturn(complete); when(m.getHandle()).thenReturn(handle); return m; } Iv2RepairLogResponseMessage makeRealCompleteResponse(long requestId, long sourceHSId, int sequence, int ofTotal, long handle) { CompleteTransactionMessage complete = mock(CompleteTransactionMessage.class); Iv2RepairLogResponseMessage m = new Iv2RepairLogResponseMessage(requestId, sequence, ofTotal, handle, complete); m.m_sourceHSId = sourceHSId; return m; } Iv2RepairLogResponseMessage makeRealAckResponse(long requestId, long sourceHSId, int sequence, int ofTotal, long handle) { assertEquals(0, sequence); Iv2RepairLogResponseMessage m = new Iv2RepairLogResponseMessage(requestId, sequence, ofTotal, handle, null); m.m_sourceHSId = sourceHSId; return m; } Iv2RepairLogResponseMessage makeRealFragResponse(long requestId, long sourceHSId, int sequence, int ofTotal, long handle) { FragmentTaskMessage frag = mock(FragmentTaskMessage.class); Iv2RepairLogResponseMessage m = new Iv2RepairLogResponseMessage(requestId, sequence, ofTotal, handle, frag); m.m_sourceHSId = sourceHSId; return m; } // Iv2RepairLogResponseMessage makeStaleResponse(long handle, long requestId) // Iv2RepairLogResponseMessage m = makeFragResponse(handle); // when(m.getRequestId()).thenReturn(requestId); // return m; // verify that responses are correctly unioned and ordered. @Test public void testUnion() throws Exception { MpPromoteAlgo algo = new MpPromoteAlgo(new ArrayList<Long>(), null, "Test"); // returned handles in a non-trivial order, with duplicates. // txns 1-5 are complete. 6 is not complete. // txn 5 returns frag(s) and complete(s). final Boolean t = true; final Boolean f = false; long returnedHandles[] = new long[]{1L, 5L, 2L, 5L, 6L, 3L, 5L, 1L}; boolean isComplete[] = new boolean[]{t, f, t, t, f, t, f, t}; long expectedUnion[] = new long[]{1L, 2L, 3L, 5L, 6L}; boolean expectComp[] = new boolean[]{t, t, t, t, f}; for (int ii=0; ii < isComplete.length; ii++) { if (isComplete[ii]) { algo.addToRepairLog(makeCompleteResponse(returnedHandles[ii])); } else { algo.addToRepairLog(makeFragResponse(returnedHandles[ii])); } } // assert one log entry per transaction and that complete trumped frag. assertEquals(expectedUnion.length, algo.m_repairLogUnion.size()); int i = 0; for (Iv2RepairLogResponseMessage li : algo.m_repairLogUnion) { assertEquals(li.getHandle(), expectedUnion[i]); if (expectComp[i]) { assertTrue(li.getPayload() instanceof CompleteTransactionMessage); } else { assertTrue(li.getPayload() instanceof FragmentTaskMessage); } i++; } } // verify that algo asks initMailbox to send the expected repair messages. @Test public void testRepairSurvivors() throws InterruptedException, ExecutionException { InitiatorMailbox mailbox = mock(InitiatorMailbox.class); ArrayList<Long> masters = new ArrayList<Long>(); masters.add(1L); masters.add(2L); masters.add(3L); MpPromoteAlgo algo = new MpPromoteAlgo(masters, mailbox, "Test"); long requestId = algo.getRequestId(); Future<Pair<Boolean, Long>> result = algo.start(); verify(mailbox, times(1)).send(any(long[].class), any(Iv2RepairLogRequestMessage.class)); // has a frag for txn 1000. MP handle is 1000L algo.deliver(makeRealAckResponse(requestId, 1L, 0, 2, 1000L)); algo.deliver(makeRealFragResponse(requestId, 1L, 1, 2, 1000L)); // has only the normal ack. Never saw an MP transaction. algo.deliver(makeRealAckResponse(requestId, 2L, 0, 1, Long.MAX_VALUE)); // also has a complete. MP handle is 1000L algo.deliver(makeRealAckResponse(requestId, 3L, 0, 3, 1000L)); algo.deliver(makeRealFragResponse(requestId, 3L, 1, 3, 1000L)); algo.deliver(makeRealCompleteResponse(requestId, 3L, 2, 3, 1000L)); // verify exactly 1 repair happened. List<Long> needsRepair = new ArrayList<Long>(); needsRepair.add(1L); verify(mailbox, times(1)).repairReplicasWith(eq(needsRepair), any(Iv2RepairLogResponseMessage.class)); Pair<Boolean, Long> real_result = result.get(); assertEquals(1000L, (long)real_result.getSecond()); } @Test public void testSlowDieOff() throws InterruptedException, ExecutionException { InitiatorMailbox mailbox = mock(InitiatorMailbox.class); InOrder inOrder = inOrder(mailbox); ArrayList<Long> masters = new ArrayList<Long>(); masters.add(1L); masters.add(2L); masters.add(3L); MpPromoteAlgo algo = new MpPromoteAlgo(masters, mailbox, "Test"); long requestId = algo.getRequestId(); Future<Pair<Boolean, Long>> result = algo.start(); // Master 1 // First, everyone completed // has a frag for txn 1000. MP handle is 1000L algo.deliver(makeRealAckResponse(requestId, 1L, 0, 8, 1000L)); algo.deliver(makeRealFragResponse(requestId, 1L, 1, 8, 1000L)); algo.deliver(makeRealCompleteResponse(requestId, 1L, 2, 8, 1000L)); // Second, 3 will lose complete algo.deliver(makeRealFragResponse(requestId, 1L, 3, 8, 1001L)); algo.deliver(makeRealCompleteResponse(requestId, 1L, 4, 8, 1001L)); // Third, 2 will lose complete and 3 has nothing algo.deliver(makeRealFragResponse(requestId, 1L, 5, 8, 1002L)); algo.deliver(makeRealCompleteResponse(requestId, 1L, 6, 8, 1002L)); // Fourth, 1 just has a fragment, the other two are gone. algo.deliver(makeRealFragResponse(requestId, 1L, 7, 8, 1003L)); // Master 2 // has only the normal ack. Never saw an MP transaction. algo.deliver(makeRealAckResponse(requestId, 2L, 0, 6, 1000L)); algo.deliver(makeRealFragResponse(requestId, 2L, 1, 6, 1000L)); algo.deliver(makeRealCompleteResponse(requestId, 2L, 2, 6, 1000L)); // second, 3 loses complete algo.deliver(makeRealFragResponse(requestId, 2L, 3, 6, 1001L)); algo.deliver(makeRealCompleteResponse(requestId, 2L, 4, 6, 1001L)); // third, 2 (us) loses complete algo.deliver(makeRealFragResponse(requestId, 2L, 5, 6, 1002L)); // Master 3 // also has a complete. MP handle is 1000L algo.deliver(makeRealAckResponse(requestId, 3L, 0, 4, 1000L)); algo.deliver(makeRealFragResponse(requestId, 3L, 1, 4, 1000L)); algo.deliver(makeRealCompleteResponse(requestId, 3L, 2, 4, 1000L)); // 3 loses complete algo.deliver(makeRealFragResponse(requestId, 3L, 3, 4, 1001L)); // First, repair 3 List<Long> needsRepair = new ArrayList<Long>(); needsRepair.add(3L); inOrder.verify(mailbox).repairReplicasWith(eq(needsRepair), any(Iv2RepairLogResponseMessage.class)); needsRepair.clear(); needsRepair.add(2L); needsRepair.add(3L); inOrder.verify(mailbox).repairReplicasWith(eq(needsRepair), any(Iv2RepairLogResponseMessage.class)); needsRepair.clear(); needsRepair.add(1L); needsRepair.add(2L); needsRepair.add(3L); inOrder.verify(mailbox).repairReplicasWith(eq(needsRepair), any(Iv2RepairLogResponseMessage.class)); Pair<Boolean, Long> real_result = result.get(); assertEquals(1003L, (long)real_result.getSecond()); } // verify correct txnID when no MP has ever been done @Test public void testSaneWithNoMP() throws InterruptedException, ExecutionException { InitiatorMailbox mailbox = mock(InitiatorMailbox.class); ArrayList<Long> masters = new ArrayList<Long>(); masters.add(1L); masters.add(2L); masters.add(3L); MpPromoteAlgo algo = new MpPromoteAlgo(masters, mailbox, "Test"); long requestId = algo.getRequestId(); Future<Pair<Boolean, Long>> result = algo.start(); verify(mailbox, times(1)).send(any(long[].class), any(Iv2RepairLogRequestMessage.class)); // has only the normal ack. Never saw an MP transaction. algo.deliver(makeRealAckResponse(requestId, 1L, 0, 1, Long.MAX_VALUE)); // has only the normal ack. Never saw an MP transaction. algo.deliver(makeRealAckResponse(requestId, 2L, 0, 1, Long.MAX_VALUE)); // has only the normal ack. Never saw an MP transaction. algo.deliver(makeRealAckResponse(requestId, 3L, 0, 1, Long.MAX_VALUE)); // verify that the discovered txn id is 0 (the correct starting txnid). Pair<Boolean, Long> real_result = result.get(); assertEquals(0L, (long)real_result.getSecond()); } /* // verify that bad request ids are not submitted to the log. @Test public void testStaleResponse() throws Exception { MpPromoteAlgo term = new SpPromoteAlgo(null, null, 0, null, VoltZK.iv2masters, "Test"); term.deliver(makeStaleResponse(1L, term.getRequestId() + 1)); assertEquals(0L, term.m_repairLogUnion.size()); } // verify that the all-done logic works on replica repair structs @Test public void testRepairLogsAreComplete() { MpPromoteAlgo term = new SpPromoteAlgo(null, null, 0, null, VoltZK.iv2masters, "Test"); MpPromoteAlgo.ReplicaRepairStruct notDone1 = new SpPromoteAlgo.ReplicaRepairStruct(); notDone1.m_receivedResponses = 1; notDone1.m_expectedResponses = 2; assertFalse(notDone1.logsComplete()); MpPromoteAlgo.ReplicaRepairStruct notDone2 = new SpPromoteAlgo.ReplicaRepairStruct(); notDone2.m_receivedResponses = 0; notDone2.m_expectedResponses = 10; MpPromoteAlgo.ReplicaRepairStruct done1 = new SpPromoteAlgo.ReplicaRepairStruct(); done1.m_receivedResponses = 5; done1.m_expectedResponses = 5; assertTrue(done1.logsComplete()); MpPromoteAlgo.ReplicaRepairStruct done2 = new SpPromoteAlgo.ReplicaRepairStruct(); done2.m_receivedResponses = 10; done2.m_expectedResponses = 10; term.m_replicaRepairStructs.put(0L, notDone1); term.m_replicaRepairStructs.put(1L, done1); term.m_replicaRepairStructs.put(2L, notDone2); term.m_replicaRepairStructs.put(3L, done2); assertFalse(term.areRepairLogsComplete()); term.m_replicaRepairStructs.clear(); term.m_replicaRepairStructs.put(2L, notDone2); assertFalse(term.areRepairLogsComplete()); term.m_replicaRepairStructs.clear(); term.m_replicaRepairStructs.put(1L, done1); term.m_replicaRepairStructs.put(3L, done2); assertTrue(term.areRepairLogsComplete()); term.m_replicaRepairStructs.clear(); term.m_replicaRepairStructs.put(3L, done2); assertTrue(term.areRepairLogsComplete()); } // be a little a paranoid about order. note that the union test also verifies // order; unsure this is interesting... This test is on one replica because // I'm not sure that we guarentee the orer of iteration across replicas. @SuppressWarnings("unchecked") @Test public void testRepairSurvivorOrder() { InitiatorMailbox mailbox = mock(InitiatorMailbox.class); InOrder inOrder = inOrder(mailbox); MpPromoteAlgo term = new SpPromoteAlgo(null, mock(ZooKeeper.class), 0, mailbox, VoltZK.iv2masters, "Test"); // missing 3, 4, 5 MpPromoteAlgo.ReplicaRepairStruct r3 = new SpPromoteAlgo.ReplicaRepairStruct(); r3.m_maxSpHandleSeen = 2L; term.m_replicaRepairStructs.put(3L, r3); // build the log long spHandles[] = new long[]{0L, 1L, 2L, 3L, 4L, 5L}; Iv2RepairLogResponseMessage msgs[] = new Iv2RepairLogResponseMessage[6]; for (int i=1; i < spHandles.length; ++i) { msgs[i] = makeResponse(spHandles[i]); term.m_repairLogUnion.add(msgs[i]); } // call the function being tested... term.repairSurvivors(); List<Long> repair3 = new ArrayList<Long>(); repair3.add(3L); // verify that r3 saw 3, 4, 5 inOrder.verify(mailbox).repairReplicasWith(repair3, msgs[3]); inOrder.verify(mailbox).repairReplicasWith(repair3, msgs[4]); inOrder.verify(mailbox).repairReplicasWith(repair3, msgs[5]); // verify exactly 3 repairs happened. verify(mailbox, times(3)).repairReplicasWith(any(repair3.getClass()), any(Iv2RepairLogResponseMessage.class)); } // Verify that a babysitter update causes the term to be cancelled. @Test public void testMidPromotionReplicaUpdate() throws Exception { final AtomicBoolean promotionResult = new AtomicBoolean(true); final InitiatorMailbox mailbox = mock(InitiatorMailbox.class); // Stub some portions of a concrete Term instance - this is the // object being tested. final MpPromoteAlgo term = new SpPromoteAlgo(null, mock(ZooKeeper.class), 0, mailbox, VoltZK.iv2masters, "Test") { // there aren't replicas to ask for repair logs @Override void prepareForFaultRecovery() { } }; Thread promotionThread = new Thread() { @Override public void run() { try { promotionResult.set(term.start().get().getFirst()); } catch (Exception e) { System.out.println("Promotion thread threw: " + e); throw new RuntimeException(e); } } }; promotionThread.start(); // cancel the term as if updateReplica() triggered. term.cancel(); promotionThread.join(); // promotion success must be false after cancel. assertFalse(promotionResult.get()); } */ }
package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.general.SeriesChangeEvent; import org.jfree.data.general.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; import org.jfree.date.MonthConstants; /** * A collection of test cases for the {@link TimeSeries} class. */ public class TimeSeriesTests extends TestCase implements SeriesChangeListener { /** A time series. */ private TimeSeries seriesA; /** A time series. */ private TimeSeries seriesB; /** A time series. */ private TimeSeries seriesC; /** A flag that indicates whether or not a change event was fired. */ private boolean gotSeriesChangeEvent = false; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TimeSeriesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TimeSeriesTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { this.seriesA = new TimeSeries("Series A", Year.class); try { this.seriesA.add(new Year(2000), new Integer(102000)); this.seriesA.add(new Year(2001), new Integer(102001)); this.seriesA.add(new Year(2002), new Integer(102002)); this.seriesA.add(new Year(2003), new Integer(102003)); this.seriesA.add(new Year(2004), new Integer(102004)); this.seriesA.add(new Year(2005), new Integer(102005)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesB = new TimeSeries("Series B", Year.class); try { this.seriesB.add(new Year(2006), new Integer(202006)); this.seriesB.add(new Year(2007), new Integer(202007)); this.seriesB.add(new Year(2008), new Integer(202008)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesC = new TimeSeries("Series C", Year.class); try { this.seriesC.add(new Year(1999), new Integer(301999)); this.seriesC.add(new Year(2000), new Integer(302000)); this.seriesC.add(new Year(2002), new Integer(302002)); } catch (SeriesException e) { System.err.println("Problem creating series."); } } /** * Sets the flag to indicate that a {@link SeriesChangeEvent} has been * received. * * @param event the event. */ public void seriesChanged(SeriesChangeEvent event) { this.gotSeriesChangeEvent = true; } /** * Check that cloning works. */ public void testClone() { TimeSeries series = new TimeSeries("Test Series"); RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002); try { series.add(jan1st2002, new Integer(42)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } TimeSeries clone = null; try { clone = (TimeSeries) series.clone(); clone.setKey("Clone Series"); try { clone.update(jan1st2002, new Integer(10)); } catch (SeriesException e) { e.printStackTrace(); } } catch (CloneNotSupportedException e) { assertTrue(false); } int seriesValue = series.getValue(jan1st2002).intValue(); int cloneValue = Integer.MAX_VALUE; if (clone != null) { cloneValue = clone.getValue(jan1st2002).intValue(); } assertEquals(42, seriesValue); assertEquals(10, cloneValue); assertEquals("Test Series", series.getKey()); if (clone != null) { assertEquals("Clone Series", clone.getKey()); } else { assertTrue(false); } } /** * Add a value to series A for 1999. It should be added at index 0. */ public void testAddValue() { try { this.seriesA.add(new Year(1999), new Integer(1)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } int value = this.seriesA.getValue(0).intValue(); assertEquals(1, value); } /** * Tests the retrieval of values. */ public void testGetValue() { Number value1 = this.seriesA.getValue(new Year(1999)); assertNull(value1); int value2 = this.seriesA.getValue(new Year(2000)).intValue(); assertEquals(102000, value2); } /** * Tests the deletion of values. */ public void testDelete() { this.seriesA.delete(0, 0); assertEquals(5, this.seriesA.getItemCount()); Number value = this.seriesA.getValue(new Year(2000)); assertNull(value); } /** * Basic tests for the delete() method. */ public void testDelete2() { TimeSeries s1 = new TimeSeries("Series", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.addChangeListener(this); this.gotSeriesChangeEvent = false; s1.delete(new Year(2001)); assertTrue(this.gotSeriesChangeEvent); assertEquals(2, s1.getItemCount()); assertEquals(null, s1.getValue(new Year(2001))); // try deleting a time period that doesn't exist... this.gotSeriesChangeEvent = false; s1.delete(new Year(2006)); assertFalse(this.gotSeriesChangeEvent); // try deleting null try { s1.delete(null); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { TimeSeries s1 = new TimeSeries("A test", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); TimeSeries s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); s2 = (TimeSeries) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(s1.equals(s2)); } /** * Tests the equals method. */ public void testEquals() { TimeSeries s1 = new TimeSeries("Time Series 1"); TimeSeries s2 = new TimeSeries("Time Series 2"); boolean b1 = s1.equals(s2); assertFalse("b1", b1); s2.setKey("Time Series 1"); boolean b2 = s1.equals(s2); assertTrue("b2", b2); RegularTimePeriod p1 = new Day(); RegularTimePeriod p2 = p1.next(); s1.add(p1, 100.0); s1.add(p2, 200.0); boolean b3 = s1.equals(s2); assertFalse("b3", b3); s2.add(p1, 100.0); s2.add(p2, 200.0); boolean b4 = s1.equals(s2); assertTrue("b4", b4); s1.setMaximumItemCount(100); boolean b5 = s1.equals(s2); assertFalse("b5", b5); s2.setMaximumItemCount(100); boolean b6 = s1.equals(s2); assertTrue("b6", b6); s1.setMaximumItemAge(100); boolean b7 = s1.equals(s2); assertFalse("b7", b7); s2.setMaximumItemAge(100); boolean b8 = s1.equals(s2); assertTrue("b8", b8); } /** * Tests a specific bug report where null arguments in the constructor * cause the equals() method to fail. Fixed for 0.9.21. */ public void testEquals2() { TimeSeries s1 = new TimeSeries("Series", null, null, Day.class); TimeSeries s2 = new TimeSeries("Series", null, null, Day.class); assertTrue(s1.equals(s2)); } /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */ public void testCreateCopy1() { TimeSeries series = new TimeSeries("Series", Month.class); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy a range before the start of the series data... TimeSeries result1 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2002)); assertEquals(0, result1.getItemCount()); // copy a range that includes only the first item in the series... TimeSeries result2 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result2.getItemCount()); // copy a range that begins before and ends in the middle of the // series... TimeSeries result3 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result3.getItemCount()); TimeSeries result4 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result4.getItemCount()); TimeSeries result5 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result5.getItemCount()); TimeSeries result6 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result6.getItemCount()); TimeSeries result7 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result7.getItemCount()); TimeSeries result8 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result8.getItemCount()); TimeSeries result9 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result9.getItemCount()); TimeSeries result10 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(3, result10.getItemCount()); TimeSeries result11 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(3, result11.getItemCount()); TimeSeries result12 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(1, result12.getItemCount()); TimeSeries result13 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(1, result13.getItemCount()); TimeSeries result14 = series.createCopy( new Month(MonthConstants.JANUARY, 2004), new Month(MonthConstants.MARCH, 2004)); assertEquals(0, result14.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Some tests to ensure that the createCopy(int, int) method is * functioning correctly. */ public void testCreateCopy2() { TimeSeries series = new TimeSeries("Series", Month.class); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy just the first item... TimeSeries result1 = series.createCopy(0, 0); assertEquals(new Month(1, 2003), result1.getTimePeriod(0)); // copy the first two items... result1 = series.createCopy(0, 1); assertEquals(new Month(2, 2003), result1.getTimePeriod(1)); // copy the middle three items... result1 = series.createCopy(1, 3); assertEquals(new Month(2, 2003), result1.getTimePeriod(0)); assertEquals(new Month(11, 2003), result1.getTimePeriod(2)); // copy the last two items... result1 = series.createCopy(3, 4); assertEquals(new Month(11, 2003), result1.getTimePeriod(0)); assertEquals(new Month(12, 2003), result1.getTimePeriod(1)); // copy the last item... result1 = series.createCopy(4, 4); assertEquals(new Month(12, 2003), result1.getTimePeriod(0)); } catch (CloneNotSupportedException e) { assertTrue(false); } // check negative first argument boolean pass = false; try { /* TimeSeries result = */ series.createCopy(-1, 1); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); // check second argument less than first argument pass = false; try { /* TimeSeries result = */ series.createCopy(1, 0); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); TimeSeries series2 = new TimeSeries("Series 2"); try { TimeSeries series3 = series2.createCopy(99, 999); assertEquals(0, series3.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */ public void testSetMaximumItemCount() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); assertTrue(s1.getItemCount() == 5); s1.setMaximumItemCount(3); assertTrue(s1.getItemCount() == 3); TimeSeriesDataItem item = s1.getDataItem(0); assertTrue(item.getPeriod().equals(new Year(2002))); } /** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.setMaximumItemCount(2); s1.addOrUpdate(new Year(2000), 100.0); assertEquals(1, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 101.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 102.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2002), 103.0); assertEquals(2, s1.getItemCount()); } /** * A test for the bug report 1075255. */ public void testBug1075255() { TimeSeries ts = new TimeSeries("dummy", FixedMillisecond.class); ts.add(new FixedMillisecond(0L), 0.0); TimeSeries ts2 = new TimeSeries("dummy2", FixedMillisecond.class); ts2.add(new FixedMillisecond(0L), 1.0); try { ts.addAndOrUpdate(ts2); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } assertEquals(1, ts.getItemCount()); } /** * Some checks for the getIndex() method. */ public void testGetIndex() { TimeSeries series = new TimeSeries("Series", Month.class); assertEquals(-1, series.getIndex(new Month(1, 2003))); series.add(new Month(1, 2003), 45.0); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(-2, series.getIndex(new Month(2, 2003))); series.add(new Month(3, 2003), 55.0); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-2, series.getIndex(new Month(2, 2003))); assertEquals(1, series.getIndex(new Month(3, 2003))); assertEquals(-3, series.getIndex(new Month(4, 2003))); } /** * Some checks for the getDataItem(int) method. */ public void testGetDataItem1() { TimeSeries series = new TimeSeries("S", Year.class); // can't get anything yet...just an exception boolean pass = false; try { /*TimeSeriesDataItem item =*/ series.getDataItem(0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); series.add(new Year(2006), 100.0); TimeSeriesDataItem item = series.getDataItem(0); assertEquals(new Year(2006), item.getPeriod()); pass = false; try { /*item = */series.getDataItem(-1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); pass = false; try { /*item = */series.getDataItem(1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getDataItem(RegularTimePeriod) method. */ public void testGetDataItem2() { TimeSeries series = new TimeSeries("S", Year.class); assertNull(series.getDataItem(new Year(2006))); // try a null argument boolean pass = false; try { /* TimeSeriesDataItem item = */ series.getDataItem(null); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some checks for the removeAgedItems() method. */ public void testRemoveAgedItems() { TimeSeries series = new TimeSeries("Test Series", Year.class); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with one item series.add(new Year(1999), 1.0); series.setMaximumItemAge(0); this.gotSeriesChangeEvent = false; series.removeAgedItems(true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with two items series.setMaximumItemAge(10); series.add(new Year(2001), 2.0); this.gotSeriesChangeEvent = false; series.setMaximumItemAge(2); assertEquals(2, series.getItemCount()); assertEquals(0, series.getIndex(new Year(1999))); assertFalse(this.gotSeriesChangeEvent); series.setMaximumItemAge(1); assertEquals(1, series.getItemCount()); assertEquals(0, series.getIndex(new Year(2001))); assertTrue(this.gotSeriesChangeEvent); } /** * Some checks for the removeAgedItems(long, boolean) method. */ public void testRemoveAgedItems2() { long y2006 = 1157087372534L; // milliseconds somewhere in 2006 TimeSeries series = new TimeSeries("Test Series", Year.class); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test a series with 1 item series.add(new Year(2004), 1.0); series.setMaximumItemAge(1); this.gotSeriesChangeEvent = false; series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); // test a series with two items series.setMaximumItemAge(2); series.add(new Year(2003), 1.0); series.add(new Year(2005), 2.0); assertEquals(2, series.getItemCount()); this.gotSeriesChangeEvent = false; assertEquals(2, series.getItemCount()); series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(2, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(1, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); } /** * Some simple checks for the hashCode() method. */ public void testHashCode() { TimeSeries s1 = new TimeSeries("Test"); TimeSeries s2 = new TimeSeries("Test"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(1, 1, 2007), 500.0); s2.add(new Day(1, 1, 2007), 500.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(2, 1, 2007), null); s2.add(new Day(2, 1, 2007), null); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(5, 1, 2007), 111.0); s2.add(new Day(5, 1, 2007), 111.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(9, 1, 2007), 1.0); s2.add(new Day(9, 1, 2007), 1.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); } }
public static void main(string args[]); { int=a getch(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Model; /** * * @author Leonardo */ public class telaLogin { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } }
package nxt; import nxt.http.API; import nxt.peer.Peers; import nxt.user.Users; import nxt.util.Logger; import nxt.util.ThreadPool; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; public final class Nxt { public static final String VERSION = "1.2.0"; public static final String APPLICATION = "NRS"; private static final Properties defaultProperties = new Properties(); static { System.out.println("Initializing Nxt server version " + Nxt.VERSION); try (InputStream is = ClassLoader.getSystemResourceAsStream("nxt-default.properties")) { if (is != null) { Nxt.defaultProperties.load(is); } else { String configFile = System.getProperty("nxt-default.properties"); if (configFile != null) { try (InputStream fis = new FileInputStream(configFile)) { Nxt.defaultProperties.load(fis); } catch (IOException e) { throw new RuntimeException("Error loading nxt-default.properties from " + configFile); } } else { throw new RuntimeException("nxt-default.properties not in classpath and system property nxt-default.properties not defined either"); } } } catch (IOException e) { throw new RuntimeException("Error loading nxt-default.properties", e); } } private static final Properties properties = new Properties(defaultProperties); static { try (InputStream is = ClassLoader.getSystemResourceAsStream("nxt.properties")) { if (is != null) { Nxt.properties.load(is); } // ignore if missing } catch (IOException e) { throw new RuntimeException("Error loading nxt.properties", e); } } public static int getIntProperty(String name) { try { int result = Integer.parseInt(properties.getProperty(name)); Logger.logMessage(name + " = \"" + result + "\""); return result; } catch (NumberFormatException e) { Logger.logMessage(name + " not defined, assuming 0"); return 0; } } public static String getStringProperty(String name) { return getStringProperty(name, null); } public static String getStringProperty(String name, String defaultValue) { String value = properties.getProperty(name); if (value != null && ! "".equals(value)) { Logger.logMessage(name + " = \"" + value + "\""); return value; } else { Logger.logMessage(name + " not defined"); return defaultValue; } } public static List<String> getStringListProperty(String name) { String value = getStringProperty(name); if (value == null || value.length() == 0) { return Collections.emptyList(); } List<String> result = new ArrayList<>(); for (String s : value.split(";")) { s = s.trim(); if (s.length() > 0) { result.add(s); } } return result; } public static Boolean getBooleanProperty(String name) { String value = properties.getProperty(name); if (Boolean.TRUE.toString().equals(value)) { Logger.logMessage(name + " = \"true\""); return true; } else if (Boolean.FALSE.toString().equals(value)) { Logger.logMessage(name + " = \"false\""); return false; } Logger.logMessage(name + " not defined, assuming false"); return false; } public static Blockchain getBlockchain() { return BlockchainImpl.getInstance(); } public static BlockchainProcessor getBlockchainProcessor() { return BlockchainProcessorImpl.getInstance(); } public static TransactionProcessor getTransactionProcessor() { return TransactionProcessorImpl.getInstance(); } public static void main(String[] args) { if (! Constants.isTestnet) { Logger.logMessage("This release is for testnet only, exiting!"); System.exit(1); } Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { Nxt.shutdown(); } })); init(); } public static void init(Properties customProperties) { properties.putAll(customProperties); init(); } public static void init() { Init.init(); } public static void shutdown() { API.shutdown(); Users.shutdown(); Peers.shutdown(); TransactionProcessorImpl.getInstance().shutdown(); ThreadPool.shutdown(); Db.shutdown(); Logger.logMessage("Nxt server " + VERSION + " stopped."); Logger.shutdown(); } private static class Init { static { long startTime = System.currentTimeMillis(); Logger.init(); Db.init(); BlockchainProcessorImpl.getInstance(); TransactionProcessorImpl.getInstance(); Peers.init(); Generator.init(); API.init(); Users.init(); DebugTrace.init(); ThreadPool.start(); long currentTime = System.currentTimeMillis(); Logger.logDebugMessage("Initialization took " + (currentTime - startTime) / 1000 + " seconds"); Logger.logMessage("Nxt server " + VERSION + " started successfully."); if (Constants.isTestnet) { Logger.logMessage("RUNNING ON TESTNET - DO NOT USE REAL ACCOUNTS!"); } } private static void init() {} private Init() {} // never } private Nxt() {} // never }
import java.util.*; import java.io.*; import java.lang.annotation.*; import org.junit.*; import org.junit.rules.*; import org.junit.runner.*; import org.junit.runners.model.*; import org.json.simple.*; import org.json.simple.parser.*; import java.lang.reflect.*; import asp.*; import tester.*; @Inherited @Target(java.lang.annotation.ElementType.TYPE) @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface Exercises { Ex[] value(); } @Inherited @Target(java.lang.annotation.ElementType.TYPE) @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface Ex { String exID(); double points(); String comment() default "<n.a.>"; } @Inherited @Target(java.lang.annotation.ElementType.TYPE) @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface Forbidden { String[] value(); } @Inherited @Target(java.lang.annotation.ElementType.TYPE) @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface NotForbidden { String[] value(); } @Inherited @Target(java.lang.annotation.ElementType.METHOD) @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface Bonus { String exID(); double bonus(); String comment() default "<n.a.>"; } @Inherited @Target(java.lang.annotation.ElementType.METHOD) @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface Malus { String exID(); double malus(); String comment() default "<n.a.>"; } @Inherited @Target(java.lang.annotation.ElementType.METHOD) @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface SecretCase { } final class PointsLogger extends JUnitWithPoints.PointsLogger { } final class PointsSummary extends JUnitWithPoints.PointsSummary { } public abstract class JUnitWithPoints { @Rule public final PointsLogger pointsLogger = new PointsLogger(); @ClassRule public final static PointsSummary pointsSummary = new PointsSummary(); private static final HashMap<String, Ex> exerciseHashMap = new HashMap<>(); private static final HashMap<String, List<ReportEntry>> reportHashMap = new HashMap<>(); private static long timeoutSum = 0; static { Locale.setDefault(Locale.US); } private static String getShortDisplayName(Description d) { String orig = d.getDisplayName(); int ix = orig.indexOf('('); if (ix == -1) return orig; return orig.substring(0, ix); } private static final class ReportEntry { Description description; Bonus bonus; Malus malus; Throwable throwable; private ReportEntry(Description description, Bonus bonus, Malus malus, Throwable throwable) { this.description = description; this.bonus = bonus; this.malus = malus; this.throwable = throwable; } private String getStackTrace() { if (throwable == null || throwable instanceof AssertionError) return ""; StackTraceElement st[] = throwable.getStackTrace(); if (st.length == 0) return ""; StackTraceElement ste = st[0]; // TODO: maybe search for student code here return ": " + ste.getClassName() + "." + ste.getMethodName() + "(line " + ste.getLineNumber() + ")"; } final String format(double bonusDeclaredPerExercise, double pointsDeclaredPerExercise, JSONArray tests) { String result = ""; JSONObject jsontest = new JSONObject(); jsontest.put("id", getShortDisplayName(description)); if (bonus != null && malus != null) { if (throwable != null) { result += String.format(" %1$+6.2f", -(pointsDeclaredPerExercise * Math.abs(malus.malus()) / bonusDeclaredPerExercise)); jsontest.put("success", (Boolean) (false)); jsontest.put("score", ((Double)(-(pointsDeclaredPerExercise * Math.abs(malus.malus()) / bonusDeclaredPerExercise))).toString()); result += " | "; if (malus.comment().equals("<n.a.>")) { jsontest.put("desc", getShortDisplayName(description)); result += getShortDisplayName(description); } else { jsontest.put("desc", malus.comment()); result += malus.comment(); } } else { result += String.format(" %1$+6.2f", (pointsDeclaredPerExercise * Math.abs(bonus.bonus()) / bonusDeclaredPerExercise)); jsontest.put("success", (Boolean) (true)); jsontest.put("score", ((Double)(pointsDeclaredPerExercise * Math.abs(bonus.bonus()) / bonusDeclaredPerExercise)).toString()); result += " | "; if (bonus.comment().equals("<n.a.>")) { jsontest.put("desc", getShortDisplayName(description)); result += getShortDisplayName(description); } else { jsontest.put("desc", bonus.comment()); result += bonus.comment(); } } if (throwable != null) { result += " | " + throwable.getClass().getSimpleName() + "(" + throwable.getLocalizedMessage() + ")"; result += getStackTrace(); jsontest.put("error", throwable.getClass().getSimpleName() + "(" + ((throwable.getLocalizedMessage() != null) ? throwable.getLocalizedMessage() : "") + ")" + getStackTrace()); } tests.add(jsontest); return result; } if (bonus != null) { if (throwable != null) { result += String.format(" %1$6.2f", 0.0); jsontest.put("success", (Boolean) (false)); jsontest.put("score", "0.0"); } else { result += String.format(" %1$+6.2f", (pointsDeclaredPerExercise * Math.abs(bonus.bonus()) / bonusDeclaredPerExercise)); jsontest.put("success", (Boolean) (true)); jsontest.put("score", ((Double)(pointsDeclaredPerExercise * Math.abs(bonus.bonus()) / bonusDeclaredPerExercise)).toString()); } result += " | "; if (bonus.comment().equals("<n.a.>")) { jsontest.put("desc", getShortDisplayName(description)); result += getShortDisplayName(description); } else { jsontest.put("desc", bonus.comment()); result += bonus.comment(); } if (throwable != null) { result += " | " + throwable.getClass().getSimpleName() + "(" + throwable.getLocalizedMessage() + ")"; result += getStackTrace(); jsontest.put("error", throwable.getClass().getSimpleName() + "(" + ((throwable.getLocalizedMessage() != null) ? throwable.getLocalizedMessage() : "") + ")" + getStackTrace()); } tests.add(jsontest); return result; } if (malus != null) { if (throwable != null) { result += String.format(" %1$+6.2f", -(pointsDeclaredPerExercise * Math.abs(malus.malus()) / bonusDeclaredPerExercise)); jsontest.put("success", (Boolean) (false)); jsontest.put("score", ((Double)(-(pointsDeclaredPerExercise * Math.abs(malus.malus()) / bonusDeclaredPerExercise))).toString()); } else { result += String.format(" %1$6.2f", 0.0); jsontest.put("success", (Boolean) (true)); jsontest.put("score", "0.0"); } result += " | "; if (malus.comment().equals("<n.a.>")) { jsontest.put("desc", getShortDisplayName(description)); result += getShortDisplayName(description); } else { jsontest.put("desc", malus.comment()); result += malus.comment(); } if (throwable != null) { result += " | " + throwable.getClass().getSimpleName() + "(" + throwable.getLocalizedMessage() + ")"; result += getStackTrace(); jsontest.put("error", throwable.getClass().getSimpleName() + "(" + ((throwable.getLocalizedMessage() != null) ? throwable.getLocalizedMessage() : "") + ")" + getStackTrace()); } tests.add(jsontest); return result; } return result; } } private static final class ReportEntryComparator implements Comparator<ReportEntry> { public int compare(ReportEntry r1, ReportEntry r2) { if (r1 == null && r2 == null) return 0; if (r1 == null) return -1; if (r2 == null) return 1; boolean t1 = r1.throwable == null; boolean t2 = r2.throwable == null; if (true || t1 == t2) return r1.description.getDisplayName().compareTo(r2.description.getDisplayName()); if (t1) return +1; return -1; } } protected static class PointsLogger extends TestWatcher { private PrintStream saveOut; private PrintStream saveErr; @Override public final Statement apply(Statement base, Description description) { String doReplace = System.getProperty("replace"); if ((doReplace != null && !doReplace.equals(""))) { String ncln = ReadReplace.getCanonicalReplacement(description); if (!doReplace.equals(ncln)) { base = new MyStatement(); } } return super.apply(base, description); } @Override protected void starting(Description description) { try { Test testAnnotation = description.getAnnotation(Test.class); if (testAnnotation.timeout() == 0) { throw new AnnotationFormatError("WARNING - found test case without TIMEOUT in @Test annotation: [" + description.getDisplayName() + "]"); } timeoutSum += testAnnotation.timeout(); saveOut = System.out; saveErr = System.err; /* System.setOut(new PrintStream(new OutputStream() { public void write(int i) { } })); System.setErr(new PrintStream(new OutputStream() { public void write(int i) { } })); */ } catch (Exception e) { throw new AnnotationFormatError(e.getMessage()); } } @Override protected final void failed(Throwable throwable, Description description) { System.setOut(saveOut); System.setErr(saveErr); Bonus bonusAnnotation = description.getAnnotation(Bonus.class); Malus malusAnnotation = description.getAnnotation(Malus.class); if (bonusAnnotation == null && malusAnnotation == null) { throw new AnnotationFormatError("WARNING - found test case without BONUS or MALUS annotation: [" + description.getDisplayName() + "]"); } else if (bonusAnnotation != null && bonusAnnotation.exID().trim().length() == 0) { throw new AnnotationFormatError("WARNING - found test case with empty exercise id in BONUS annotation: [" + description.getDisplayName() + "]"); } else if (bonusAnnotation != null && !exerciseHashMap.containsKey(bonusAnnotation.exID())) { throw new AnnotationFormatError("WARNING - found test case with non-declared exercise id in BONUS annotation: [" + description.getDisplayName() + "]"); } else if (bonusAnnotation != null && bonusAnnotation.bonus() == 0) { throw new AnnotationFormatError("WARNING - found test case with illegal bonus value in BONUS annotation: [" + description.getDisplayName() + "]"); } else if (malusAnnotation != null && malusAnnotation.exID().trim().length() == 0) { throw new AnnotationFormatError("WARNING - found test case with empty exercise id in MALUS annotation: [" + description.getDisplayName() + "]"); } else if (malusAnnotation != null && !exerciseHashMap.containsKey(malusAnnotation.exID())) { throw new AnnotationFormatError("WARNING - found test case with non-declared exercise id in MALUS annotation: [" + description.getDisplayName() + "]"); } else if (malusAnnotation != null && malusAnnotation.malus() == 0) { throw new AnnotationFormatError("WARNING - found test case with illegal malus value in MALUS annotation: [" + description.getDisplayName() + "]"); } else { String exID = null; if (bonusAnnotation != null && malusAnnotation != null) { if (!bonusAnnotation.exID().equals(malusAnnotation.exID())){ throw new AnnotationFormatError("WARNING - found test case with different exercise id in MALUS/BONUS annotations: [" + description.getDisplayName() + "]"); } } if (bonusAnnotation != null) { exID = bonusAnnotation.exID(); } if (malusAnnotation != null) { exID = malusAnnotation.exID(); } if (!reportHashMap.containsKey(exID)) { reportHashMap.put(exID, new ArrayList<ReportEntry>()); } reportHashMap.get(exID).add(new ReportEntry(description, bonusAnnotation, malusAnnotation, throwable)); } } @Override protected final void succeeded(Description description) { failed(null, description); } } protected static class PointsSummary extends ExternalResource { @Override public final Statement apply(Statement base, Description description) { reportHashMap.clear(); exerciseHashMap.clear(); Exercises exercisesAnnotation = description.getAnnotation(Exercises.class); if (exercisesAnnotation == null || exercisesAnnotation.value().length == 0) { throw new AnnotationFormatError("WARNING - found test set without exercise points declaration: [" + description.getDisplayName() + "]"); } for (Ex exercise : exercisesAnnotation.value()) { if (exercise.exID().trim().length() == 0) { throw new AnnotationFormatError("WARNING - found exercise points declaration with empty exercise name and following points: [" + exercise.points() + "]"); } else if (exercise.points() == 0) { throw new AnnotationFormatError("WARNING - found exercise points declaration with illegal points value: [" + exercise.exID() + "]"); } else if (exerciseHashMap.containsKey(exercise.exID())) { throw new AnnotationFormatError("WARNING - found exercise points declaration with duplicate exercise: [" + exercise.exID() + "]"); } exerciseHashMap.put(exercise.exID(), exercise); } return super.apply(base, description); } @Override protected final void after() { if (timeoutSum > 60_000) { throw new AnnotationFormatError("WARNING - total timeout sum is too high for \"Tobis judge hosts\": [" + timeoutSum + "ms]"); } for (String exerciseId : exerciseHashMap.keySet()) { if (!reportHashMap.containsKey(exerciseId)) { String doReplace = System.getProperty("replace"); if (doReplace == null || doReplace.equals("")) { throw new AnnotationFormatError("WARNING - found exercise points declaration for exercise without test case: [" + exerciseId + "]"); } } } String[] exerciseIds = reportHashMap.keySet().toArray(new String[0]); Arrays.sort(exerciseIds); String summary = ""; HashMap<String, List<JSONObject>> previousDeductions = new HashMap<>(); JSONObject jsonsummary = new JSONObject(); JSONArray jsonexercises = new JSONArray(); double pointsAchievedTotal = 0; String tmpstr = System.getProperty("MustUseDeductionJSON"); // get deducted points from json environment variable if(tmpstr != null && tmpstr.equals("yes")) { try { try { BufferedReader br = new BufferedReader(new FileReader("checkMustUse.report")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append('\n'); line = br.readLine(); } tmpstr = sb.toString(); } catch (Exception e) { System.err.println("Something with Jakobs JSON went horribly wrong."); } JSONObject tmp = (JSONObject) new JSONParser().parse(tmpstr); if(tmp.containsKey("deductions")) { JSONArray a = (JSONArray) tmp.get("deductions"); for(Object oo : a) { JSONObject jo = (JSONObject) oo; if(jo.containsKey("exid")) { String id = (String) jo.get("exid"); if(!previousDeductions.containsKey(id)) previousDeductions.put(id, new ArrayList<JSONObject>()); previousDeductions.get(id).add(jo); } } } } catch(ParseException | ClassCastException e) { // do nothing } } for (String exerciseId : exerciseIds) { double bonusDeclaredPerExercise, bonusAchievedPerExercise, pointsDeclaredPerExercise, pointsAchievedPerExercise; JSONObject jsonexercise = new JSONObject(); List<JSONObject> prevDeductOnThisExercise = previousDeductions.get(exerciseId); if (summary.length() > 0) { summary += "\n"; } Ex exercise = exerciseHashMap.get(exerciseId); List<ReportEntry> reportPerExercise = reportHashMap.get(exerciseId); Collections.sort(reportPerExercise, new ReportEntryComparator()); bonusDeclaredPerExercise = 0; for (ReportEntry reportEntry : reportPerExercise) { if (reportEntry.bonus != null) { bonusDeclaredPerExercise += Math.abs(reportEntry.bonus.bonus()); } } String report = ""; pointsDeclaredPerExercise = exercise.points(); bonusAchievedPerExercise = 0; JSONArray jsontests = new JSONArray(); for (ReportEntry reportEntry : reportPerExercise) { Bonus bonus = reportEntry.bonus; Malus malus = reportEntry.malus; Throwable throwable = reportEntry.throwable; report += reportEntry.format(bonusDeclaredPerExercise, pointsDeclaredPerExercise, jsontests) + "\n"; if (bonus != null && throwable == null) { bonusAchievedPerExercise += Math.abs(bonus.bonus()); } if (malus != null && throwable != null) { bonusAchievedPerExercise -= Math.abs(malus.malus()); } } if(prevDeductOnThisExercise != null) { for (JSONObject jo : prevDeductOnThisExercise) { jsontests.add(jo); } } jsonexercise.put("tests", jsontests); bonusAchievedPerExercise = Math.min(bonusDeclaredPerExercise, Math.max(0, bonusAchievedPerExercise)); pointsAchievedPerExercise = Math.ceil(pointsDeclaredPerExercise * 2 * bonusAchievedPerExercise / bonusDeclaredPerExercise) / 2; summary += exercise.exID() + String.format(" (%1$.1f points):", pointsAchievedPerExercise) + "\n"; summary += report; pointsAchievedTotal += pointsAchievedPerExercise; jsonexercise.put("possiblePts", ((Double) exercise.points()).toString()); jsonexercise.put("name", exercise.exID()); jsonexercise.put("score", String.format("%1$.1f", pointsAchievedPerExercise)); jsonexercises.add(jsonexercise); } jsonsummary.put("exercises", jsonexercises); summary = "Score: " + String.format("%1$.1f", pointsAchievedTotal) + "\n\n" + summary; jsonsummary.put("score", String.format("%1$.1f", pointsAchievedTotal)); if (System.getProperty("json") != null && System.getProperty("json").equals("yes")) { System.err.println(jsonsummary); } else { try { try (FileWriter fileWriter = new FileWriter(new File(System.getProperty("user.dir"), "autocomment.txt"))) { fileWriter.write(summary); } } catch (Throwable t) { System.err.println(summary); } } } } } class MyStatement extends Statement { public void evaluate() { Assert.fail("this test case is not executed at all; ignoring it would make the point proportions incorrect -> FAIL!"); } }
/* * Gregory Pellegrin * pellegrin.gregory.work@gmail.com */ /* * TODO * * Refactoring * Multijoueurs * Collisions * Objectifs annexes * Map * IA * Site Web * Son */ package Game; import Entity.Ennemi; import Entity.Entity; import Entity.Player; import Ennemi.MotherShip; import Ennemi.BasicShip; import Ennemi.SpeedShip; import Ennemi.SuperMotherShip; import Ennemi.SuperSpeedShip; import Entity.Story; import Util.Clock; import java.awt.BorderLayout; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.swing.JFrame; public class Game extends JFrame { public Story story; private static final int GAME_MODE_MAX = 3; private static final int FRAMES_PER_SECOND = 60; private static final long FRAME_TIME = (long) (1000000000.0 / FRAMES_PER_SECOND); private static final int DISPLAY_LEVEL_LIMIT = 60; private static final int DEATH_COOLDOWN_LIMIT = 200; private static final int RESPAWN_COOLDOWN_LIMIT = 100; private static final int INVULN_COOLDOWN_LIMIT = 0; private static final int RESET_COOLDOWN_LIMIT = 120; private final KeyAdapter menuListener; private final KeyAdapter soloModeListener; private final MenuPanel menu; private final WorldPanel world; private List <Entity> entities; private List <Entity> pendingEntities; private Clock logicTimer; private Player player; private boolean isGameModeChoose; private boolean isGameOver; private boolean isShowingLevel; private boolean restartGame; private int gameMode; private int deathCooldown; private int restartCooldown; private int score; private int lives; private int level; private int starSpeed; private Game () { super ("Asteroids"); this.menu = new MenuPanel (this); this.world = new WorldPanel (this); this.menuListener = new KeyAdapter () { @Override public void keyPressed (KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: changeGameModeUp(); break; case KeyEvent.VK_DOWN: changeGameModeDown(); break; case KeyEvent.VK_SPACE: gameModeIsChoose(); break; case KeyEvent.VK_ENTER: gameModeIsChoose(); break; } } }; this.soloModeListener = new KeyAdapter () { @Override public void keyPressed (KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_Z: if (! checkForRestart()) player.setMove(true); break; case KeyEvent.VK_D: if (! checkForRestart()) player.setRotateRight(true); break; case KeyEvent.VK_Q: if (! checkForRestart()) player.setRotateLeft(true); break; case KeyEvent.VK_O: if (! checkForRestart()) player.setSuperSpeed(true); break; case KeyEvent.VK_SPACE: if (! checkForRestart()) player.setFiring(true); if (isShowingLevel) isShowingLevel = false; break; case KeyEvent.VK_ENTER: isShowingLevel = false; break; case KeyEvent.VK_P: if (! checkForRestart()) logicTimer.setPaused(! logicTimer.isPaused()); break; case KeyEvent.VK_ESCAPE: restart(); default: checkForRestart(); break; } } @Override public void keyReleased (KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_Z: player.setMove(false); break; case KeyEvent.VK_D: player.setRotateRight(false); break; case KeyEvent.VK_Q: player.setRotateLeft(false); break; case KeyEvent.VK_O: player.setSuperSpeed(false); break; case KeyEvent.VK_SPACE: player.setFiring(false); break; } } }; this.story = new Story (); this.setLayout(new BorderLayout ()); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setResizable(false); this.add(this.menu, BorderLayout.CENTER); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); } public List <Entity> getEntities () { return this.entities; } public Player getPlayer () { return this.player; } public boolean isGameOver () { return this.isGameOver; } public int getGameMode () { return this.gameMode; } public int getScore () { return this.score; } public int getLives () { return this.lives; } public int getLevel () { return this.level; } public int getStarSpeed () { return this.starSpeed; } public boolean isPaused () { return this.logicTimer.isPaused(); } public boolean isPlayerInvulnerable () { return (this.deathCooldown > Game.INVULN_COOLDOWN_LIMIT); } public boolean canDrawPlayer () { return (this.deathCooldown <= Game.RESPAWN_COOLDOWN_LIMIT); } public boolean isShowingLevel () { return this.isShowingLevel; } private boolean areEnemiesDead () { for (Entity e : this.entities) if (e.getClass().getSuperclass() == Ennemi.class) return false; return true; } private boolean checkForRestart () { boolean restart = (this.isGameOver && (this.restartCooldown <= 0)); if (restart) this.restartGame = true; return restart; } private void restart () { this.restartGame = true; this.isGameOver = true; } public void addScore (int score) { this.score = this.score + score; } public void killPlayer () { this.lives if (this.lives == 0) { this.isGameOver = true; this.restartCooldown = Game.RESET_COOLDOWN_LIMIT; this.deathCooldown = Integer.MAX_VALUE; } else this.deathCooldown = Game.DEATH_COOLDOWN_LIMIT; this.player.setFiringEnabled(false); } public void registerEntity (Entity entity) { this.pendingEntities.add(entity); } private void resetEntityLists () { this.pendingEntities.clear(); this.entities.clear(); this.entities.add(this.player); } private void removeKeyListener () { this.removeKeyListener(this.menuListener); this.removeKeyListener(this.soloModeListener); } private void changeGameModeUp () { if (this.gameMode > 0) this.gameMode } private void changeGameModeDown () { if (this.gameMode < (Game.GAME_MODE_MAX - 1)) this.gameMode++; } private void gameModeIsChoose () { this.isGameModeChoose = true; } private void resetMenu () { this.isGameModeChoose = false; this.gameMode = 0; this.starSpeed = 1; this.resetEntityLists(); this.removeKeyListener(); this.remove(this.world); this.add(this.menu, BorderLayout.CENTER); this.revalidate(); this.addKeyListener(this.menuListener); } private void resetGame () { this.score = 0; this.level = 0; this.lives = 3; this.deathCooldown = 0; this.isGameOver = false; this.restartGame = false; this.starSpeed = 1; this.resetEntityLists(); this.removeKeyListener(); this.remove(this.menu); this.add(this.world, BorderLayout.CENTER); this.revalidate(); this.addKeyListener(this.soloModeListener); } private void startMenu () { this.entities = new LinkedList <> (); this.pendingEntities = new ArrayList <> (); this.resetMenu(); this.logicTimer = new Clock (Game.FRAMES_PER_SECOND); while (! this.isGameModeChoose) { long start = System.nanoTime(); this.logicTimer.update(); this.menu.repaint(); long delta = Game.FRAME_TIME - (System.nanoTime() - start); if (delta > 0) try { Thread.sleep(delta / 1000000L, (int) delta % 1000000); } catch (Exception e) { System.out.println(e.getMessage()); } } } private void startGame () { this.entities = new LinkedList <> (); this.pendingEntities = new ArrayList <> (); this.player = new Player (); this.resetGame(); this.logicTimer = new Clock (Game.FRAMES_PER_SECOND); while (! this.isGameOver || ! this.restartGame) { long start = System.nanoTime(); this.logicTimer.update(); for (int i = 0; i < 5 && this.logicTimer.hasElapsedCycle(); i++) this.updateGame(); this.world.repaint(); long delta = Game.FRAME_TIME - (System.nanoTime() - start); if (delta > 0) try { Thread.sleep(delta / 1000000L, (int) delta % 1000000); } catch (Exception e) { System.out.println(e.getMessage()); } } } private void updateGame () { this.entities.addAll(this.pendingEntities); this.pendingEntities.clear(); if (this.restartCooldown > 0) this.restartCooldown if (! this.isGameOver && this.areEnemiesDead()) { this.level++; this.isShowingLevel = true; this.resetEntityLists(); this.player.reset(); this.player.setFiringEnabled(true); if (this.getLevel() <= 2) { this.isShowingLevel = true; this.starSpeed = 1; for (int i = 0; i < 4 * this.getLevel(); i++) this.registerEntity(new BasicShip (50 + i * 50, 100, Ennemi.START_LEFT)); for (int i = 0; i < 2 * this.getLevel(); i++) this.registerEntity(new SpeedShip (50 + i * 50, 200, Ennemi.START_LEFT)); for (int i = 0; i < 2 * this.getLevel(); i++) this.registerEntity(new SuperSpeedShip (50 + i * 50, 300, Ennemi.START_LEFT)); for (int i = 0; i < 1 * this.getLevel(); i++) this.registerEntity(new MotherShip (50 + i * 50, 400, Ennemi.START_LEFT)); for (int i = 0; i < 1 * this.getLevel(); i++) this.registerEntity(new SuperMotherShip (300 + i * 50, 200, Ennemi.START_LEFT)); } if (this.getLevel() == 3) { this.isShowingLevel = true; this.starSpeed = 2; for (int i = 0; i < 4 * this.getLevel(); i++) this.registerEntity(new BasicShip (50 + i * 50, 100, Ennemi.START_LEFT)); } } if (this.deathCooldown > 0) { this.deathCooldown switch (this.deathCooldown) { case Game.RESPAWN_COOLDOWN_LIMIT: this.player.reset(); this.player.setFiringEnabled(false); break; case Game.INVULN_COOLDOWN_LIMIT: this.player.setFiringEnabled(true); break; } } if (! this.isShowingLevel()) { for (Entity entity : this.entities) entity.update(this); for (int i = 0; i < this.entities.size(); i++) { Entity a = this.entities.get(i); for (int j = i + 1; j < this.entities.size(); j++) { Entity b = this.entities.get(j); if (i != j && a.checkCollision(b) && ((a != this.player && b != this.player) || this.deathCooldown <= Game.INVULN_COOLDOWN_LIMIT)) { a.checkCollision(this, b); b.checkCollision(this, a); } } } Iterator <Entity> iter = this.entities.iterator(); while (iter.hasNext()) if (iter.next().needsRemoval()) iter.remove(); } } public static void main (String [] args) { Game game = new Game(); while (true) { game.startMenu(); game.startGame(); } } }
package org.dazeend.harmonium.screens; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.dazeend.harmonium.Harmonium; import org.dazeend.harmonium.music.Album; import org.dazeend.harmonium.music.AlbumReadable; import org.dazeend.harmonium.music.Disc; import org.dazeend.harmonium.music.Playable; import org.dazeend.harmonium.music.PlaylistEligible; import com.tivo.hme.bananas.BView; /** * @author Charles Perry (harmonium@DazeEnd.org) * */ public class TrackScreen extends HAlbumInfoListScreen { private String screenTitle; private Playable playableTrack; private PlaylistEligible trackParent; private final String playTrackString = "Play This Track Now"; private final String playOnlyTrackString = "Play Only This Track Now"; private final String addTrackToPlaylistString = "Add Track to Playlist"; private final String playParentAlbumString = "Play Album Starting With This Track"; private final String playParentPlaylistString = "Play Playlist Starting With This Track"; private final String playParentDiscString = "Play Disc Starting With This Track"; private final String enqueueTrackNext = "Play This Track Next"; private final String enqueueTrackEnd = "Add Track to \"Now Playing\" Playlist"; private HList list; public TrackScreen(Harmonium app, final Playable thisTrack) { this(app, thisTrack, null); } public TrackScreen(Harmonium app, final Playable thisTrack, final PlaylistEligible trackParent) { super( app, (AlbumReadable) thisTrack, thisTrack.toString() ); Vector<String> listCommands = new Vector<String>(5); this.screenTitle = thisTrack.toString(); this.playableTrack = thisTrack; this.trackParent = trackParent; // Set up modified list if (this.app.getDiscJockey().isPlaying()) { // Something's playing now, so add the enqueue options. listCommands.add(this.enqueueTrackNext); listCommands.add(this.enqueueTrackEnd); } if (trackParent != null) { if (trackParent instanceof Album) listCommands.add(this.playParentAlbumString); else if (trackParent instanceof Disc) listCommands.add(this.playParentDiscString); else listCommands.add(this.playParentPlaylistString); listCommands.add(this.playOnlyTrackString); } else { listCommands.add(this.playTrackString); } listCommands.add(this.addTrackToPlaylistString); int listHeight = Math.min(5, listCommands.size()) * rowHeight; this.list = new HList( this.getNormal(), // Put list on "normal" level this.safeTitleH, // x coord. of button this.screenHeight - this.safeTitleV - listHeight, // y coord - Align with bottom of screen (screenWidth - (2 * safeTitleH)), // width of list (full screen) listHeight, // height of list this.rowHeight // height of each row ); for (String listCommand : listCommands) this.list.add(listCommand); this.setFocusDefault(this.list); } /* (non-Javadoc) * @see com.tivo.hme.bananas.BScreen#handleAction(com.tivo.hme.bananas.BView, java.lang.Object) */ @Override public boolean handleAction(BView view, Object action) { if(action.equals("right") || action.equals("select")) { String menuOption = (String)this.list.get( this.list.getFocus() ); if(menuOption.equals(this.addTrackToPlaylistString)) { this.app.push(new AddToPlaylistScreen(this.app, this.playableTrack), TRANSITION_LEFT); return true; } else { play(); return true; } } return super.handleAction(view, action); } /* (non-Javadoc) * Handles key presses from TiVo remote control. */ @Override public boolean handleKeyPress(int key, long rawcode) { this.app.checkKeyPressToResetInactivityTimer(key); switch(key) { case KEY_PLAY: play(); return true; case KEY_ENTER: this.app.play("select.snd"); this.app.push(new AddToPlaylistScreen(this.app, this.playableTrack), TRANSITION_LEFT); return true; } return super.handleKeyPress(key, rawcode); } private void play() { String menuOption = (String)this.list.get( this.list.getFocus() ); if(menuOption.equals(this.playTrackString) || menuOption.equals(this.playOnlyTrackString)) { List<PlaylistEligible> playlist = new ArrayList<PlaylistEligible>(); playlist.add( (PlaylistEligible)this.playableTrack); boolean shuffleMode = this.app.getPreferences().getTrackDefaultShuffleMode(); boolean repeatMode = this.app.getPreferences().getTrackDefaultRepeatMode(); this.app.getDiscJockey().play(playlist, shuffleMode, repeatMode); } else if (menuOption.equals(playParentAlbumString) || menuOption.equals(playParentPlaylistString) || menuOption.equals(this.playParentDiscString)) { // Ian TODO: Consider moving this logic down into DiscJockey. It's also // used in BrowseAlbumScreen. List<PlaylistEligible> playlist = new ArrayList<PlaylistEligible>(); playlist.add( this.trackParent ); boolean shuffleMode; boolean repeatMode; // Ian TODO: Should this be disc/album shuffle mode? See also comment // in BrowseAlbumScreen. shuffleMode = this.app.getPreferences().getTrackDefaultShuffleMode(); repeatMode = this.app.getPreferences().getTrackDefaultRepeatMode(); this.app.getDiscJockey().play(playlist, shuffleMode, repeatMode, playableTrack); } else if (menuOption.equals(enqueueTrackNext)) { this.app.getDiscJockey().enqueueNext(this.playableTrack); } else if (menuOption.equals(enqueueTrackEnd)) { this.app.getDiscJockey().enqueueAtEnd(this.playableTrack); } else this.app.play("bonk.snd"); } /* (non-Javadoc) * @see com.tivo.hme.sdk.HmeObject#toString() */ @Override public String toString() { return this.screenTitle; } }
package battlecode.world; import static battlecode.common.GameConstants.*; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Predicate; import com.google.common.collect.ForwardingMultimap; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; import battlecode.common.Chassis; import battlecode.common.ComponentClass; import battlecode.common.ComponentType; import battlecode.common.Direction; import battlecode.common.GameConstants; import battlecode.common.MapLocation; import battlecode.common.Message; import battlecode.common.Robot; import battlecode.common.Team; import battlecode.engine.GenericRobot; import battlecode.engine.signal.Signal; import battlecode.server.Config; import battlecode.world.signal.DeathSignal; import battlecode.world.signal.TurnOffSignal; public class InternalRobot extends InternalObject implements Robot, GenericRobot { /** * Robots that are inside a transport are considered to be at this * location, so that no one but the dropship will be able to sense them. */ public static final MapLocation VERY_FAR_AWAY = new MapLocation(-1000, -1000); private volatile double myEnergonLevel; protected volatile Direction myDirection; private volatile boolean energonChanged = true; protected volatile long controlBits; // is this used ever? protected volatile boolean hasBeenAttacked = false; private static boolean upkeepEnabled = Config.getGlobalConfig().getBoolean("bc.engine.upkeep-enabled"); /** first index is robot type, second is direction, third is x or y */ private static final Map<ComponentType, int[][][]> offsets = GameMap.computeVisibleOffsets(); /** number of bytecodes used in the most recent round */ private volatile int bytecodesUsed = 0; private List<Message> incomingMessageQueue; protected GameMap.MapMemory mapMemory; private InternalRobotBuffs buffs = new InternalRobotBuffs(this); public final Chassis chassis; private List<BaseComponent> newComponents; private volatile boolean on; private volatile boolean hasBeenOff; private volatile int cores; private volatile int platings; private volatile int regens; private volatile int weight; private volatile int invulnerableRounds; private volatile InternalRobot transporter; private Set<InternalRobot> passengers; private RobotControllerImpl rc; private Bug buggedBy; public static class ComponentSet extends ForwardingMultimap<ComponentClass, BaseComponent> { Multimap<ComponentClass, BaseComponent> backingMap = HashMultimap.create(); protected Multimap<ComponentClass, BaseComponent> delegate() { return backingMap; } public boolean add(BaseComponent c) { return put(c.componentClass(), c); } public boolean remove(BaseComponent c) { return remove(c.componentClass(), c); } public boolean contains(BaseComponent c) { return containsEntry(c.componentClass(), c); } } private ComponentSet components = new ComponentSet(); public InternalRobotBuffs getBuffs() { return buffs; } public RobotControllerImpl getRC() { return rc; } public void setRC(RobotControllerImpl rc) { this.rc = rc; } @SuppressWarnings("unchecked") public InternalRobot(GameWorld gw, Chassis chassis, MapLocation loc, Team t, boolean spawnedRobot) { super(gw, loc, chassis.level, t); myDirection = Direction.values()[gw.getRandGen().nextInt(8)]; this.chassis = chassis; myEnergonLevel = getMaxEnergon(); incomingMessageQueue = new LinkedList<Message>(); mapMemory = new GameMap.MapMemory(gw.getGameMap()); saveMapMemory(null, loc, false); controlBits = 0; newComponents = new ArrayList<BaseComponent>(); on = true; } public boolean inTransport() { return transporter != null; } @Override public InternalRobot container() { return transporter; } public boolean isOn() { return on; } public void setPower(boolean b) { if(b&&!on) { hasBeenOff = true; for(BaseComponent c : components.values()) { c.activate(POWER_WAKE_DELAY); } } on = b; } public void setBugged(Bug b) { if (buggedBy != null) { buggedBy.removeBug(); } buggedBy = b; } public boolean queryHasBeenOff() { boolean tmp = hasBeenOff; hasBeenOff = false; return tmp; } public boolean hasRoomFor(ComponentType c) { if (c == ComponentType.IRON) { for (BaseComponent bc : components.get(ComponentClass.ARMOR)) { if (bc.type == ComponentType.IRON) { return false; } } } return c.weight + weight <= chassis.weight; } public void equip(ComponentType type) { BaseComponent controller; switch (type) { case SHIELD: case HARDENED: case REGEN: case PLASMA: case PLATING: case PROCESSOR: controller = new BaseComponent(type, this); break; case SMG: case BLASTER: case RAILGUN: case HAMMER: case MEDIC: case BEAM: controller = new Weapon(type, this); break; case SATELLITE: case TELESCOPE: case SIGHT: case RADAR: case BUILDING_SENSOR: controller = new Sensor(type, this); break; case BUG: controller = new Bug(type, this); case ANTENNA: case DISH: case NETWORK: controller = new Radio(type, this); break; case RECYCLER: controller = new Miner(this); break; case CONSTRUCTOR: case FACTORY: case ARMORY: case DUMMY: controller = new Builder(type, this); break; case SMALL_MOTOR: case MEDIUM_MOTOR: case LARGE_MOTOR: case FLYING_MOTOR: case BUILDING_MOTOR: controller = new Motor(type, this); break; case JUMP: controller = new JumpCore(type, this); break; case DROPSHIP: controller = new Dropship(this); break; default: throw new RuntimeException("component " + type + " is not supported yet"); } components.add(controller); newComponents.add(controller); if (myGameWorld.getCurrentRound() >= 0) { controller.activate(EQUIP_WAKE_DELAY); } weight += type.weight; switch (type) { case PLATING: platings++; changeEnergonLevel(GameConstants.PLATING_HP_BONUS); break; case PROCESSOR: cores++; break; case REGEN: regens++; break; case DROPSHIP: passengers = new HashSet<InternalRobot>(); break; } } public void addAction(Signal s) { myGameWorld.visitSignal(s); } public Chassis getChassis() { return chassis; } /* public InternalComponent [] getComponents() { return Iterables.toArray(Iterables.transform(components.values(),Util.controllerToComponent),InternalComponent.class); } */ public ComponentType[] getComponentTypes() { return Iterables.toArray(Iterables.transform(components.values(), Util.typeOfComponent), ComponentType.class); } public BaseComponent[] getComponentControllers() { return components.values().toArray(new BaseComponent[0]); } public BaseComponent[] getNewComponentControllers() { BaseComponent[] controllers = newComponents.toArray(new BaseComponent[0]); newComponents.clear(); return controllers; } public BaseComponent[] getComponentControllers(ComponentClass cl) { return components.get(cl).toArray(new BaseComponent[0]); } public BaseComponent[] getComponentControllers(final ComponentType t) { Predicate<BaseComponent> p = new Predicate<BaseComponent>() { public boolean apply(BaseComponent c) { return c.type() == t; } }; Iterable<BaseComponent> filtered = Iterables.filter(components.get(t.componentClass), p); return Iterables.toArray(filtered, BaseComponent.class); } @Override public void processBeginningOfRound() { super.processBeginningOfRound(); buffs.processBeginningOfRound(); } public void processBeginningOfTurn() { rc.processBeginningOfTurn(); for (BaseComponent c : components.values()) { c.processBeginningOfTurn(); } if (invulnerableRounds > 0) { invulnerableRounds } if (on && !myGameWorld.spendResources(getTeam(), chassis.upkeep)) { myGameWorld.visitSignal(new TurnOffSignal(this, false)); } if(isOn()) changeEnergonLevel(regens * REGEN_AMOUNT); } @Override public void processEndOfTurn() { super.processEndOfTurn(); for (BaseComponent c : components.values()) { c.processEndOfTurn(); } } @Override public void processEndOfRound() { super.processEndOfRound(); buffs.processEndOfRound(); if (myEnergonLevel <= 0) { suicide(); } } public double getEnergonLevel() { return myEnergonLevel; } public Direction getDirection() { return myDirection; } public void activateShield() { invulnerableRounds = IRON_EFFECT_ROUNDS; } public void takeDamage(double baseAmount) { if (baseAmount < 0) { changeEnergonLevel(-baseAmount); return; } if (!isOn()) { changeEnergonLevelFromAttack(-baseAmount); return; } if (invulnerableRounds > 0) { return; } boolean haveHardened = false; double minDamage = Math.min(SHIELD_MIN_DAMAGE, baseAmount); for (BaseComponent c : components.get(ComponentClass.ARMOR)) { switch (c.type()) { case SHIELD: baseAmount -= SHIELD_DAMAGE_REDUCTION; break; case HARDENED: haveHardened = true; break; case PLASMA: if (!c.isActive()) { c.activate(); return; } break; } } if (haveHardened && baseAmount > HARDENED_MAX_DAMAGE) { changeEnergonLevelFromAttack(-HARDENED_MAX_DAMAGE); } else { changeEnergonLevelFromAttack(-Math.max(minDamage, baseAmount)); } } public void changeEnergonLevelFromAttack(double amount) { hasBeenAttacked = true; changeEnergonLevel(amount * (buffs.getDamageReceivedMultiplier() + 1)); } public void changeEnergonLevel(double amount) { myEnergonLevel += amount; if (myEnergonLevel > getMaxEnergon()) { myEnergonLevel = getMaxEnergon(); } energonChanged = true; if (myEnergonLevel <= 0) { suicide(); } } public boolean clearEnergonChanged() { if (energonChanged) { energonChanged = false; return true; } else { return false; } } public InternalRobot[] robotsOnBoard() { return passengers.toArray(new InternalRobot[0]); } public int spaceAvailable() { int space = TRANSPORT_CAPACITY; for (InternalRobot r : passengers) { space -= r.getChassis().weight; } return space; } public double getMaxEnergon() { return chassis.maxHp + platings * PLATING_HP_BONUS; } public void setDirection(Direction dir) { myDirection = dir; } public void suicide() { (new DeathSignal(this)).accept(myGameWorld); } public void enqueueIncomingMessage(Message msg) { incomingMessageQueue.add(msg); } public Message dequeueIncomingMessage() { if (incomingMessageQueue.size() > 0) { return incomingMessageQueue.remove(0); } else { return null; } // ~ return incomingMessageQueue.poll(); } public Message[] dequeueIncomingMessages() { Message[] result = incomingMessageQueue.toArray(new Message[incomingMessageQueue.size()]); incomingMessageQueue.clear(); return result; } public GameMap.MapMemory getMapMemory() { return mapMemory; } public void saveMapMemory(MapLocation oldLoc, MapLocation newLoc, boolean fringeOnly) { for (BaseComponent c : components.get(ComponentClass.SENSOR)) { saveMapMemory(newLoc,c.type()); } } public void saveMapMemory(MapLocation newLoc, ComponentType t) { if(t!=ComponentType.BUG) { int[][] myOffsets = offsets.get(t)[myDirection.ordinal()]; mapMemory.rememberLocations(newLoc, myOffsets[0], myOffsets[1]); } } public void addPassenger(InternalRobot passenger) { passengers.add(passenger); } public boolean hasPassenger(InternalRobot passenger) { return passengers.contains(passenger); } public void removePassenger(InternalRobot passenger) { passengers.remove(passenger); } public void loadOnto(InternalRobot transporter) { this.transporter = transporter; myGameWorld.notifyMovingObject(this, myLocation, null); myLocation = VERY_FAR_AWAY; } public void unloadTo(MapLocation loc) { myLocation = loc; transporter = null; myGameWorld.notifyMovingObject(this, null, myLocation); } public void setControlBits(long l) { controlBits = l; } public long getControlBits() { return controlBits; } public void setBytecodesUsed(int numBytecodes) { bytecodesUsed = numBytecodes; } public int getBytecodesUsed() { return bytecodesUsed; } public int getBytecodeLimit() { if ((!on) || inTransport()) { return 0; } return BYTECODE_LIMIT_BASE + BYTECODE_LIMIT_ADDON * cores; } public boolean hasBeenAttacked() { return hasBeenAttacked; } @Override public String toString() { return String.format("%s:%s#%d", getTeam(), chassis, getID()); } public void freeMemory() { incomingMessageQueue = null; mapMemory = null; buffs = null; components = null; newComponents = null; passengers = null; } }
package com.faveset.khttp; import java.nio.ByteBuffer; /** * Note that all implementations may be initialized statically and thus * should be stateless. */ interface StateHandler { /** * Performs a step of the state machine when reading new data from the * connection. * * @param buf holds unread data from the connection. * * @return true if the state is complete. False if more data is needed * in buf to proceed. * * @throws InvalidRequestException */ boolean handleState(NonBlockingConnection conn, ByteBuffer buf, HandlerState state) throws InvalidRequestException; }
package controller; import view.MapEditorPanel; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; public class MapEditorController implements KeyListener { private final String[] terrainTypesArray = {"Woods", "Pasture", "Rock", "Mountains", "Desert", "Sea"}; private final String[] riverConnectorNumbersArray = {"0", "1" , "2 sharp", "2 wide", "3"}; private String currentTerrainType; private String currentRiverNumber; private int hexRotation; private final int hexRotationAnglePerPress = 60; private final ArrayList<String> terrainTypesList = new ArrayList<>(Arrays.asList(terrainTypesArray)); private final ArrayList<String> riverConnectorNumbersList = new ArrayList<>(Arrays.asList(riverConnectorNumbersArray)); private Iterator<String> terrainIterator; private Iterator<String> riverIterator; private MapEditorPanel mapEditorPanel; public MapEditorController(MapEditorPanel mapEditorPanel){ terrainIterator = terrainTypesList.iterator(); riverIterator = riverConnectorNumbersList.iterator(); this.mapEditorPanel = mapEditorPanel; mapEditorPanel.setControllerAsKeyListener(this); } //cycles through terrain types with an iterator, sends the string to the correct JLabel in TileSelectionPanel public void cycleTerrain(){ if (!terrainIterator.hasNext()) { terrainIterator = terrainTypesList.iterator(); //reset iterator to element 0 } riverIterator = riverConnectorNumbersList.iterator(); //reset river iterator to start at 0 every time a new terrain is cycled to currentTerrainType = terrainIterator.next(); mapEditorPanel.setTerrainInTileSelectionText(currentTerrainType); //set JLabel in View for terrain } //cycles through river count with an iterator, sends the string to the correct JLabel in TileSelectionPanel public void cycleRiverCount(){ if (!riverIterator.hasNext()){ riverIterator = riverConnectorNumbersList.iterator(); //reset iterator to element 0 } if(!currentTerrainType.equals("Sea")){ //only set river count if non-Sea terrain currentRiverNumber = riverIterator.next(); } else{ currentRiverNumber = ""; //a sea tile has no rivers } mapEditorPanel.setRiverConnectorsInTileSelectionText(currentRiverNumber); } public void cycleOrientation(){ hexRotation = (hexRotation + hexRotationAnglePerPress) % 360; //rotate 60 degress and reset at 360 } @Override public void keyTyped(KeyEvent e) { System.out.println("key typed"); } //TODO check for the correct keypress before cycling @Override public void keyPressed(KeyEvent e) { System.out.println("key pressed"); cycleTerrain(); cycleRiverCount(); cycleOrientation(); } @Override public void keyReleased(KeyEvent e) { System.out.println("key released"); } public String getCurrentTerrainType() { return currentTerrainType; } public String getCurrentRiverNumber() { return currentRiverNumber; } public int getHexRotation() { return hexRotation; } //TODO add remaining methods from design doc }
package h2o.common; import h2o.common.exception.ExceptionUtil; import h2o.common.util.collection.CollectionUtil; import h2o.jodd.util.SystemUtil; import org.apache.commons.configuration.PropertiesConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class Mode { private static final Logger log = LoggerFactory.getLogger( Mode.class.getName() ); public static final String PROD = "PROD"; public static final String TEST = "TEST"; public static final String DEV = "DEV"; public static final String mode; public static final String name; public static final boolean prodMode; public static final boolean testMode; public static final boolean devMode; public static final boolean debugMode; private static final String[] userModeArrays; static { boolean p = false; boolean t = false; boolean d = false; boolean debug = false; String m; String userModes; try { PropertiesConfiguration config = new PropertiesConfiguration("mode.properties"); m = SystemUtil.get("H2OMode" , config.getString("mode", PROD )).trim().toUpperCase(); try { debug = SystemUtil.getBoolean("H2ODebug" , config.getBoolean("debug" , false )); } catch ( Exception e ) { } userModes = SystemUtil.get("H2OUserMode" , config.getString("userMode","")).trim().toUpperCase(); } catch (Throwable e) { m = SystemUtil.get("H2OMode").trim().toUpperCase(); if ( m == null ) { e.fillInStackTrace(); log.error("", e); throw ExceptionUtil.toRuntimeException(e); } debug = SystemUtil.getBoolean("H2ODebug" , false); userModes = SystemUtil.get("H2OUserMode","").trim().toUpperCase(); } if ( PROD.equals( m ) ) { p = true; } else if ( TEST.equals( m ) ) { t = true; } else if ( DEV.equals( m ) ) { d = true; } else { throw new IllegalArgumentException(m); } String[] uma = new String[0]; if( !"".equals(userModes) ) { List<String> ums = CollectionUtil.toList( userModes, new String[] {":",",",";"," ", "\t"} ); uma = ums.toArray( new String[ums.size()] ); } prodMode = p; devMode = d; testMode = t; debugMode = debug; userModeArrays = uma; mode = m; name = m.toLowerCase(); log.info("Mode : {}" , mode ); log.info("Debug Mode : {}" , debugMode ); log.info("User Mode : {}" , userModeArrays ); } private Mode() {} public static boolean isMode( String m ) { if(m == null) { return false; } return m.trim().toUpperCase().equals(mode); } public static boolean isDebugMode() { return debugMode; } public static boolean isUserMode( String m ) { if(m == null) { return false; } String um = m.trim().toUpperCase(); for ( String u : userModeArrays ) { if ( u.equals(um) ) { return true; } } return false; } }
package ed.lang.ruby; import java.math.BigDecimal; import java.math.BigInteger; import org.jruby.*; import org.jruby.internal.runtime.methods.JavaMethod; import org.jruby.javasupport.JavaUtil; import org.jruby.runtime.*; import org.jruby.runtime.builtin.IRubyObject; import static org.jruby.runtime.Visibility.PUBLIC; import ed.db.DBCursor; import ed.db.ObjectId; import ed.js.*; import ed.js.engine.Scope; /** * RubyJSObjectWrapper acts as a bridge between Ruby objects and Java * objects. */ public class RubyObjectWrapper extends RubyObject { static final boolean DEBUG = Boolean.getBoolean("DEBUG.RB.WRAP"); protected final Scope _scope; protected final org.jruby.Ruby _runtime; protected final Object _obj; public static IRubyObject toRuby(Scope s, org.jruby.Ruby runtime, Object obj) { return toRuby(s, runtime, obj, null, null); } public static IRubyObject toRuby(Scope s, org.jruby.Ruby runtime, Object obj, String name) { return toRuby(s, runtime, obj, name, null); } /** Given a Java object (JSObject, Number, etc.), return a Ruby object. */ public static IRubyObject toRuby(Scope s, org.jruby.Ruby runtime, Object obj, String name, RubyObjectWrapper container) { if (obj == null) return runtime.getNil(); if (obj instanceof JSString || obj instanceof ObjectId) return RubyString.newString(runtime, obj.toString()); if (obj instanceof JSFunctionWrapper) return ((JSFunctionWrapper)obj).getProc(); if (obj instanceof JSFunction) { IRubyObject methodOwner = container == null ? runtime.getTopSelf() : container; return new RubyJSFunctionWrapper(s, runtime, (JSFunction)obj, name, methodOwner.getSingletonClass()); } if (obj instanceof JSArray) return new RubyJSArrayWrapper(s, runtime, (JSArray)obj); if (obj instanceof JSMap) { JSMap jm = (JSMap)obj; RubyHash rh = new RubyHash(runtime); ThreadContext context = runtime.getCurrentContext(); for (Object key : jm.keys()) rh.op_aset(context, toRuby(s, runtime, key), toRuby(s, runtime, jm.get(key), key.toString())); return rh; // return new RubyJSHashWrapper((JSMap)obj); } if (obj instanceof DBCursor) return new RubyDBCursorWrapper(s, runtime, (DBCursor)obj); if (obj instanceof BigDecimal) return new RubyBigDecimal(runtime, (BigDecimal)obj); if (obj instanceof BigInteger) return new RubyBignum(runtime, (BigInteger)obj); if (obj instanceof JSObject) return new RubyJSObjectWrapper(s, runtime, (JSObject)obj); return JavaUtil.convertJavaToUsableRubyObject(runtime, obj); } /** Given a Ruby block, returns a JavaScript object. */ public static JSFunctionWrapper toJS(Scope scope, org.jruby.Ruby runtime, Block block) { return new JSFunctionWrapper(scope, runtime, block); } /** Given a Ruby object, returns a JavaScript object. */ public static Object toJS(final Scope scope, final org.jruby.Ruby runtime, IRubyObject r) { if (r == null) return null; if (r instanceof RubyString) return new JSString(((RubyString)r).toString()); if (r instanceof RubyObjectWrapper) return ((RubyObjectWrapper)r)._obj; if (r instanceof RubyBignum) return JavaUtil.convertRubyToJava(r, BigInteger.class); if (r instanceof RubyBigDecimal) return ((RubyBigDecimal)r).getValue(); if (r instanceof RubyNumeric) return JavaUtil.convertRubyToJava(r); if (r instanceof RubyJSArrayWrapper) return ((RubyJSArrayWrapper)r).getJSArray(); if (r instanceof RubyArray) { RubyArray ra = (RubyArray)r; int len = ra.getLength(); JSArray ja = new JSArray(len); for (int i = 0; i < len; ++i) ja.setInt(i, toJS(scope, runtime, ra.entry(i))); return ja; } // if (r instanceof RubyJSMapWrapper) // return ((RubyJSMapWrapper)r).getJSMap(); if (r instanceof RubyHash) { RubyHash rh = (RubyHash)r; final JSObjectBase jobj = new JSObjectBase(); rh.visitAll(new RubyHash.Visitor() { public void visit(final IRubyObject key, final IRubyObject value) { jobj.set(key.toString(), toJS(scope, runtime, value)); } }); return jobj; // return ((RubyJSMapWrapper)r).getJSMap(); } if (r instanceof RubyProc) return new JSFunctionWrapper(scope, runtime, ((RubyProc)r).getBlock()); return JavaUtil.convertRubyToJava(r); // punt } public static Object[] toJSFunctionArgs(Scope s, org.jruby.Ruby r, IRubyObject[] args, int offset, Block block) { boolean haveBlock = block != null && block.isGiven(); Object[] jargs = new Object[args.length - offset + (haveBlock ? 1 : 0)]; for (int i = offset; i < args.length; ++i) jargs[i-offset] = RubyObjectWrapper.toJS(s, r, args[i]); if (haveBlock) jargs[args.length-offset] = RubyObjectWrapper.toJS(s, r, block); return jargs; } RubyObjectWrapper(Scope s, org.jruby.Ruby runtime, Object obj) { super(runtime, runtime.getObject()); _scope = s; _runtime = runtime; _obj = obj; if (RubyObjectWrapper.DEBUG) System.err.println("creating RubyObjectWrapper around " + (obj == null ? "null" : ("instance of " + obj.getClass().getName()))); } public Object getObject() { return _obj; } public IRubyObject toRuby(Object obj) { return toRuby(_scope, _runtime, obj); } public IRubyObject toRuby(Object obj, String name) { return toRuby(_scope, _runtime, obj, name); } public IRubyObject toRuby(Object obj, String name, RubyObjectWrapper container) { return toRuby(_scope, _runtime, obj, name, container); } public JSFunctionWrapper toJS(Block block) { return toJS(_scope, _runtime, block); } public Object toJS(IRubyObject r) { return toJS(_scope, _runtime, r); } public Object[] toJSFunctionArgs(IRubyObject[] args) { return toJSFunctionArgs(_scope, _runtime, args, 0, null); } public Object[] toJSFunctionArgs(IRubyObject[] args, int offset) { return toJSFunctionArgs(_scope, _runtime, args, offset, null); } public Object[] toJSFunctionArgs(IRubyObject[] args, Block block) { return toJSFunctionArgs(_scope, _runtime, args, 0, block); } public Object[] toJSFunctionArgs(IRubyObject[] args, int offset, Block block) { return toJSFunctionArgs(_scope, _runtime, args, offset, block); } }
package com.akiban.admin; public class AdminKey { // Cluster configuration. Format: // name: [*]host:port // The names $admin and $mysql are reserved for configuring the addresses of the admin service and the mysql head. // All other names are chunkserver names. * is used to denote the lead chunkserver. It must be specified for // exactly one chunkserver, and never for $admin or $mysql. public static final String CONFIG_CLUSTER = "/config/cluster.properties"; // Chunkserver properties. Format specified by chunkserver public static final String CONFIG_CHUNKSERVER = "/config/server.properties"; // Logging properties. log4j format. public static final String CONFIG_LOGGING = "/config/logging.properties"; public static final String STATE_BASE = "/state"; public static final String CONFIG_BASE = "/config"; // Chunkserver status. Format: // state: up/down // lead: true/false public static final String STATE_CHUNKSERVER = "/state/%s.properties"; public static final String[] REQUIRED_KEYS = new String[]{ CONFIG_CLUSTER, CONFIG_CHUNKSERVER, CONFIG_LOGGING }; public static String[] CONFIG_KEYS = new String[]{ CONFIG_CLUSTER, CONFIG_CHUNKSERVER, CONFIG_LOGGING }; public static String stateChunkserverName(String chunkserverName) { return String.format(STATE_CHUNKSERVER, chunkserverName); } }
package com.ceph.rados; import static com.ceph.rados.Library.rados; import java.io.Closeable; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import com.ceph.rados.exceptions.RadosException; import com.sun.jna.Callback; import com.sun.jna.Pointer; import com.sun.jna.ptr.PointerByReference; public class Completion extends RadosBase implements Closeable { // Static members private static Map<Integer,Completion> completionMap = new HashMap<>(); private static int nextCompletionId = 1; // Instance members private boolean safe; private boolean complete; // Callback support private static Callback completeCallback = new Callback() { @SuppressWarnings("unused") public void callback(Pointer completionPointer, Pointer callbackContext) throws RadosException { final int completionId = (int)Pointer.nativeValue(callbackContext); Completion completion; synchronized (completionMap) { completion = completionMap.get(completionId); } // If the completion has not been closed yet, call the handler. if (completion != null) { completion.complete = true; completion.onComplete(); } } }; private static Callback safeCallback = new Callback() { @SuppressWarnings("unused") public void callback(Pointer completionPointer, Pointer callbackContext) throws RadosException { final int completionId = (int)Pointer.nativeValue(callbackContext); Completion completion; synchronized (completionMap) { completion = completionMap.get(completionId); } // If the completion has not been closed yet, call the handler. if (completion != null) { completion.safe = true; completion.onSafe(); } } }; // Instance members private Pointer pointer; private int completionId; /** * Constructs a completion to use with asynchronous operations. * <p> * The complete and safe callbacks correspond to operations being acked and committed, respectively. * The callbacks are called in order of receipt, so the safe callback may be triggered before the complete callback, and vice versa. * This is affected by journalling on the OSDs. * <p> * NOTE: Read operations only get a complete callback. * * @param notifyOnComplete If true, onComplete() is called when the operation is in memory on all replicas * @param notifyOnSafe If true, onSafe() is called when the operation is on stable storage on all replicas * @throws RadosException */ public Completion(final boolean notifyOnComplete, final boolean notifyOnSafe) throws RadosException { super(); final PointerByReference pointerByReference = new PointerByReference(); // Generate an ID for this completion. synchronized (completionMap) { completionId = nextCompletionId++; if (completionId <= 0) { completionId = 1; nextCompletionId = 2; } // If callbacks will be registered, then also record this object in the global completion map // so that it can be accessed from the callback handlers. if (notifyOnComplete || notifyOnSafe) completionMap.put(completionId, this); } // Create the completion object. if (notifyOnComplete || notifyOnSafe) { handleReturnCode(new Callable<Integer>() { @Override public Integer call() throws Exception { return rados.rados_aio_create_completion( Pointer.createConstant((long)completionId), notifyOnComplete?completeCallback:null, notifyOnSafe?safeCallback:null, pointerByReference ); } }, "Failed to create completion with callbacks" ); } else { handleReturnCode(new Callable<Integer>() { @Override public Integer call() throws Exception { return rados.rados_aio_create_completion(null, null, null, pointerByReference); } }, "Failed to create completion" ); } pointer = pointerByReference.getValue(); } /** * Block until the operation completes. This means it is in memory on all replicas. * @throws RadosException */ public void waitForComplete() throws RadosException { handleReturnCode(new Callable<Integer>() { @Override public Integer call() throws Exception { return rados.rados_aio_wait_for_complete(getPointer()); } }, "Failed to wait for AIO completion" ); } /** * Override this function to implement callback handling. If notifyOnSafe is true, this function is called when * the operation is in memory on all replicas. */ public void onComplete() { } /** * Override this function to implement callback handling. If notifyOnComplete is true, this function is called when * the operation is on stable storage on all replicas. */ public void onSafe() { } /** * Release a completion * <p> * Call this when you no longer need the completion. It may not be freed immediately if the operation is not acked and committed. */ @Override public void close() throws IOException { rados.rados_aio_release(getPointer()); if (completionId > 0) { synchronized (completionMap) { completionMap.remove(completionId); } completionId = 0; } } /** * @return True if the safe callback is enabled has occurred, else false. */ public boolean isSafe() { return safe; } /** * @return True if the complete callback is enabled has occurred, else false. */ public boolean isComplete() { return complete; } public Pointer getPointer() { return pointer; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + completionId; return result; } @Override public boolean equals(Object that) { if (this == that) return true; if (that == null) return false; if (!(that instanceof Completion)) return false; return (completionId == ((Completion)that).completionId); } }
package com.codeski.nbt; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.zip.GZIPOutputStream; import com.codeski.nbt.tags.NBT; /** * Class for writing NBT structures as NBT, JSON, or XML. */ public class NBTWriter { /** * Writes the tag specified and its children as JSON text. * * @param root * The root tag to write. * @param file * The file to write to. * @throws FileNotFoundException * If the file being written to does not exist. */ public static void writeJSON(NBT<?> root, File file) throws FileNotFoundException { new NBTWriter(root, file).writeJSON(); } /** * Writes the tag specified and its children as NBT binary data. * * @param root * The root tag to write. * @param file * The file to write to. * @throws FileNotFoundException * If the file being written to does not exist. */ public static void writeNBT(NBT<?> root, File file) throws FileNotFoundException { NBTWriter.writeNBT(root, file, true); } /** * Writes the tag specified and its children as NBT binary data. * * @param root * The root tag to write. * @param file * The file to write to. * @param compressed * Whether or not the file should be compressed. * @throws FileNotFoundException * If the file being written to does not exist. */ public static void writeNBT(NBT<?> root, File file, boolean compressed) throws FileNotFoundException { new NBTWriter(root, file).writeNBT(compressed); } /** * Writes the tag specified and its children as XML text. * * @param root * The root tag to write. * @param file * The file to write to. * @throws FileNotFoundException * If the file being written to does not exist. */ public static void writeXML(NBT<?> root, File file) throws FileNotFoundException { new NBTWriter(root, file).writeXML(); } private final File file; private final NBT<?> root; private NBTWriter(NBT<?> root, File file) throws FileNotFoundException { this.root = root; this.file = file; } private void writeJSON() { try (PrintWriter out = new PrintWriter(file)) { out.println("{ " + root.toJSON() + " }"); } catch (IOException e) { System.err.println("There was an error writing the data to JSON text."); e.printStackTrace(System.err); } } private void writeNBT(boolean compressed) { if (compressed) try (DataOutputStream out = new DataOutputStream(new GZIPOutputStream(new FileOutputStream(file)))) { out.write(root.toNBT()); } catch (IOException e) { System.err.println("There was an error writing the data to NBT binary data."); e.printStackTrace(System.err); } else try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) { out.write(root.toNBT()); } catch (IOException e) { System.err.println("There was an error writing the data to NBT binary data."); e.printStackTrace(System.err); } } private void writeXML() { try (PrintWriter out = new PrintWriter(file)) { out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + root.toXML()); } catch (IOException e) { System.err.println("There was an error writing the data to XML text."); e.printStackTrace(System.err); } } }
package com.crawljax.core; import java.util.List; import org.apache.log4j.Logger; import com.crawljax.browser.EmbeddedBrowser; import com.crawljax.core.configuration.CrawljaxConfigurationReader; import com.crawljax.core.exception.BrowserConnectionException; import com.crawljax.core.exception.CrawlPathToException; import com.crawljax.core.plugin.CrawljaxPluginsUtil; import com.crawljax.core.state.*; import com.crawljax.core.state.Eventable.EventType; import com.crawljax.forms.FormHandler; import com.crawljax.forms.FormInput; import com.crawljax.util.ElementResolver; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class that performs crawl actions. It is designed to be run inside a Thread. * * @see #run() * @author dannyroest@gmail.com (Danny Roest) * @author Stefan Lenselink <S.R.Lenselink@student.tudelft.nl> * @version $Id: Crawler.java 492 2011-06-10 21:14:44Z amesbah $ */ public class Crawler implements Runnable { private static final Logger LOGGER = Logger.getLogger(Crawler.class.getName()); private static final int ONE_SECOND = 1000; /** * The main browser window 1 to 1 relation; Every Thread will get on browser assigned in the run * function. */ private EmbeddedBrowser browser; /** * The central DataController. This is a multiple to 1 relation Every Thread shares an instance * of the same controller! All operations / fields used in the controller should be checked for * thread safety. */ private final CrawljaxController controller; /** * Depth register. */ private int depth = 0; /** * The path followed from the index to the current state. */ private final CrawlPath backTrackPath; /** * The utility which is used to extract the candidate clickables. */ private CandidateElementExtractor candidateExtractor; private boolean fired = false; /** * The name of this Crawler when not default (automatic) this will be added to the Thread name * in the thread as (name). In the {@link CrawlerExecutor#beforeExecute(Thread, Runnable)} the * name is retrieved using the {@link #toString()} function. * * @see Crawler#toString() * @see CrawlerExecutor#beforeExecute(Thread, Runnable) */ private String name = ""; /** * The sateMachine for this Crawler, keeping track of the path crawled by this Crawler. */ private final StateMachine stateMachine; private final CrawljaxConfigurationReader configurationReader; private FormHandler formHandler; /** * The object to places calls to add new Crawlers or to remove one. */ private final CrawlQueueManager crawlQueueManager; /** * Enum for describing what has happened after a {@link Crawler#clickTag(Eventable)} has been * performed. * * @see Crawler#clickTag(Eventable) */ private enum ClickResult { cloneDetected, newState, domUnChanged } /** * @param mother * the main CrawljaxController * @param exactEventPath * the event path up till this moment. * @param name * a name for this crawler (default is empty). */ public Crawler(CrawljaxController mother, List<Eventable> exactEventPath, String name) { this(mother, new CrawlPath(exactEventPath)); this.name = name; } /** * Private Crawler constructor for a 'reload' crawler. Only used internally. * * @param mother * the main CrawljaxController * @param returnPath * the path used to return to the last state, this can be a empty list * @deprecated better to use {@link #Crawler(CrawljaxController, CrawlPath)} */ @Deprecated protected Crawler(CrawljaxController mother, List<Eventable> returnPath) { this(mother, new CrawlPath(returnPath)); } /** * Private Crawler constructor for a 'reload' crawler. Only used internally. * * @param mother * the main CrawljaxController * @param returnPath * the path used to return to the last state, this can be a empty list */ protected Crawler(CrawljaxController mother, CrawlPath returnPath) { this.backTrackPath = returnPath; this.controller = mother; this.configurationReader = controller.getConfigurationReader(); this.crawlQueueManager = mother.getCrawlQueueManager(); if (controller.getSession() != null) { this.stateMachine = new StateMachine(controller.getSession().getStateFlowGraph(), controller .getSession().getInitialState(), controller.getInvariantList()); } else { /** * Reset the state machine to null, because there is no session where to load the * stateFlowGraph from. */ this.stateMachine = null; } } /** * Brings the browser to the initial state. */ public void goToInitialURL() { LOGGER.info("Loading Page " + configurationReader.getCrawlSpecificationReader().getSiteUrl()); getBrowser().goToUrl(configurationReader.getCrawlSpecificationReader().getSiteUrl()); /** * Thread safe */ controller.doBrowserWait(getBrowser()); CrawljaxPluginsUtil.runOnUrlLoadPlugins(getBrowser()); } /** * Try to fire a given event on the Browser. * * @param eventable * the eventable to fire * @return true iff the event is fired */ private boolean fireEvent(Eventable eventable) { if (eventable.getIdentification().getHow().toString().equals("xpath") && eventable.getRelatedFrame().equals("")) { /** * The path in the page to the 'clickable' (link, div, span, etc) */ String xpath = eventable.getIdentification().getValue(); /** * The type of event to execute on the 'clickable' like onClick, mouseOver, hover, etc */ EventType eventType = eventable.getEventType(); /** * Try to find a 'better' / 'quicker' xpath */ String newXPath = new ElementResolver(eventable, getBrowser()).resolve(); if (newXPath != null && !xpath.equals(newXPath)) { LOGGER.info("XPath changed from " + xpath + " to " + newXPath + " relatedFrame:" + eventable.getRelatedFrame()); eventable = new Eventable(new Identification(Identification.How.xpath, newXPath), eventType); } } if (getBrowser().fireEvent(eventable)) { /** * Let the controller execute its specified wait operation on the browser thread safe. */ controller.doBrowserWait(getBrowser()); /** * Close opened windows */ getBrowser().closeOtherWindows(); return true; // A event fired } else { /** * Execute the OnFireEventFailedPlugins with the current crawlPath with the crawlPath * removed 1 state to represent the path TO here. */ CrawljaxPluginsUtil.runOnFireEventFailedPlugins(eventable, controller.getSession() .getCurrentCrawlPath().immutableCopy(true)); return false; // no event fired } } /** * Enters the form data. First, the related input elements (if any) to the eventable are filled * in and then it tries to fill in the remaining input elements. * * @param eventable * the eventable element. */ private void handleInputElements(Eventable eventable) { List<FormInput> formInputs = eventable.getRelatedFormInputs(); for (FormInput formInput : formHandler.getFormInputs()) { if (!formInputs.contains(formInput)) { formInputs.add(formInput); } } eventable.setRelatedFormInputs(formInputs); formHandler.handleFormElements(formInputs); } /** * Reload the browser following the {@link #backTrackPath} to the given currentEvent. * * @throws CrawljaxException * if the {@link Eventable#getTargetStateVertix()} encounters an error. */ private void goBackExact() throws CrawljaxException { /** * Thread safe */ StateVertix curState = controller.getSession().getInitialState(); for (Eventable clickable : backTrackPath) { if (!controller.getElementChecker().checkCrawlCondition(getBrowser())) { return; } LOGGER.info("Backtracking by executing " + clickable.getEventType() + " on element: " + clickable); this.getStateMachine().changeState(clickable.getTargetStateVertix()); curState = clickable.getTargetStateVertix(); controller.getSession().addEventableToCrawlPath(clickable); this.handleInputElements(clickable); if (this.fireEvent(clickable)) { // TODO ali, do not increase depth if eventable is from guidedcrawling depth++; /** * Run the onRevisitStateValidator(s) */ CrawljaxPluginsUtil.runOnRevisitStatePlugins(this.controller.getSession(), curState); } if (!controller.getElementChecker().checkCrawlCondition(getBrowser())) { return; } } } /** * @param eventable * the element to execute an action on. * @return the result of the click operation * @throws CrawljaxException * an exception. */ private ClickResult clickTag(final Eventable eventable) throws CrawljaxException { // load input element values this.handleInputElements(eventable); // Guifre Ruiz: Included support for meta refresh tags if (eventable.getElement().getTag().toLowerCase().equals("meta")) { Pattern p = Pattern.compile("(\\d+);\\s+URL=(.*)"); for (Attribute e : eventable.getElement().getAttributes()) { Matcher m = p.matcher(e.getValue()); if (m.find()) { if(LOGGER.isDebugEnabled()) { LOGGER.debug("URL:" + m.group(2)); } try { //seconds*1000=ms Thread.sleep(Integer.parseInt(m.group(1)) * 1000); } catch (Exception ex) { LOGGER.error(ex); } } } } LOGGER.info("Executing " + eventable.getEventType() + " on element: " + eventable + "; State: " + this.getStateMachine().getCurrentState().getName()); if (this.fireEvent(eventable)) { StateVertix newState = new StateVertix(getBrowser().getCurrentUrl(), controller.getSession() .getStateFlowGraph().getNewStateName(), getBrowser().getDom(), this.controller.getStrippedDom(getBrowser())); if (isDomChanged(this.getStateMachine().getCurrentState(), newState)) { // Dom is changed, so data might need be filled in again controller.getSession().addEventableToCrawlPath(eventable); if (this.getStateMachine().update(eventable, newState, this.getBrowser(), this.controller.getSession())) { // Dom changed // No Clone // TODO change the interface of runGuidedCrawlingPlugins to remove the // controller.getSession().getCurrentCrawlPath() call because its from the // session now. CrawljaxPluginsUtil.runGuidedCrawlingPlugins(controller, controller .getSession(), controller.getSession().getCurrentCrawlPath(), this .getStateMachine()); return ClickResult.newState; } else { // Dom changed; Clone return ClickResult.cloneDetected; } } } // Event not fired or, Dom not changed return ClickResult.domUnChanged; } /** * Return the Exacteventpath. * * @return the exacteventpath * @deprecated use {@link CrawlSession#getCurrentCrawlPath()} */ @Deprecated public final List<Eventable> getExacteventpath() { return controller.getSession().getCurrentCrawlPath(); } /** * Have we reached the depth limit? * * @param depth * the current depth. Added as argument so this call can be moved out if desired. * @return true if the limit has been reached */ private boolean depthLimitReached(int depth) { if (this.depth >= configurationReader.getCrawlSpecificationReader().getDepth() && configurationReader.getCrawlSpecificationReader().getDepth() != 0) { LOGGER.info("DEPTH " + depth + " reached returning from rec call. Given depth: " + configurationReader.getCrawlSpecificationReader().getDepth()); return true; } else { return false; } } private void spawnThreads(StateVertix state) { Crawler c = null; do { if (c != null) { this.crawlQueueManager.addWorkToQueue(c); } c = new Crawler(this.controller, controller.getSession().getCurrentCrawlPath() .immutableCopy(true)); } while (state.registerCrawler(c)); } private ClickResult crawlAction(CandidateCrawlAction action) throws CrawljaxException { CandidateElement candidateElement = action.getCandidateElement(); EventType eventType = action.getEventType(); StateVertix orrigionalState = this.getStateMachine().getCurrentState(); if (candidateElement.allConditionsSatisfied(getBrowser())) { ClickResult clickResult = clickTag(new Eventable(candidateElement, eventType)); switch (clickResult) { case cloneDetected: fired = false; // We are in the clone state so we continue with the cloned version to search // for work. this.controller.getSession().branchCrawlPath(); spawnThreads(orrigionalState); break; case newState: fired = true; // Recurse because new state found spawnThreads(orrigionalState); break; case domUnChanged: // Dom not updated, continue with the next break; default: break; } return clickResult; } else { LOGGER.info("Conditions not satisfied for element: " + candidateElement + "; State: " + this.getStateMachine().getCurrentState().getName()); } return ClickResult.domUnChanged; } /** * Crawl through the clickables. * * @throws CrawljaxException * if an exception is thrown. */ private boolean crawl() throws CrawljaxException { if (depthLimitReached(depth)) { return true; } if (!checkConstraints()) { return false; } // Store the currentState to be able to 'back-track' later. StateVertix orrigionalState = this.getStateMachine().getCurrentState(); if (orrigionalState.searchForCandidateElements(candidateExtractor, configurationReader .getTagElements(), configurationReader.getExcludeTagElements(), configurationReader.getCrawlSpecificationReader().getClickOnce())) { // Only execute the preStateCrawlingPlugins when it's the first time LOGGER.info("Starting preStateCrawlingPlugins..."); CrawljaxPluginsUtil.runPreStateCrawlingPlugins(controller.getSession(), orrigionalState.getUnprocessedCandidateElements()); } CandidateCrawlAction action = orrigionalState.pollCandidateCrawlAction(this, crawlQueueManager); while (action != null) { if (depthLimitReached(depth)) { return true; } if (!checkConstraints()) { return false; } ClickResult result = this.crawlAction(action); orrigionalState.finishedWorking(this, action); switch (result) { case newState: return newStateDetected(orrigionalState); case cloneDetected: return true; default: break; } action = orrigionalState.pollCandidateCrawlAction(this, crawlQueueManager); } return true; } /** * A new state has been found! * * @param orrigionalState * the current state * @return true if crawling must continue false otherwise. * @throws CrawljaxException */ private boolean newStateDetected(StateVertix orrigionalState) throws CrawljaxException { /** * An event has been fired so we are one level deeper */ depth++; LOGGER.info("RECURSIVE Call crawl; Current DEPTH= " + depth); if (!this.crawl()) { // Crawling has stopped controller.terminate(false); return false; } this.getStateMachine().changeState(orrigionalState); return true; } /** * Initialize the Crawler, retrieve a Browser and go to the initial URL when no browser was * present. rewind the state machine and goBack to the state if there is exactEventPath is * specified. * * @throws InterruptedException * when the request for a browser is interrupted. */ public void init() throws InterruptedException { // Start a new CrawlPath for this Crawler controller.getSession().startNewPath(); this.browser = this.getBrowser(); if (this.browser == null) { /** * As the browser is null, request one and got to the initial URL, if the browser is * Already set the browser will be in the initial URL. */ this.browser = controller.getBrowserPool().requestBrowser(); LOGGER.info("Reloading page for navigating back"); this.goToInitialURL(); } // TODO Stefan ideally this should be placed in the constructor this.formHandler = new FormHandler(getBrowser(), configurationReader.getInputSpecification(), configurationReader.getCrawlSpecificationReader().getRandomInputInForms()); this.candidateExtractor = new CandidateElementExtractor(controller.getElementChecker(), this.getBrowser(), formHandler, configurationReader.getCrawlSpecificationReader()); /** * go back into the previous state. */ try { this.goBackExact(); } catch (CrawljaxException e) { LOGGER.error("Failed to backtrack", e); } } /** * Terminate and clean up this Crawler, release the acquired browser. Notice that other Crawlers * might still be active. So this function does NOT shutdown all Crawlers active that should be * done with {@link CrawlerExecutor#shutdown()} */ public void shutdown() { controller.getBrowserPool().freeBrowser(this.getBrowser()); } /** * The main function stated by the ExecutorService. Crawlers add themselves to the list by * calling {@link CrawlQueueManager#addWorkToQueue(Crawler)}. When the ExecutorService finds a * free thread this method is called and when this method ends the Thread is released again and * a new Thread is started * * @see java.util.concurrent.Executors#newFixedThreadPool(int) * @see java.util.concurrent.ExecutorService */ @Override public void run() { if (!checkConstraints()) { // Constrains are not met at start of this Crawler, so stop immediately return; } if (backTrackPath.last() != null) { try { if (!backTrackPath.last().getTargetStateVertix().startWorking(this)) { return; } } catch (CrawljaxException e) { LOGGER.error("Received Crawljax exception", e); } } try { /** * Init the Crawler */ try { this.init(); } catch (InterruptedException e) { if (this.getBrowser() == null) { return; } } /** * Hand over the main crawling */ if (!this.crawl()) { controller.terminate(false); } /** * Crawling is done; so the crawlPath of the current branch is known */ if (!fired) { controller.getSession().removeCrawlPath(); } } catch (BrowserConnectionException e) { // The connection of the browser has gone down, most of the times it means that the // browser process has crashed. LOGGER.error("Crawler failed because the used browser died during Crawling", new CrawlPathToException("Crawler failed due to browser crash", controller .getSession().getCurrentCrawlPath(), e)); // removeBrowser will throw a RuntimeException if the current browser is the last // browser in the pool. this.controller.getBrowserPool().removeBrowser(this.getBrowser(), this.controller.getCrawlQueueManager()); return; } catch (CrawljaxException e) { LOGGER.error("Crawl failed!", e); } /** * At last failure or non shutdown the Crawler. */ this.shutdown(); } /** * Return the browser used in this Crawler Thread. * * @return the browser used in this Crawler Thread */ public EmbeddedBrowser getBrowser() { return browser; } @Override public String toString() { return this.name; } /** * @return the state machine. */ public StateMachine getStateMachine() { return stateMachine; } /** * Test to see if the (new) DOM is changed with regards to the old DOM. This method is Thread * safe. * * @param stateBefore * the state before the event. * @param stateAfter * the state after the event. * @return true if the state is changed according to the compare method of the oracle. */ private boolean isDomChanged(final StateVertix stateBefore, final StateVertix stateAfter) { boolean isChanged = false; // do not need Oracle Comparators now, because hash of stripped dom is // already calculated // isChanged = !stateComparator.compare(stateBefore.getDom(), // stateAfter.getDom(), browser); isChanged = !stateAfter.equals(stateBefore); if (isChanged) { LOGGER.info("Dom is Changed!"); } else { LOGGER.info("Dom Not Changed!"); } return isChanged; } /** * Checks the state and time constraints. This function is nearly Thread-safe. * * @return true if all conditions are met. */ private boolean checkConstraints() { long timePassed = System.currentTimeMillis() - controller.getSession().getStartTime(); int maxCrawlTime = configurationReader.getCrawlSpecificationReader().getMaximumRunTime(); if ((maxCrawlTime != 0) && (timePassed > maxCrawlTime * ONE_SECOND)) { LOGGER.info("Max time " + maxCrawlTime + " seconds passed!"); /* stop crawling */ return false; } StateFlowGraph graph = controller.getSession().getStateFlowGraph(); int maxNumberOfStates = configurationReader.getCrawlSpecificationReader().getMaxNumberOfStates(); if ((maxNumberOfStates != 0) && (graph.getAllStates().size() >= maxNumberOfStates)) { LOGGER.info("Max number of states " + maxNumberOfStates + " reached!"); /* stop crawling */ return false; } /* continue crawling */ return true; } }
package com.ctrip.ops.sysdev; import org.apache.commons.cli.*; import com.ctrip.ops.sysdev.inputs.BaseInput; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.DailyRollingFileAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import com.ctrip.ops.sysdev.configs.HangoutConfig; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public class Option { String flag, opt; public Option(String flag, String opt) { this.flag = flag; this.opt = opt; } } /** * parse the input command arguments * @param args * @return * @throws ParseException */ private static CommandLine parseArg(String[] args) throws ParseException { Options options = new Options(); options.addOption("h", false, "usage help"); options.addOption("help", false, "usage help"); options.addOption("f", true, "configuration file"); options.addOption("l", true, "log file"); options.addOption("w", true, "filter worker number"); options.addOption("v", false, "print info log"); options.addOption("vv", false, "print debug log"); options.addOption("vvvv", false, "print trace log"); CommandLineParser paraer = new BasicParser(); CommandLine cmdLine = paraer.parse(options, args); if (cmdLine.hasOption("help") || cmdLine.hasOption("h")) { usage(); System.exit(-1); } if(!cmdLine.hasOption("f")) { throw new ParseException("Required -f argument to specify config file"); } return cmdLine; } /** * print help information */ private static void usage() { StringBuilder helpInfo = new StringBuilder(); helpInfo.append("-h").append("\t\t\thelp command").append("\n") .append("-help").append("\t\t\thelp command").append("\n") .append("-f").append("\t\t\trequired config, indicate config file").append("\n") .append("-l").append("\t\t\tlog file that store the output").append("\n") .append("-w").append("\t\t\tfilter worker numbers").append("\n") .append("-v").append("\t\t\tprint info log").append("\n") .append("-vv").append("\t\t\tprint debug log").append("\n") .append("-vvvv").append("\t\t\tprint trace log").append("\n"); System.out.println(helpInfo.toString()); } public static void main(String[] args) { CommandLine cmdLine = null; try { cmdLine = parseArg(args); } catch (ParseException e) { System.out.println(e.getMessage()); System.exit(-1); } setupLogger(cmdLine); // parse configure file Map configs = null; try { configs = HangoutConfig.parse(cmdLine.getOptionValue("f")); } catch (IOException e) { e.printStackTrace(); } logger.debug(configs); // for input in all_inputs ArrayList<Map> inputs = (ArrayList<Map>) configs.get("inputs"); for (Map input : inputs) { Iterator<Entry<String, Map>> inputIT = input.entrySet().iterator(); while (inputIT.hasNext()) { Map.Entry<String, Map> inputEntry = inputIT.next(); String inputType = inputEntry.getKey(); Map inputConfig = inputEntry.getValue(); Class<?> inputClass = null; try { inputClass = Class .forName("com.ctrip.ops.sysdev.inputs." + inputType); Constructor<?> ctor = inputClass.getConstructor(Map.class, ArrayList.class, ArrayList.class); BaseInput inputInstance = (BaseInput) ctor.newInstance( inputConfig, configs.get("filters"), configs.get("outputs")); inputInstance.emit(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } /** * Setup logger according arguments * @param cmdLine */ private static void setupLogger(CommandLine cmdLine) { if (cmdLine.hasOption("l")) { DailyRollingFileAppender fa = new DailyRollingFileAppender(); fa.setName("FileLogger"); fa.setFile(cmdLine.getOptionValue("l")); fa.setLayout(new PatternLayout("%d %p %C %t %m%n")); if (cmdLine.hasOption("vvvv")) { fa.setThreshold(Level.TRACE); Logger.getRootLogger().setLevel(Level.TRACE); } else if (cmdLine.hasOption("vv")) { fa.setThreshold(Level.DEBUG); } else if (cmdLine.hasOption("v")) { fa.setThreshold(Level.INFO); } else { fa.setThreshold(Level.WARN); } fa.setAppend(true); fa.activateOptions(); Logger.getRootLogger().addAppender(fa); } else { ConsoleAppender console = new ConsoleAppender(); String PATTERN = "%d %p %C %t %m%n"; console.setLayout(new PatternLayout(PATTERN)); if (cmdLine.hasOption("vvvv")) { console.setThreshold(Level.TRACE); Logger.getRootLogger().setLevel(Level.TRACE); } else if (cmdLine.hasOption("vv")) { console.setThreshold(Level.DEBUG); } else if (cmdLine.hasOption("v")) { console.setThreshold(Level.INFO); } else { console.setThreshold(Level.WARN); } console.activateOptions(); Logger.getRootLogger().addAppender(console); } } }
package com.github.nwillc.opa; import com.github.nwillc.opa.query.Query; import java.util.Optional; import java.util.stream.Stream; /** * A simplistic data access object interface. Supporting create/update, deletion and retrieval. * * @param <K> the type of the key for the persisted type * @param <T> the type being persisted */ public interface Dao<K, T extends HasKey<K>> { /** * Find an object based on the key. * * @param key the key to search for * @return an optional holding the object if found */ Optional<T> findOne(final K key); /** * Return a stream of the objects * * @return stream of objects */ Stream<T> findAll(); /** * Find the objects matching a query. * * @param query the query to base the search on * @return a stream of any objects that match */ Stream<T> find(Query<T> query); /** * Save the object, create it or update if it exists. * * @param entity the enity to save or update */ void save(final T entity); /** * Delete an based on its key. * * @param key the key of the object to delete */ void delete(final K key); default Transaction createTransaction() { return null; } default void commit(Integer transactionId) {} default void rollback(Integer transactionId) {} }
package com.jcabi.github; import com.google.common.base.Optional; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import java.io.IOException; import java.net.URL; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import lombok.ToString; @Immutable @SuppressWarnings("PMD.TooManyMethods") public interface Statuses extends JsonReadable { /** * Associated commit. * @return Commit */ @NotNull(message = "commit is never NULL") Commit commit(); Status create( @NotNull(message = "status creation data can't be NULL") final StatusCreate status ) throws IOException; @NotNull(message = "iterable of statuses is never NULL") Iterable<Status> list( @NotNull(message = "ref can't be NULL") final String ref ); /** * Smart commit. */ @Immutable @ToString @Loggable(Loggable.DEBUG) @EqualsAndHashCode(of = { "statuses", "jsn" }) final class Smart implements Statuses { /** * Encapsulated status. */ private final transient Statuses statuses; /** * SmartJson object for convenient JSON parsing. */ private final transient SmartJson jsn; /** * Public ctor. * @param stats Status */ public Smart( @NotNull(message = "statuses can't be NULL") final Statuses stats ) { this.statuses = stats; this.jsn = new SmartJson(this.statuses); } /** * Get its message. * @return Message of commit * @throws IOException If there is any I/O problem */ @NotNull(message = "message is never NULL") public String message() throws IOException { return this.jsn.text("message"); } /** * Get its URL. * @return URL of comment * @throws IOException If there is any I/O problem */ @NotNull(message = "URL is never NULL") public URL url() throws IOException { return new URL(this.jsn.text("url")); } @Override @NotNull(message = "commit is never NULL") public Commit commit() { return this.statuses.commit(); } @Override public Status create( @NotNull(message = "status can't be NULL") final StatusCreate status ) throws IOException { return this.statuses.create(status); } @Override public Iterable<Status> list( @NotNull(message = "ref can't be NULL") final String ref ) { return this.statuses.list(ref); } @Override @NotNull(message = "JSON is never NULL") public JsonObject json() throws IOException { return this.statuses.json(); } } @ToString @Loggable(Loggable.DEBUG) @EqualsAndHashCode(of = { "state", "description", "context", "targeturl" }) final class StatusCreate implements JsonReadable { /** * State. */ private final transient Status.State state; /** * Description. */ private final transient String description; /** * Context string. */ private final transient Optional<String> context; /** * Target URL. */ private final transient Optional<String> targeturl; /** * Public ctor. * @param stat State */ public StatusCreate( @NotNull(message = "state can't be NULL") final Status.State stat ) { this( stat, "", Optional.<String>absent(), Optional.<String>absent() ); } /** * Private ctor. * @param stat State * @param desc Description * @param cntxt Context * @param target Target URL * @checkstyle ParameterNumberCheck (10 lines) */ private StatusCreate( @NotNull(message = "state can't be NULL") final Status.State stat, @NotNull(message = "description can't be NULL") final String desc, @NotNull(message = "context optional itself can't be NULL") final Optional<String> cntxt, @NotNull(message = "target URL optional itself can't be NULL") final Optional<String> target ) { this.state = stat; this.description = desc; this.context = cntxt; this.targeturl = target; } /** * Returns a StatusCreate with the given state. * @param stat State * @return StatusCreate */ public StatusCreate withState(final Status.State stat) { return new StatusCreate( stat, this.description, this.context, this.targeturl ); } /** * Returns a StatusCreate with the given description. * @param desc Description * @return StatusCreate */ public StatusCreate withDescription(final String desc) { return new StatusCreate( this.state, desc, this.context, this.targeturl ); } /** * Returns a StatusCreate with the given context. * @param cntxt Context * @return StatusCreate */ public StatusCreate withContext(final Optional<String> cntxt) { return new StatusCreate( this.state, this.description, cntxt, this.targeturl ); } /** * Returns a StatusCreate with the given target URL. * @param target Target URL * @return StatusCreate */ public StatusCreate withTargetUrl(final Optional<String> target) { return new StatusCreate( this.state, this.description, this.context, target ); } @Override @NotNull(message = "JSON is never NULL") public JsonObject json() { final JsonObjectBuilder builder = Json.createObjectBuilder() .add("state", this.state.identifier()) .add("description", this.description); if (this.context.isPresent()) { builder.add("context", this.context.get()); } if (this.targeturl.isPresent()) { builder.add("target_url", this.targeturl.get()); } return builder.build(); } } }
package com.justjournal.db; import org.apache.cayenne.Cayenne; import org.apache.cayenne.ObjectContext; import org.apache.cayenne.access.DataContext; import org.apache.log4j.Logger; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collection; /** * Tag management * @author Lucas Holt */ final public class TagDao { private static final Logger log = Logger.getLogger(TagDao.class); /** * Get a single tag by id * @param id tag id * @return tag */ public static Tag viewSingle(int id) { Tag tag = null; try { ObjectContext dataContext = DataContext.getThreadObjectContext(); com.justjournal.model.Tags tagItem = Cayenne.objectForPK(dataContext, com.justjournal.model.Tags.class, id); tag = new Tag(id, tagItem.getName()); tag.setCount(tagItem.getTagsToEntryList().size()); } catch (Exception e1) { log.error(e1); } return tag; } /** * List all tags * @return tag collection */ public static Collection<Tag> list() { Collection<Tag> tags = new ArrayList<Tag>(); try { // TODO: Convert to Cayenne ResultSet rs = SQLHelper.executeResultSet("select tags.id, tags.name as name, count(*) as count from entry_tags, tags where tags.id=entry_tags.tagid GROUP by tags.name;"); while (rs.next()) { Tag tag = new Tag(rs.getInt(1), rs.getString(2)); tag.setCount(rs.getInt(3)); tags.add(tag); } rs.close(); } catch (Exception ex) { log.error(ex); } return tags; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-01-13"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-10-19"); this.setApiVersion("18.16.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param language language */ public void setLanguage(String language){ this.requestConfiguration.put("language", language); } /** * language * * @return String */ public String getLanguage(){ if(this.requestConfiguration.containsKey("language")){ return(String) this.requestConfiguration.get("language"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-01-14"); this.setApiVersion("17.18.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }